babylon.max.js 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = Vector3.Normalize(axis1);
  870. var w = Vector3.Normalize(axis3);
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross;
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1;
  890. var v1;
  891. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  892. z = 1.0;
  893. }
  894. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  895. x = 1.0;
  896. }
  897. else {
  898. t = w.z / w.x;
  899. x = -t * Math.sqrt(1 / (1 + t * t));
  900. z = Math.sqrt(1 / (1 + t * t));
  901. }
  902. u1 = new Vector3(x, y, z);
  903. u1.normalize();
  904. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  905. v1.normalize();
  906. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  907. cross.normalize();
  908. if (Vector3.Dot(w, cross) < 0) {
  909. sign = 1.0;
  910. }
  911. dot = Vector3.Dot(u, u1);
  912. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  913. roll = Math.acos(dot) * sign;
  914. if (Vector3.Dot(u1, X) < 0) {
  915. roll = Math.PI + roll;
  916. u1 = u1.scaleInPlace(-1);
  917. v1 = v1.scaleInPlace(-1);
  918. nbRevert++;
  919. }
  920. // step 2 : rotate around u1
  921. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  922. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  923. var w2;
  924. var v2;
  925. x = 0.0;
  926. y = 0.0;
  927. z = 0.0;
  928. sign = -1;
  929. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  930. x = 1.0;
  931. }
  932. else {
  933. t = u1.z / u1.x;
  934. x = -t * Math.sqrt(1 / (1 + t * t));
  935. z = Math.sqrt(1 / (1 + t * t));
  936. }
  937. w2 = new Vector3(x, y, z);
  938. w2.normalize();
  939. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. v2 = v2.scaleInPlace(-1);
  952. w2 = w2.scaleInPlace(-1);
  953. nbRevert++;
  954. }
  955. // step 3 : rotate around v2
  956. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  957. sign = -1;
  958. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  959. cross.normalize();
  960. if (Vector3.Dot(cross, Y) < 0) {
  961. sign = 1.0;
  962. }
  963. dot = Vector3.Dot(u1, X);
  964. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  965. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  966. if (dot < 0 && nbRevert < 2) {
  967. yaw = Math.PI + yaw;
  968. }
  969. ref.x = pitch;
  970. ref.y = yaw;
  971. ref.z = roll;
  972. };
  973. return Vector3;
  974. })();
  975. BABYLON.Vector3 = Vector3;
  976. //Vector4 class created for EulerAngle class conversion to Quaternion
  977. var Vector4 = (function () {
  978. function Vector4(x, y, z, w) {
  979. this.x = x;
  980. this.y = y;
  981. this.z = z;
  982. this.w = w;
  983. }
  984. Vector4.prototype.toString = function () {
  985. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  986. };
  987. // Operators
  988. Vector4.prototype.asArray = function () {
  989. var result = [];
  990. this.toArray(result, 0);
  991. return result;
  992. };
  993. Vector4.prototype.toArray = function (array, index) {
  994. if (index === undefined) {
  995. index = 0;
  996. }
  997. array[index] = this.x;
  998. array[index + 1] = this.y;
  999. array[index + 2] = this.z;
  1000. array[index + 3] = this.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.addInPlace = function (otherVector) {
  1004. this.x += otherVector.x;
  1005. this.y += otherVector.y;
  1006. this.z += otherVector.z;
  1007. this.w += otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.add = function (otherVector) {
  1011. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1012. };
  1013. Vector4.prototype.addToRef = function (otherVector, result) {
  1014. result.x = this.x + otherVector.x;
  1015. result.y = this.y + otherVector.y;
  1016. result.z = this.z + otherVector.z;
  1017. result.w = this.w + otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractInPlace = function (otherVector) {
  1021. this.x -= otherVector.x;
  1022. this.y -= otherVector.y;
  1023. this.z -= otherVector.z;
  1024. this.w -= otherVector.w;
  1025. return this;
  1026. };
  1027. Vector4.prototype.subtract = function (otherVector) {
  1028. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1029. };
  1030. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1031. result.x = this.x - otherVector.x;
  1032. result.y = this.y - otherVector.y;
  1033. result.z = this.z - otherVector.z;
  1034. result.w = this.w - otherVector.w;
  1035. return this;
  1036. };
  1037. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1038. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1039. };
  1040. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1041. result.x = this.x - x;
  1042. result.y = this.y - y;
  1043. result.z = this.z - z;
  1044. result.w = this.w - w;
  1045. return this;
  1046. };
  1047. Vector4.prototype.negate = function () {
  1048. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1049. };
  1050. Vector4.prototype.scaleInPlace = function (scale) {
  1051. this.x *= scale;
  1052. this.y *= scale;
  1053. this.z *= scale;
  1054. this.w *= scale;
  1055. return this;
  1056. };
  1057. Vector4.prototype.scale = function (scale) {
  1058. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1059. };
  1060. Vector4.prototype.scaleToRef = function (scale, result) {
  1061. result.x = this.x * scale;
  1062. result.y = this.y * scale;
  1063. result.z = this.z * scale;
  1064. result.w = this.w * scale;
  1065. };
  1066. Vector4.prototype.equals = function (otherVector) {
  1067. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1068. };
  1069. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1070. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1071. return otherVector
  1072. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1074. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1075. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1076. };
  1077. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1078. return this.x === x && this.y === y && this.z === z && this.w === w;
  1079. };
  1080. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1081. this.x *= otherVector.x;
  1082. this.y *= otherVector.y;
  1083. this.z *= otherVector.z;
  1084. this.w *= otherVector.w;
  1085. return this;
  1086. };
  1087. Vector4.prototype.multiply = function (otherVector) {
  1088. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1089. };
  1090. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1091. result.x = this.x * otherVector.x;
  1092. result.y = this.y * otherVector.y;
  1093. result.z = this.z * otherVector.z;
  1094. result.w = this.w * otherVector.w;
  1095. return this;
  1096. };
  1097. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1098. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1099. };
  1100. Vector4.prototype.divide = function (otherVector) {
  1101. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1102. };
  1103. Vector4.prototype.divideToRef = function (otherVector, result) {
  1104. result.x = this.x / otherVector.x;
  1105. result.y = this.y / otherVector.y;
  1106. result.z = this.z / otherVector.z;
  1107. result.w = this.w / otherVector.w;
  1108. return this;
  1109. };
  1110. Vector4.prototype.MinimizeInPlace = function (other) {
  1111. if (other.x < this.x)
  1112. this.x = other.x;
  1113. if (other.y < this.y)
  1114. this.y = other.y;
  1115. if (other.z < this.z)
  1116. this.z = other.z;
  1117. if (other.w < this.w)
  1118. this.w = other.w;
  1119. return this;
  1120. };
  1121. Vector4.prototype.MaximizeInPlace = function (other) {
  1122. if (other.x > this.x)
  1123. this.x = other.x;
  1124. if (other.y > this.y)
  1125. this.y = other.y;
  1126. if (other.z > this.z)
  1127. this.z = other.z;
  1128. if (other.w > this.w)
  1129. this.w = other.w;
  1130. return this;
  1131. };
  1132. // Properties
  1133. Vector4.prototype.length = function () {
  1134. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1135. };
  1136. Vector4.prototype.lengthSquared = function () {
  1137. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1138. };
  1139. // Methods
  1140. Vector4.prototype.normalize = function () {
  1141. var len = this.length();
  1142. if (len === 0)
  1143. return this;
  1144. var num = 1.0 / len;
  1145. this.x *= num;
  1146. this.y *= num;
  1147. this.z *= num;
  1148. this.w *= num;
  1149. return this;
  1150. };
  1151. Vector4.prototype.clone = function () {
  1152. return new Vector4(this.x, this.y, this.z, this.w);
  1153. };
  1154. Vector4.prototype.copyFrom = function (source) {
  1155. this.x = source.x;
  1156. this.y = source.y;
  1157. this.z = source.z;
  1158. this.w = source.w;
  1159. return this;
  1160. };
  1161. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1162. this.x = x;
  1163. this.y = y;
  1164. this.z = z;
  1165. this.w = w;
  1166. return this;
  1167. };
  1168. // Statics
  1169. Vector4.FromArray = function (array, offset) {
  1170. if (!offset) {
  1171. offset = 0;
  1172. }
  1173. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1174. };
  1175. Vector4.FromArrayToRef = function (array, offset, result) {
  1176. result.x = array[offset];
  1177. result.y = array[offset + 1];
  1178. result.z = array[offset + 2];
  1179. result.w = array[offset + 3];
  1180. };
  1181. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1182. result.x = array[offset];
  1183. result.y = array[offset + 1];
  1184. result.z = array[offset + 2];
  1185. result.w = array[offset + 3];
  1186. };
  1187. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1188. result.x = x;
  1189. result.y = y;
  1190. result.z = z;
  1191. result.w = w;
  1192. };
  1193. Vector4.Zero = function () {
  1194. return new Vector4(0, 0, 0, 0);
  1195. };
  1196. Vector4.Normalize = function (vector) {
  1197. var result = Vector4.Zero();
  1198. Vector4.NormalizeToRef(vector, result);
  1199. return result;
  1200. };
  1201. Vector4.NormalizeToRef = function (vector, result) {
  1202. result.copyFrom(vector);
  1203. result.normalize();
  1204. };
  1205. Vector4.Minimize = function (left, right) {
  1206. var min = left.clone();
  1207. min.MinimizeInPlace(right);
  1208. return min;
  1209. };
  1210. Vector4.Maximize = function (left, right) {
  1211. var max = left.clone();
  1212. max.MaximizeInPlace(right);
  1213. return max;
  1214. };
  1215. Vector4.Distance = function (value1, value2) {
  1216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1217. };
  1218. Vector4.DistanceSquared = function (value1, value2) {
  1219. var x = value1.x - value2.x;
  1220. var y = value1.y - value2.y;
  1221. var z = value1.z - value2.z;
  1222. var w = value1.w - value2.w;
  1223. return (x * x) + (y * y) + (z * z) + (w * w);
  1224. };
  1225. Vector4.Center = function (value1, value2) {
  1226. var center = value1.add(value2);
  1227. center.scaleInPlace(0.5);
  1228. return center;
  1229. };
  1230. return Vector4;
  1231. })();
  1232. BABYLON.Vector4 = Vector4;
  1233. var Quaternion = (function () {
  1234. function Quaternion(x, y, z, w) {
  1235. if (x === void 0) { x = 0; }
  1236. if (y === void 0) { y = 0; }
  1237. if (z === void 0) { z = 0; }
  1238. if (w === void 0) { w = 1; }
  1239. this.x = x;
  1240. this.y = y;
  1241. this.z = z;
  1242. this.w = w;
  1243. }
  1244. Quaternion.prototype.toString = function () {
  1245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1246. };
  1247. Quaternion.prototype.asArray = function () {
  1248. return [this.x, this.y, this.z, this.w];
  1249. };
  1250. Quaternion.prototype.equals = function (otherQuaternion) {
  1251. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1252. };
  1253. Quaternion.prototype.clone = function () {
  1254. return new Quaternion(this.x, this.y, this.z, this.w);
  1255. };
  1256. Quaternion.prototype.copyFrom = function (other) {
  1257. this.x = other.x;
  1258. this.y = other.y;
  1259. this.z = other.z;
  1260. this.w = other.w;
  1261. return this;
  1262. };
  1263. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1264. this.x = x;
  1265. this.y = y;
  1266. this.z = z;
  1267. this.w = w;
  1268. return this;
  1269. };
  1270. Quaternion.prototype.add = function (other) {
  1271. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1272. };
  1273. Quaternion.prototype.subtract = function (other) {
  1274. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1275. };
  1276. Quaternion.prototype.scale = function (value) {
  1277. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1278. };
  1279. Quaternion.prototype.multiply = function (q1) {
  1280. var result = new Quaternion(0, 0, 0, 1.0);
  1281. this.multiplyToRef(q1, result);
  1282. return result;
  1283. };
  1284. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1285. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1286. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1287. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1288. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1289. result.copyFromFloats(x, y, z, w);
  1290. return this;
  1291. };
  1292. Quaternion.prototype.multiplyInPlace = function (q1) {
  1293. this.multiplyToRef(q1, this);
  1294. return this;
  1295. };
  1296. Quaternion.prototype.length = function () {
  1297. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1298. };
  1299. Quaternion.prototype.normalize = function () {
  1300. var length = 1.0 / this.length();
  1301. this.x *= length;
  1302. this.y *= length;
  1303. this.z *= length;
  1304. this.w *= length;
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toEulerAngles = function () {
  1308. var result = Vector3.Zero();
  1309. this.toEulerAnglesToRef(result);
  1310. return result;
  1311. };
  1312. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1313. //result is an EulerAngles in the in the z-x-z convention
  1314. var qx = this.x;
  1315. var qy = this.y;
  1316. var qz = this.z;
  1317. var qw = this.w;
  1318. var qxy = qx * qy;
  1319. var qxz = qx * qz;
  1320. var qwy = qw * qy;
  1321. var qwz = qw * qz;
  1322. var qwx = qw * qx;
  1323. var qyz = qy * qz;
  1324. var sqx = qx * qx;
  1325. var sqy = qy * qy;
  1326. var determinant = sqx + sqy;
  1327. if (determinant !== 0.000 && determinant !== 1.000) {
  1328. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1329. result.y = Math.acos(1 - 2 * determinant);
  1330. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1331. }
  1332. else {
  1333. if (determinant === 0.0) {
  1334. result.x = 0.0;
  1335. result.y = 0.0;
  1336. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1337. }
  1338. else {
  1339. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1340. result.y = Math.PI;
  1341. result.z = 0.0;
  1342. }
  1343. }
  1344. return this;
  1345. };
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. return Viewport;
  2244. })();
  2245. BABYLON.Viewport = Viewport;
  2246. var Frustum = (function () {
  2247. function Frustum() {
  2248. }
  2249. Frustum.GetPlanes = function (transform) {
  2250. var frustumPlanes = [];
  2251. for (var index = 0; index < 6; index++) {
  2252. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2253. }
  2254. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2255. return frustumPlanes;
  2256. };
  2257. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2258. // Near
  2259. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2260. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2261. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2262. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2263. frustumPlanes[0].normalize();
  2264. // Far
  2265. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2266. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2267. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2268. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2269. frustumPlanes[1].normalize();
  2270. // Left
  2271. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2272. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2273. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2274. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2275. frustumPlanes[2].normalize();
  2276. // Right
  2277. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2278. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2279. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2280. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2281. frustumPlanes[3].normalize();
  2282. // Top
  2283. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2284. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2285. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2286. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2287. frustumPlanes[4].normalize();
  2288. // Bottom
  2289. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2290. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2291. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2292. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2293. frustumPlanes[5].normalize();
  2294. };
  2295. return Frustum;
  2296. })();
  2297. BABYLON.Frustum = Frustum;
  2298. var Ray = (function () {
  2299. function Ray(origin, direction, length) {
  2300. if (length === void 0) { length = Number.MAX_VALUE; }
  2301. this.origin = origin;
  2302. this.direction = direction;
  2303. this.length = length;
  2304. }
  2305. // Methods
  2306. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2307. var d = 0.0;
  2308. var maxValue = Number.MAX_VALUE;
  2309. var inv;
  2310. var min;
  2311. var max;
  2312. var temp;
  2313. if (Math.abs(this.direction.x) < 0.0000001) {
  2314. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2315. return false;
  2316. }
  2317. }
  2318. else {
  2319. inv = 1.0 / this.direction.x;
  2320. min = (minimum.x - this.origin.x) * inv;
  2321. max = (maximum.x - this.origin.x) * inv;
  2322. if (max === -Infinity) {
  2323. max = Infinity;
  2324. }
  2325. if (min > max) {
  2326. temp = min;
  2327. min = max;
  2328. max = temp;
  2329. }
  2330. d = Math.max(min, d);
  2331. maxValue = Math.min(max, maxValue);
  2332. if (d > maxValue) {
  2333. return false;
  2334. }
  2335. }
  2336. if (Math.abs(this.direction.y) < 0.0000001) {
  2337. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2338. return false;
  2339. }
  2340. }
  2341. else {
  2342. inv = 1.0 / this.direction.y;
  2343. min = (minimum.y - this.origin.y) * inv;
  2344. max = (maximum.y - this.origin.y) * inv;
  2345. if (max === -Infinity) {
  2346. max = Infinity;
  2347. }
  2348. if (min > max) {
  2349. temp = min;
  2350. min = max;
  2351. max = temp;
  2352. }
  2353. d = Math.max(min, d);
  2354. maxValue = Math.min(max, maxValue);
  2355. if (d > maxValue) {
  2356. return false;
  2357. }
  2358. }
  2359. if (Math.abs(this.direction.z) < 0.0000001) {
  2360. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2361. return false;
  2362. }
  2363. }
  2364. else {
  2365. inv = 1.0 / this.direction.z;
  2366. min = (minimum.z - this.origin.z) * inv;
  2367. max = (maximum.z - this.origin.z) * inv;
  2368. if (max === -Infinity) {
  2369. max = Infinity;
  2370. }
  2371. if (min > max) {
  2372. temp = min;
  2373. min = max;
  2374. max = temp;
  2375. }
  2376. d = Math.max(min, d);
  2377. maxValue = Math.min(max, maxValue);
  2378. if (d > maxValue) {
  2379. return false;
  2380. }
  2381. }
  2382. return true;
  2383. };
  2384. Ray.prototype.intersectsBox = function (box) {
  2385. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2386. };
  2387. Ray.prototype.intersectsSphere = function (sphere) {
  2388. var x = sphere.center.x - this.origin.x;
  2389. var y = sphere.center.y - this.origin.y;
  2390. var z = sphere.center.z - this.origin.z;
  2391. var pyth = (x * x) + (y * y) + (z * z);
  2392. var rr = sphere.radius * sphere.radius;
  2393. if (pyth <= rr) {
  2394. return true;
  2395. }
  2396. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2397. if (dot < 0.0) {
  2398. return false;
  2399. }
  2400. var temp = pyth - (dot * dot);
  2401. return temp <= rr;
  2402. };
  2403. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2404. if (!this._edge1) {
  2405. this._edge1 = Vector3.Zero();
  2406. this._edge2 = Vector3.Zero();
  2407. this._pvec = Vector3.Zero();
  2408. this._tvec = Vector3.Zero();
  2409. this._qvec = Vector3.Zero();
  2410. }
  2411. vertex1.subtractToRef(vertex0, this._edge1);
  2412. vertex2.subtractToRef(vertex0, this._edge2);
  2413. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2414. var det = Vector3.Dot(this._edge1, this._pvec);
  2415. if (det === 0) {
  2416. return null;
  2417. }
  2418. var invdet = 1 / det;
  2419. this.origin.subtractToRef(vertex0, this._tvec);
  2420. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2421. if (bu < 0 || bu > 1.0) {
  2422. return null;
  2423. }
  2424. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2425. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2426. if (bv < 0 || bu + bv > 1.0) {
  2427. return null;
  2428. }
  2429. //check if the distance is longer than the predefined length.
  2430. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2431. if (distance > this.length) {
  2432. return null;
  2433. }
  2434. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2435. };
  2436. // Statics
  2437. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2438. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2439. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2440. var direction = end.subtract(start);
  2441. direction.normalize();
  2442. return new Ray(start, direction);
  2443. };
  2444. /**
  2445. * 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
  2446. * transformed to the given world matrix.
  2447. * @param origin The origin point
  2448. * @param end The end point
  2449. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2450. */
  2451. Ray.CreateNewFromTo = function (origin, end, world) {
  2452. if (world === void 0) { world = Matrix.Identity(); }
  2453. var direction = end.subtract(origin);
  2454. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2455. direction.normalize();
  2456. return Ray.Transform(new Ray(origin, direction, length), world);
  2457. };
  2458. Ray.Transform = function (ray, matrix) {
  2459. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2460. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2461. return new Ray(newOrigin, newDirection, ray.length);
  2462. };
  2463. return Ray;
  2464. })();
  2465. BABYLON.Ray = Ray;
  2466. (function (Space) {
  2467. Space[Space["LOCAL"] = 0] = "LOCAL";
  2468. Space[Space["WORLD"] = 1] = "WORLD";
  2469. })(BABYLON.Space || (BABYLON.Space = {}));
  2470. var Space = BABYLON.Space;
  2471. var Axis = (function () {
  2472. function Axis() {
  2473. }
  2474. Axis.X = new Vector3(1, 0, 0);
  2475. Axis.Y = new Vector3(0, 1, 0);
  2476. Axis.Z = new Vector3(0, 0, 1);
  2477. return Axis;
  2478. })();
  2479. BABYLON.Axis = Axis;
  2480. ;
  2481. var BezierCurve = (function () {
  2482. function BezierCurve() {
  2483. }
  2484. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2485. // Extract X (which is equal to time here)
  2486. var f0 = 1 - 3 * x2 + 3 * x1;
  2487. var f1 = 3 * x2 - 6 * x1;
  2488. var f2 = 3 * x1;
  2489. var refinedT = t;
  2490. for (var i = 0; i < 5; i++) {
  2491. var refinedT2 = refinedT * refinedT;
  2492. var refinedT3 = refinedT2 * refinedT;
  2493. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2494. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2495. refinedT -= (x - t) * slope;
  2496. refinedT = Math.min(1, Math.max(0, refinedT));
  2497. }
  2498. // Resolve cubic bezier for the given x
  2499. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2500. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2501. Math.pow(refinedT, 3);
  2502. };
  2503. return BezierCurve;
  2504. })();
  2505. BABYLON.BezierCurve = BezierCurve;
  2506. (function (Orientation) {
  2507. Orientation[Orientation["CW"] = 0] = "CW";
  2508. Orientation[Orientation["CCW"] = 1] = "CCW";
  2509. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2510. var Orientation = BABYLON.Orientation;
  2511. var Angle = (function () {
  2512. function Angle(radians) {
  2513. var _this = this;
  2514. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2515. this.radians = function () { return _this._radians; };
  2516. this._radians = radians;
  2517. if (this._radians < 0)
  2518. this._radians += (2 * Math.PI);
  2519. }
  2520. Angle.BetweenTwoPoints = function (a, b) {
  2521. var delta = b.subtract(a);
  2522. var theta = Math.atan2(delta.y, delta.x);
  2523. return new Angle(theta);
  2524. };
  2525. Angle.FromRadians = function (radians) {
  2526. return new Angle(radians);
  2527. };
  2528. Angle.FromDegrees = function (degrees) {
  2529. return new Angle(degrees * Math.PI / 180);
  2530. };
  2531. return Angle;
  2532. })();
  2533. BABYLON.Angle = Angle;
  2534. var Arc2 = (function () {
  2535. function Arc2(startPoint, midPoint, endPoint) {
  2536. this.startPoint = startPoint;
  2537. this.midPoint = midPoint;
  2538. this.endPoint = endPoint;
  2539. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2540. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2541. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2542. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2543. 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);
  2544. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2545. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2546. var a1 = this.startAngle.degrees();
  2547. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2548. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2549. // angles correction
  2550. if (a2 - a1 > +180.0)
  2551. a2 -= 360.0;
  2552. if (a2 - a1 < -180.0)
  2553. a2 += 360.0;
  2554. if (a3 - a2 > +180.0)
  2555. a3 -= 360.0;
  2556. if (a3 - a2 < -180.0)
  2557. a3 += 360.0;
  2558. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2559. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2560. }
  2561. return Arc2;
  2562. })();
  2563. BABYLON.Arc2 = Arc2;
  2564. var PathCursor = (function () {
  2565. function PathCursor(path) {
  2566. this.path = path;
  2567. this._onchange = new Array();
  2568. this.value = 0;
  2569. this.animations = new Array();
  2570. }
  2571. PathCursor.prototype.getPoint = function () {
  2572. var point = this.path.getPointAtLengthPosition(this.value);
  2573. return new Vector3(point.x, 0, point.y);
  2574. };
  2575. PathCursor.prototype.moveAhead = function (step) {
  2576. if (step === void 0) { step = 0.002; }
  2577. this.move(step);
  2578. return this;
  2579. };
  2580. PathCursor.prototype.moveBack = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(-step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.move = function (step) {
  2586. if (Math.abs(step) > 1) {
  2587. throw "step size should be less than 1.";
  2588. }
  2589. this.value += step;
  2590. this.ensureLimits();
  2591. this.raiseOnChange();
  2592. return this;
  2593. };
  2594. PathCursor.prototype.ensureLimits = function () {
  2595. while (this.value > 1) {
  2596. this.value -= 1;
  2597. }
  2598. while (this.value < 0) {
  2599. this.value += 1;
  2600. }
  2601. return this;
  2602. };
  2603. // used by animation engine
  2604. PathCursor.prototype.markAsDirty = function (propertyName) {
  2605. this.ensureLimits();
  2606. this.raiseOnChange();
  2607. return this;
  2608. };
  2609. PathCursor.prototype.raiseOnChange = function () {
  2610. var _this = this;
  2611. this._onchange.forEach(function (f) { return f(_this); });
  2612. return this;
  2613. };
  2614. PathCursor.prototype.onchange = function (f) {
  2615. this._onchange.push(f);
  2616. return this;
  2617. };
  2618. return PathCursor;
  2619. })();
  2620. BABYLON.PathCursor = PathCursor;
  2621. var Path2 = (function () {
  2622. function Path2(x, y) {
  2623. this._points = new Array();
  2624. this._length = 0;
  2625. this.closed = false;
  2626. this._points.push(new Vector2(x, y));
  2627. }
  2628. Path2.prototype.addLineTo = function (x, y) {
  2629. if (closed) {
  2630. BABYLON.Tools.Error("cannot add lines to closed paths");
  2631. return this;
  2632. }
  2633. var newPoint = new Vector2(x, y);
  2634. var previousPoint = this._points[this._points.length - 1];
  2635. this._points.push(newPoint);
  2636. this._length += newPoint.subtract(previousPoint).length();
  2637. return this;
  2638. };
  2639. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2640. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2641. if (closed) {
  2642. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2643. return this;
  2644. }
  2645. var startPoint = this._points[this._points.length - 1];
  2646. var midPoint = new Vector2(midX, midY);
  2647. var endPoint = new Vector2(endX, endY);
  2648. var arc = new Arc2(startPoint, midPoint, endPoint);
  2649. var increment = arc.angle.radians() / numberOfSegments;
  2650. if (arc.orientation === Orientation.CW)
  2651. increment *= -1;
  2652. var currentAngle = arc.startAngle.radians() + increment;
  2653. for (var i = 0; i < numberOfSegments; i++) {
  2654. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2655. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2656. this.addLineTo(x, y);
  2657. currentAngle += increment;
  2658. }
  2659. return this;
  2660. };
  2661. Path2.prototype.close = function () {
  2662. this.closed = true;
  2663. return this;
  2664. };
  2665. Path2.prototype.length = function () {
  2666. var result = this._length;
  2667. if (!this.closed) {
  2668. var lastPoint = this._points[this._points.length - 1];
  2669. var firstPoint = this._points[0];
  2670. result += (firstPoint.subtract(lastPoint).length());
  2671. }
  2672. return result;
  2673. };
  2674. Path2.prototype.getPoints = function () {
  2675. return this._points;
  2676. };
  2677. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2678. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2679. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2680. return Vector2.Zero();
  2681. }
  2682. var lengthPosition = normalizedLengthPosition * this.length();
  2683. var previousOffset = 0;
  2684. for (var i = 0; i < this._points.length; i++) {
  2685. var j = (i + 1) % this._points.length;
  2686. var a = this._points[i];
  2687. var b = this._points[j];
  2688. var bToA = b.subtract(a);
  2689. var nextOffset = (bToA.length() + previousOffset);
  2690. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2691. var dir = bToA.normalize();
  2692. var localOffset = lengthPosition - previousOffset;
  2693. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2694. }
  2695. previousOffset = nextOffset;
  2696. }
  2697. BABYLON.Tools.Error("internal error");
  2698. return Vector2.Zero();
  2699. };
  2700. Path2.StartingAt = function (x, y) {
  2701. return new Path2(x, y);
  2702. };
  2703. return Path2;
  2704. })();
  2705. BABYLON.Path2 = Path2;
  2706. var Path3D = (function () {
  2707. /**
  2708. * new Path3D(path, normal, raw)
  2709. * path : an array of Vector3, the curve axis of the Path3D
  2710. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2711. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2712. */
  2713. function Path3D(path, firstNormal, raw) {
  2714. this.path = path;
  2715. this._curve = new Array();
  2716. this._distances = new Array();
  2717. this._tangents = new Array();
  2718. this._normals = new Array();
  2719. this._binormals = new Array();
  2720. for (var p = 0; p < path.length; p++) {
  2721. this._curve[p] = path[p].clone(); // hard copy
  2722. }
  2723. this._raw = raw || false;
  2724. this._compute(firstNormal);
  2725. }
  2726. Path3D.prototype.getCurve = function () {
  2727. return this._curve;
  2728. };
  2729. Path3D.prototype.getTangents = function () {
  2730. return this._tangents;
  2731. };
  2732. Path3D.prototype.getNormals = function () {
  2733. return this._normals;
  2734. };
  2735. Path3D.prototype.getBinormals = function () {
  2736. return this._binormals;
  2737. };
  2738. Path3D.prototype.getDistances = function () {
  2739. return this._distances;
  2740. };
  2741. Path3D.prototype.update = function (path, firstNormal) {
  2742. for (var p = 0; p < path.length; p++) {
  2743. this._curve[p].x = path[p].x;
  2744. this._curve[p].y = path[p].y;
  2745. this._curve[p].z = path[p].z;
  2746. }
  2747. this._compute(firstNormal);
  2748. return this;
  2749. };
  2750. // private function compute() : computes tangents, normals and binormals
  2751. Path3D.prototype._compute = function (firstNormal) {
  2752. var l = this._curve.length;
  2753. // first and last tangents
  2754. this._tangents[0] = this._getFirstNonNullVector(0);
  2755. if (!this._raw) {
  2756. this._tangents[0].normalize();
  2757. }
  2758. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2759. if (!this._raw) {
  2760. this._tangents[l - 1].normalize();
  2761. }
  2762. // normals and binormals at first point : arbitrary vector with _normalVector()
  2763. var tg0 = this._tangents[0];
  2764. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2765. this._normals[0] = pp0;
  2766. if (!this._raw) {
  2767. this._normals[0].normalize();
  2768. }
  2769. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2770. if (!this._raw) {
  2771. this._binormals[0].normalize();
  2772. }
  2773. this._distances[0] = 0;
  2774. // normals and binormals : next points
  2775. var prev; // previous vector (segment)
  2776. var cur; // current vector (segment)
  2777. var curTang; // current tangent
  2778. // previous normal
  2779. var prevBinor; // previous binormal
  2780. for (var i = 1; i < l; i++) {
  2781. // tangents
  2782. prev = this._getLastNonNullVector(i);
  2783. if (i < l - 1) {
  2784. cur = this._getFirstNonNullVector(i);
  2785. this._tangents[i] = prev.add(cur);
  2786. this._tangents[i].normalize();
  2787. }
  2788. this._distances[i] = this._distances[i - 1] + prev.length();
  2789. // normals and binormals
  2790. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2791. curTang = this._tangents[i];
  2792. prevBinor = this._binormals[i - 1];
  2793. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2794. if (!this._raw) {
  2795. this._normals[i].normalize();
  2796. }
  2797. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2798. if (!this._raw) {
  2799. this._binormals[i].normalize();
  2800. }
  2801. }
  2802. };
  2803. // private function getFirstNonNullVector(index)
  2804. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2805. Path3D.prototype._getFirstNonNullVector = function (index) {
  2806. var i = 1;
  2807. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2808. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2809. i++;
  2810. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2811. }
  2812. return nNVector;
  2813. };
  2814. // private function getLastNonNullVector(index)
  2815. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2816. Path3D.prototype._getLastNonNullVector = function (index) {
  2817. var i = 1;
  2818. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2819. while (nLVector.length() === 0 && index > i + 1) {
  2820. i++;
  2821. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2822. }
  2823. return nLVector;
  2824. };
  2825. // private function normalVector(v0, vt, va) :
  2826. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2827. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2828. Path3D.prototype._normalVector = function (v0, vt, va) {
  2829. var normal0;
  2830. if (va === undefined || va === null) {
  2831. var point;
  2832. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2833. point = new Vector3(0, -1, 0);
  2834. }
  2835. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2836. point = new Vector3(1, 0, 0);
  2837. }
  2838. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2839. point = new Vector3(0, 0, 1);
  2840. }
  2841. normal0 = Vector3.Cross(vt, point);
  2842. }
  2843. else {
  2844. normal0 = Vector3.Cross(vt, va);
  2845. Vector3.CrossToRef(normal0, vt, normal0);
  2846. }
  2847. normal0.normalize();
  2848. return normal0;
  2849. };
  2850. return Path3D;
  2851. })();
  2852. BABYLON.Path3D = Path3D;
  2853. var Curve3 = (function () {
  2854. function Curve3(points) {
  2855. this._length = 0;
  2856. this._points = points;
  2857. this._length = this._computeLength(points);
  2858. }
  2859. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2860. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2861. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2862. var bez = new Array();
  2863. var equation = function (t, val0, val1, val2) {
  2864. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2865. return res;
  2866. };
  2867. for (var i = 0; i <= nbPoints; i++) {
  2868. 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)));
  2869. }
  2870. return new Curve3(bez);
  2871. };
  2872. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2873. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2874. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2875. var bez = new Array();
  2876. var equation = function (t, val0, val1, val2, val3) {
  2877. 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;
  2878. return res;
  2879. };
  2880. for (var i = 0; i <= nbPoints; i++) {
  2881. 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)));
  2882. }
  2883. return new Curve3(bez);
  2884. };
  2885. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2886. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2887. var hermite = new Array();
  2888. var step = 1 / nbPoints;
  2889. for (var i = 0; i <= nbPoints; i++) {
  2890. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2891. }
  2892. return new Curve3(hermite);
  2893. };
  2894. Curve3.prototype.getPoints = function () {
  2895. return this._points;
  2896. };
  2897. Curve3.prototype.length = function () {
  2898. return this._length;
  2899. };
  2900. Curve3.prototype.continue = function (curve) {
  2901. var lastPoint = this._points[this._points.length - 1];
  2902. var continuedPoints = this._points.slice();
  2903. var curvePoints = curve.getPoints();
  2904. for (var i = 1; i < curvePoints.length; i++) {
  2905. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2906. }
  2907. var continuedCurve = new Curve3(continuedPoints);
  2908. return continuedCurve;
  2909. };
  2910. Curve3.prototype._computeLength = function (path) {
  2911. var l = 0;
  2912. for (var i = 1; i < path.length; i++) {
  2913. l += (path[i].subtract(path[i - 1])).length();
  2914. }
  2915. return l;
  2916. };
  2917. return Curve3;
  2918. })();
  2919. BABYLON.Curve3 = Curve3;
  2920. // Vertex formats
  2921. var PositionNormalVertex = (function () {
  2922. function PositionNormalVertex(position, normal) {
  2923. if (position === void 0) { position = Vector3.Zero(); }
  2924. if (normal === void 0) { normal = Vector3.Up(); }
  2925. this.position = position;
  2926. this.normal = normal;
  2927. }
  2928. PositionNormalVertex.prototype.clone = function () {
  2929. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2930. };
  2931. return PositionNormalVertex;
  2932. })();
  2933. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2934. var PositionNormalTextureVertex = (function () {
  2935. function PositionNormalTextureVertex(position, normal, uv) {
  2936. if (position === void 0) { position = Vector3.Zero(); }
  2937. if (normal === void 0) { normal = Vector3.Up(); }
  2938. if (uv === void 0) { uv = Vector2.Zero(); }
  2939. this.position = position;
  2940. this.normal = normal;
  2941. this.uv = uv;
  2942. }
  2943. PositionNormalTextureVertex.prototype.clone = function () {
  2944. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2945. };
  2946. return PositionNormalTextureVertex;
  2947. })();
  2948. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. var Database = (function () {
  2953. function Database(urlToScene, callbackManifestChecked) {
  2954. // Handling various flavors of prefixed version of IndexedDB
  2955. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2956. this.callbackManifestChecked = callbackManifestChecked;
  2957. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2958. this.db = null;
  2959. this.enableSceneOffline = false;
  2960. this.enableTexturesOffline = false;
  2961. this.manifestVersionFound = 0;
  2962. this.mustUpdateRessources = false;
  2963. this.hasReachedQuota = false;
  2964. if (!Database.IDBStorageEnabled) {
  2965. this.callbackManifestChecked(true);
  2966. }
  2967. else {
  2968. this.checkManifestFile();
  2969. }
  2970. }
  2971. Database.prototype.checkManifestFile = function () {
  2972. var _this = this;
  2973. function noManifestFile() {
  2974. that.enableSceneOffline = false;
  2975. that.enableTexturesOffline = false;
  2976. that.callbackManifestChecked(false);
  2977. }
  2978. var that = this;
  2979. var manifestURL = this.currentSceneUrl + ".manifest";
  2980. var xhr = new XMLHttpRequest();
  2981. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2982. xhr.open("GET", manifestURLTimeStamped, true);
  2983. xhr.addEventListener("load", function () {
  2984. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2985. try {
  2986. var manifestFile = JSON.parse(xhr.response);
  2987. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2988. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2989. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2990. _this.manifestVersionFound = manifestFile.version;
  2991. }
  2992. if (_this.callbackManifestChecked) {
  2993. _this.callbackManifestChecked(true);
  2994. }
  2995. }
  2996. catch (ex) {
  2997. noManifestFile();
  2998. }
  2999. }
  3000. else {
  3001. noManifestFile();
  3002. }
  3003. }, false);
  3004. xhr.addEventListener("error", function (event) {
  3005. noManifestFile();
  3006. }, false);
  3007. try {
  3008. xhr.send();
  3009. }
  3010. catch (ex) {
  3011. BABYLON.Tools.Error("Error on XHR send request.");
  3012. that.callbackManifestChecked(false);
  3013. }
  3014. };
  3015. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3016. var _this = this;
  3017. function handleError() {
  3018. that.isSupported = false;
  3019. if (errorCallback)
  3020. errorCallback();
  3021. }
  3022. var that = this;
  3023. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3024. // Your browser doesn't support IndexedDB
  3025. this.isSupported = false;
  3026. if (errorCallback)
  3027. errorCallback();
  3028. }
  3029. else {
  3030. // If the DB hasn't been opened or created yet
  3031. if (!this.db) {
  3032. this.hasReachedQuota = false;
  3033. this.isSupported = true;
  3034. var request = this.idbFactory.open("babylonjs", 1);
  3035. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3036. request.onerror = function (event) {
  3037. handleError();
  3038. };
  3039. // executes when a version change transaction cannot complete due to other active transactions
  3040. request.onblocked = function (event) {
  3041. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3042. handleError();
  3043. };
  3044. // DB has been opened successfully
  3045. request.onsuccess = function (event) {
  3046. _this.db = request.result;
  3047. successCallback();
  3048. };
  3049. // Initialization of the DB. Creating Scenes & Textures stores
  3050. request.onupgradeneeded = function (event) {
  3051. _this.db = (event.target).result;
  3052. try {
  3053. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3054. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3055. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3056. }
  3057. catch (ex) {
  3058. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3059. handleError();
  3060. }
  3061. };
  3062. }
  3063. else {
  3064. if (successCallback)
  3065. successCallback();
  3066. }
  3067. }
  3068. };
  3069. Database.prototype.loadImageFromDB = function (url, image) {
  3070. var _this = this;
  3071. var completeURL = Database.ReturnFullUrlLocation(url);
  3072. var saveAndLoadImage = function () {
  3073. if (!_this.hasReachedQuota && _this.db !== null) {
  3074. // the texture is not yet in the DB, let's try to save it
  3075. _this._saveImageIntoDBAsync(completeURL, image);
  3076. }
  3077. else {
  3078. image.src = url;
  3079. }
  3080. };
  3081. if (!this.mustUpdateRessources) {
  3082. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3083. }
  3084. else {
  3085. saveAndLoadImage();
  3086. }
  3087. };
  3088. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3089. if (this.isSupported && this.db !== null) {
  3090. var texture;
  3091. var transaction = this.db.transaction(["textures"]);
  3092. transaction.onabort = function (event) {
  3093. image.src = url;
  3094. };
  3095. transaction.oncomplete = function (event) {
  3096. var blobTextureURL;
  3097. if (texture) {
  3098. var URL = window.URL || window.webkitURL;
  3099. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3100. image.onerror = function () {
  3101. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3102. image.src = url;
  3103. };
  3104. image.src = blobTextureURL;
  3105. }
  3106. else {
  3107. notInDBCallback();
  3108. }
  3109. };
  3110. var getRequest = transaction.objectStore("textures").get(url);
  3111. getRequest.onsuccess = function (event) {
  3112. texture = (event.target).result;
  3113. };
  3114. getRequest.onerror = function (event) {
  3115. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3116. image.src = url;
  3117. };
  3118. }
  3119. else {
  3120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3121. image.src = url;
  3122. }
  3123. };
  3124. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3125. var _this = this;
  3126. if (this.isSupported) {
  3127. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3128. var generateBlobUrl = function () {
  3129. var blobTextureURL;
  3130. if (blob) {
  3131. var URL = window.URL || window.webkitURL;
  3132. try {
  3133. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3134. }
  3135. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3136. catch (ex) {
  3137. blobTextureURL = URL.createObjectURL(blob);
  3138. }
  3139. }
  3140. image.src = blobTextureURL;
  3141. };
  3142. if (Database.IsUASupportingBlobStorage) {
  3143. var xhr = new XMLHttpRequest(), blob;
  3144. xhr.open("GET", url, true);
  3145. xhr.responseType = "blob";
  3146. xhr.addEventListener("load", function () {
  3147. if (xhr.status === 200) {
  3148. // Blob as response (XHR2)
  3149. blob = xhr.response;
  3150. var transaction = _this.db.transaction(["textures"], "readwrite");
  3151. // the transaction could abort because of a QuotaExceededError error
  3152. transaction.onabort = function (event) {
  3153. try {
  3154. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3155. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3156. this.hasReachedQuota = true;
  3157. }
  3158. }
  3159. catch (ex) { }
  3160. generateBlobUrl();
  3161. };
  3162. transaction.oncomplete = function (event) {
  3163. generateBlobUrl();
  3164. };
  3165. var newTexture = { textureUrl: url, data: blob };
  3166. try {
  3167. // Put the blob into the dabase
  3168. var addRequest = transaction.objectStore("textures").put(newTexture);
  3169. addRequest.onsuccess = function (event) {
  3170. };
  3171. addRequest.onerror = function (event) {
  3172. generateBlobUrl();
  3173. };
  3174. }
  3175. catch (ex) {
  3176. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3177. if (ex.code === 25) {
  3178. Database.IsUASupportingBlobStorage = false;
  3179. }
  3180. image.src = url;
  3181. }
  3182. }
  3183. else {
  3184. image.src = url;
  3185. }
  3186. }, false);
  3187. xhr.addEventListener("error", function (event) {
  3188. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3189. image.src = url;
  3190. }, false);
  3191. xhr.send();
  3192. }
  3193. else {
  3194. image.src = url;
  3195. }
  3196. }
  3197. else {
  3198. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3199. image.src = url;
  3200. }
  3201. };
  3202. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3203. var _this = this;
  3204. var updateVersion = function (event) {
  3205. // the version is not yet in the DB or we need to update it
  3206. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3207. };
  3208. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3209. };
  3210. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3211. var _this = this;
  3212. if (this.isSupported) {
  3213. var version;
  3214. try {
  3215. var transaction = this.db.transaction(["versions"]);
  3216. transaction.oncomplete = function (event) {
  3217. if (version) {
  3218. // If the version in the JSON file is > than the version in DB
  3219. if (_this.manifestVersionFound > version.data) {
  3220. _this.mustUpdateRessources = true;
  3221. updateInDBCallback();
  3222. }
  3223. else {
  3224. callback(version.data);
  3225. }
  3226. }
  3227. else {
  3228. _this.mustUpdateRessources = true;
  3229. updateInDBCallback();
  3230. }
  3231. };
  3232. transaction.onabort = function (event) {
  3233. callback(-1);
  3234. };
  3235. var getRequest = transaction.objectStore("versions").get(url);
  3236. getRequest.onsuccess = function (event) {
  3237. version = (event.target).result;
  3238. };
  3239. getRequest.onerror = function (event) {
  3240. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3241. callback(-1);
  3242. };
  3243. }
  3244. catch (ex) {
  3245. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3246. callback(-1);
  3247. }
  3248. }
  3249. else {
  3250. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3251. callback(-1);
  3252. }
  3253. };
  3254. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3255. var _this = this;
  3256. if (this.isSupported && !this.hasReachedQuota) {
  3257. try {
  3258. // Open a transaction to the database
  3259. var transaction = this.db.transaction(["versions"], "readwrite");
  3260. // the transaction could abort because of a QuotaExceededError error
  3261. transaction.onabort = function (event) {
  3262. try {
  3263. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3264. _this.hasReachedQuota = true;
  3265. }
  3266. }
  3267. catch (ex) { }
  3268. callback(-1);
  3269. };
  3270. transaction.oncomplete = function (event) {
  3271. callback(_this.manifestVersionFound);
  3272. };
  3273. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3274. // Put the scene into the database
  3275. var addRequest = transaction.objectStore("versions").put(newVersion);
  3276. addRequest.onsuccess = function (event) {
  3277. };
  3278. addRequest.onerror = function (event) {
  3279. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3280. };
  3281. }
  3282. catch (ex) {
  3283. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3284. callback(-1);
  3285. }
  3286. }
  3287. else {
  3288. callback(-1);
  3289. }
  3290. };
  3291. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3292. var _this = this;
  3293. var completeUrl = Database.ReturnFullUrlLocation(url);
  3294. var saveAndLoadFile = function (event) {
  3295. // the scene is not yet in the DB, let's try to save it
  3296. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3297. };
  3298. this._checkVersionFromDB(completeUrl, function (version) {
  3299. if (version !== -1) {
  3300. if (!_this.mustUpdateRessources) {
  3301. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3302. }
  3303. else {
  3304. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3305. }
  3306. }
  3307. else {
  3308. errorCallback();
  3309. }
  3310. });
  3311. };
  3312. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3313. if (this.isSupported) {
  3314. var targetStore;
  3315. if (url.indexOf(".babylon") !== -1) {
  3316. targetStore = "scenes";
  3317. }
  3318. else {
  3319. targetStore = "textures";
  3320. }
  3321. var file;
  3322. var transaction = this.db.transaction([targetStore]);
  3323. transaction.oncomplete = function (event) {
  3324. if (file) {
  3325. callback(file.data);
  3326. }
  3327. else {
  3328. notInDBCallback();
  3329. }
  3330. };
  3331. transaction.onabort = function (event) {
  3332. notInDBCallback();
  3333. };
  3334. var getRequest = transaction.objectStore(targetStore).get(url);
  3335. getRequest.onsuccess = function (event) {
  3336. file = (event.target).result;
  3337. };
  3338. getRequest.onerror = function (event) {
  3339. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3340. notInDBCallback();
  3341. };
  3342. }
  3343. else {
  3344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3345. callback();
  3346. }
  3347. };
  3348. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3349. var _this = this;
  3350. if (this.isSupported) {
  3351. var targetStore;
  3352. if (url.indexOf(".babylon") !== -1) {
  3353. targetStore = "scenes";
  3354. }
  3355. else {
  3356. targetStore = "textures";
  3357. }
  3358. // Create XHR
  3359. var xhr = new XMLHttpRequest(), fileData;
  3360. xhr.open("GET", url, true);
  3361. if (useArrayBuffer) {
  3362. xhr.responseType = "arraybuffer";
  3363. }
  3364. xhr.onprogress = progressCallback;
  3365. xhr.addEventListener("load", function () {
  3366. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3367. // Blob as response (XHR2)
  3368. //fileData = xhr.responseText;
  3369. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3370. if (!_this.hasReachedQuota) {
  3371. // Open a transaction to the database
  3372. var transaction = _this.db.transaction([targetStore], "readwrite");
  3373. // the transaction could abort because of a QuotaExceededError error
  3374. transaction.onabort = function (event) {
  3375. try {
  3376. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3377. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3378. this.hasReachedQuota = true;
  3379. }
  3380. }
  3381. catch (ex) { }
  3382. callback(fileData);
  3383. };
  3384. transaction.oncomplete = function (event) {
  3385. callback(fileData);
  3386. };
  3387. var newFile;
  3388. if (targetStore === "scenes") {
  3389. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3390. }
  3391. else {
  3392. newFile = { textureUrl: url, data: fileData };
  3393. }
  3394. try {
  3395. // Put the scene into the database
  3396. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3397. addRequest.onsuccess = function (event) {
  3398. };
  3399. addRequest.onerror = function (event) {
  3400. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3401. };
  3402. }
  3403. catch (ex) {
  3404. callback(fileData);
  3405. }
  3406. }
  3407. else {
  3408. callback(fileData);
  3409. }
  3410. }
  3411. else {
  3412. callback();
  3413. }
  3414. }, false);
  3415. xhr.addEventListener("error", function (event) {
  3416. BABYLON.Tools.Error("error on XHR request.");
  3417. callback();
  3418. }, false);
  3419. xhr.send();
  3420. }
  3421. else {
  3422. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3423. callback();
  3424. }
  3425. };
  3426. Database.IsUASupportingBlobStorage = true;
  3427. Database.IDBStorageEnabled = true;
  3428. Database.parseURL = function (url) {
  3429. var a = document.createElement('a');
  3430. a.href = url;
  3431. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3432. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3433. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3434. return absLocation;
  3435. };
  3436. Database.ReturnFullUrlLocation = function (url) {
  3437. if (url.indexOf("http:/") === -1) {
  3438. return (Database.parseURL(window.location.href) + url);
  3439. }
  3440. else {
  3441. return url;
  3442. }
  3443. };
  3444. return Database;
  3445. })();
  3446. BABYLON.Database = Database;
  3447. })(BABYLON || (BABYLON = {}));
  3448. var BABYLON;
  3449. (function (BABYLON) {
  3450. var Internals;
  3451. (function (Internals) {
  3452. /*
  3453. * Based on jsTGALoader - Javascript loader for TGA file
  3454. * By Vincent Thibault
  3455. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3456. */
  3457. var TGATools = (function () {
  3458. function TGATools() {
  3459. }
  3460. TGATools.GetTGAHeader = function (data) {
  3461. var offset = 0;
  3462. var header = {
  3463. id_length: data[offset++],
  3464. colormap_type: data[offset++],
  3465. image_type: data[offset++],
  3466. colormap_index: data[offset++] | data[offset++] << 8,
  3467. colormap_length: data[offset++] | data[offset++] << 8,
  3468. colormap_size: data[offset++],
  3469. origin: [
  3470. data[offset++] | data[offset++] << 8,
  3471. data[offset++] | data[offset++] << 8
  3472. ],
  3473. width: data[offset++] | data[offset++] << 8,
  3474. height: data[offset++] | data[offset++] << 8,
  3475. pixel_size: data[offset++],
  3476. flags: data[offset++]
  3477. };
  3478. return header;
  3479. };
  3480. TGATools.UploadContent = function (gl, data) {
  3481. // Not enough data to contain header ?
  3482. if (data.length < 19) {
  3483. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3484. return;
  3485. }
  3486. // Read Header
  3487. var offset = 18;
  3488. var header = TGATools.GetTGAHeader(data);
  3489. // Assume it's a valid Targa file.
  3490. if (header.id_length + offset > data.length) {
  3491. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3492. return;
  3493. }
  3494. // Skip not needed data
  3495. offset += header.id_length;
  3496. var use_rle = false;
  3497. var use_pal = false;
  3498. var use_rgb = false;
  3499. var use_grey = false;
  3500. // Get some informations.
  3501. switch (header.image_type) {
  3502. case TGATools._TYPE_RLE_INDEXED:
  3503. use_rle = true;
  3504. case TGATools._TYPE_INDEXED:
  3505. use_pal = true;
  3506. break;
  3507. case TGATools._TYPE_RLE_RGB:
  3508. use_rle = true;
  3509. case TGATools._TYPE_RGB:
  3510. use_rgb = true;
  3511. break;
  3512. case TGATools._TYPE_RLE_GREY:
  3513. use_rle = true;
  3514. case TGATools._TYPE_GREY:
  3515. use_grey = true;
  3516. break;
  3517. }
  3518. var pixel_data;
  3519. var numAlphaBits = header.flags & 0xf;
  3520. var pixel_size = header.pixel_size >> 3;
  3521. var pixel_total = header.width * header.height * pixel_size;
  3522. // Read palettes
  3523. var palettes;
  3524. if (use_pal) {
  3525. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3526. }
  3527. // Read LRE
  3528. if (use_rle) {
  3529. pixel_data = new Uint8Array(pixel_total);
  3530. var c, count, i;
  3531. var localOffset = 0;
  3532. var pixels = new Uint8Array(pixel_size);
  3533. while (offset < pixel_total && localOffset < pixel_total) {
  3534. c = data[offset++];
  3535. count = (c & 0x7f) + 1;
  3536. // RLE pixels
  3537. if (c & 0x80) {
  3538. // Bind pixel tmp array
  3539. for (i = 0; i < pixel_size; ++i) {
  3540. pixels[i] = data[offset++];
  3541. }
  3542. // Copy pixel array
  3543. for (i = 0; i < count; ++i) {
  3544. pixel_data.set(pixels, localOffset + i * pixel_size);
  3545. }
  3546. localOffset += pixel_size * count;
  3547. }
  3548. else {
  3549. count *= pixel_size;
  3550. for (i = 0; i < count; ++i) {
  3551. pixel_data[localOffset + i] = data[offset++];
  3552. }
  3553. localOffset += count;
  3554. }
  3555. }
  3556. }
  3557. else {
  3558. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3559. }
  3560. // Load to texture
  3561. var x_start, y_start, x_step, y_step, y_end, x_end;
  3562. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3563. default:
  3564. case TGATools._ORIGIN_UL:
  3565. x_start = 0;
  3566. x_step = 1;
  3567. x_end = header.width;
  3568. y_start = 0;
  3569. y_step = 1;
  3570. y_end = header.height;
  3571. break;
  3572. case TGATools._ORIGIN_BL:
  3573. x_start = 0;
  3574. x_step = 1;
  3575. x_end = header.width;
  3576. y_start = header.height - 1;
  3577. y_step = -1;
  3578. y_end = -1;
  3579. break;
  3580. case TGATools._ORIGIN_UR:
  3581. x_start = header.width - 1;
  3582. x_step = -1;
  3583. x_end = -1;
  3584. y_start = 0;
  3585. y_step = 1;
  3586. y_end = header.height;
  3587. break;
  3588. case TGATools._ORIGIN_BR:
  3589. x_start = header.width - 1;
  3590. x_step = -1;
  3591. x_end = -1;
  3592. y_start = header.height - 1;
  3593. y_step = -1;
  3594. y_end = -1;
  3595. break;
  3596. }
  3597. // Load the specify method
  3598. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3599. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3600. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3601. };
  3602. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3603. var image = pixel_data, colormap = palettes;
  3604. var width = header.width, height = header.height;
  3605. var color, i = 0, x, y;
  3606. var imageData = new Uint8Array(width * height * 4);
  3607. for (y = y_start; y !== y_end; y += y_step) {
  3608. for (x = x_start; x !== x_end; x += x_step, i++) {
  3609. color = image[i];
  3610. imageData[(x + width * y) * 4 + 3] = 255;
  3611. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3612. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3613. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3614. }
  3615. }
  3616. return imageData;
  3617. };
  3618. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3619. var image = pixel_data;
  3620. var width = header.width, height = header.height;
  3621. var color, i = 0, x, y;
  3622. var imageData = new Uint8Array(width * height * 4);
  3623. for (y = y_start; y !== y_end; y += y_step) {
  3624. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3625. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3626. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3627. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3628. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3629. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3630. }
  3631. }
  3632. return imageData;
  3633. };
  3634. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3635. var image = pixel_data;
  3636. var width = header.width, height = header.height;
  3637. var i = 0, x, y;
  3638. var imageData = new Uint8Array(width * height * 4);
  3639. for (y = y_start; y !== y_end; y += y_step) {
  3640. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3641. imageData[(x + width * y) * 4 + 3] = 255;
  3642. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3643. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3644. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3645. }
  3646. }
  3647. return imageData;
  3648. };
  3649. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3650. var image = pixel_data;
  3651. var width = header.width, height = header.height;
  3652. var i = 0, x, y;
  3653. var imageData = new Uint8Array(width * height * 4);
  3654. for (y = y_start; y !== y_end; y += y_step) {
  3655. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3657. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3658. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3659. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3660. }
  3661. }
  3662. return imageData;
  3663. };
  3664. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3665. var image = pixel_data;
  3666. var width = header.width, height = header.height;
  3667. var color, i = 0, x, y;
  3668. var imageData = new Uint8Array(width * height * 4);
  3669. for (y = y_start; y !== y_end; y += y_step) {
  3670. for (x = x_start; x !== x_end; x += x_step, i++) {
  3671. color = image[i];
  3672. imageData[(x + width * y) * 4 + 0] = color;
  3673. imageData[(x + width * y) * 4 + 1] = color;
  3674. imageData[(x + width * y) * 4 + 2] = color;
  3675. imageData[(x + width * y) * 4 + 3] = 255;
  3676. }
  3677. }
  3678. return imageData;
  3679. };
  3680. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3681. var image = pixel_data;
  3682. var width = header.width, height = header.height;
  3683. var i = 0, x, y;
  3684. var imageData = new Uint8Array(width * height * 4);
  3685. for (y = y_start; y !== y_end; y += y_step) {
  3686. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3687. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3688. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3689. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3690. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._TYPE_NO_DATA = 0;
  3696. TGATools._TYPE_INDEXED = 1;
  3697. TGATools._TYPE_RGB = 2;
  3698. TGATools._TYPE_GREY = 3;
  3699. TGATools._TYPE_RLE_INDEXED = 9;
  3700. TGATools._TYPE_RLE_RGB = 10;
  3701. TGATools._TYPE_RLE_GREY = 11;
  3702. TGATools._ORIGIN_MASK = 0x30;
  3703. TGATools._ORIGIN_SHIFT = 0x04;
  3704. TGATools._ORIGIN_BL = 0x00;
  3705. TGATools._ORIGIN_BR = 0x01;
  3706. TGATools._ORIGIN_UL = 0x02;
  3707. TGATools._ORIGIN_UR = 0x03;
  3708. return TGATools;
  3709. })();
  3710. Internals.TGATools = TGATools;
  3711. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3712. })(BABYLON || (BABYLON = {}));
  3713. var BABYLON;
  3714. (function (BABYLON) {
  3715. var SmartArray = (function () {
  3716. function SmartArray(capacity) {
  3717. this.length = 0;
  3718. this._duplicateId = 0;
  3719. this.data = new Array(capacity);
  3720. this._id = SmartArray._GlobalId++;
  3721. }
  3722. SmartArray.prototype.push = function (value) {
  3723. this.data[this.length++] = value;
  3724. if (this.length > this.data.length) {
  3725. this.data.length *= 2;
  3726. }
  3727. if (!value.__smartArrayFlags) {
  3728. value.__smartArrayFlags = {};
  3729. }
  3730. value.__smartArrayFlags[this._id] = this._duplicateId;
  3731. };
  3732. SmartArray.prototype.pushNoDuplicate = function (value) {
  3733. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3734. return;
  3735. }
  3736. this.push(value);
  3737. };
  3738. SmartArray.prototype.sort = function (compareFn) {
  3739. this.data.sort(compareFn);
  3740. };
  3741. SmartArray.prototype.reset = function () {
  3742. this.length = 0;
  3743. this._duplicateId++;
  3744. };
  3745. SmartArray.prototype.concat = function (array) {
  3746. if (array.length === 0) {
  3747. return;
  3748. }
  3749. if (this.length + array.length > this.data.length) {
  3750. this.data.length = (this.length + array.length) * 2;
  3751. }
  3752. for (var index = 0; index < array.length; index++) {
  3753. this.data[this.length++] = (array.data || array)[index];
  3754. }
  3755. };
  3756. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3757. if (array.length === 0) {
  3758. return;
  3759. }
  3760. if (this.length + array.length > this.data.length) {
  3761. this.data.length = (this.length + array.length) * 2;
  3762. }
  3763. for (var index = 0; index < array.length; index++) {
  3764. var item = (array.data || array)[index];
  3765. this.pushNoDuplicate(item);
  3766. }
  3767. };
  3768. SmartArray.prototype.indexOf = function (value) {
  3769. var position = this.data.indexOf(value);
  3770. if (position >= this.length) {
  3771. return -1;
  3772. }
  3773. return position;
  3774. };
  3775. // Statics
  3776. SmartArray._GlobalId = 0;
  3777. return SmartArray;
  3778. })();
  3779. BABYLON.SmartArray = SmartArray;
  3780. })(BABYLON || (BABYLON = {}));
  3781. var BABYLON;
  3782. (function (BABYLON) {
  3783. var SmartCollection = (function () {
  3784. function SmartCollection(capacity) {
  3785. if (capacity === void 0) { capacity = 10; }
  3786. this.count = 0;
  3787. this._initialCapacity = capacity;
  3788. this.items = {};
  3789. this._keys = new Array(this._initialCapacity);
  3790. }
  3791. SmartCollection.prototype.add = function (key, item) {
  3792. if (this.items[key] != undefined) {
  3793. return -1;
  3794. }
  3795. this.items[key] = item;
  3796. //literal keys are always strings, but we keep source type of key in _keys array
  3797. this._keys[this.count++] = key;
  3798. if (this.count > this._keys.length) {
  3799. this._keys.length *= 2;
  3800. }
  3801. return this.count;
  3802. };
  3803. SmartCollection.prototype.remove = function (key) {
  3804. if (this.items[key] == undefined) {
  3805. return -1;
  3806. }
  3807. return this.removeItemOfIndex(this.indexOf(key));
  3808. };
  3809. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3810. if (index < this.count && index > -1) {
  3811. delete this.items[this._keys[index]];
  3812. //here, shifting by hand is better optimised than .splice
  3813. while (index < this.count) {
  3814. this._keys[index] = this._keys[index + 1];
  3815. index++;
  3816. }
  3817. }
  3818. else {
  3819. return -1;
  3820. }
  3821. return --this.count;
  3822. };
  3823. SmartCollection.prototype.indexOf = function (key) {
  3824. for (var i = 0; i !== this.count; i++) {
  3825. if (this._keys[i] === key) {
  3826. return i;
  3827. }
  3828. }
  3829. return -1;
  3830. };
  3831. SmartCollection.prototype.item = function (key) {
  3832. return this.items[key];
  3833. };
  3834. SmartCollection.prototype.getAllKeys = function () {
  3835. if (this.count > 0) {
  3836. var keys = new Array(this.count);
  3837. for (var i = 0; i < this.count; i++) {
  3838. keys[i] = this._keys[i];
  3839. }
  3840. return keys;
  3841. }
  3842. else {
  3843. return undefined;
  3844. }
  3845. };
  3846. SmartCollection.prototype.getKeyByIndex = function (index) {
  3847. if (index < this.count && index > -1) {
  3848. return this._keys[index];
  3849. }
  3850. else {
  3851. return undefined;
  3852. }
  3853. };
  3854. SmartCollection.prototype.getItemByIndex = function (index) {
  3855. if (index < this.count && index > -1) {
  3856. return this.items[this._keys[index]];
  3857. }
  3858. else {
  3859. return undefined;
  3860. }
  3861. };
  3862. SmartCollection.prototype.empty = function () {
  3863. if (this.count > 0) {
  3864. this.count = 0;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. };
  3869. SmartCollection.prototype.forEach = function (block) {
  3870. var key;
  3871. for (key in this.items) {
  3872. if (this.items.hasOwnProperty(key)) {
  3873. block(this.items[key]);
  3874. }
  3875. }
  3876. };
  3877. return SmartCollection;
  3878. })();
  3879. BABYLON.SmartCollection = SmartCollection;
  3880. })(BABYLON || (BABYLON = {}));
  3881. var BABYLON;
  3882. (function (BABYLON) {
  3883. // Screenshots
  3884. var screenshotCanvas;
  3885. var cloneValue = function (source, destinationObject) {
  3886. if (!source)
  3887. return null;
  3888. if (source instanceof BABYLON.Mesh) {
  3889. return null;
  3890. }
  3891. if (source instanceof BABYLON.SubMesh) {
  3892. return source.clone(destinationObject);
  3893. }
  3894. else if (source.clone) {
  3895. return source.clone();
  3896. }
  3897. return null;
  3898. };
  3899. var Tools = (function () {
  3900. function Tools() {
  3901. }
  3902. Tools.Instantiate = function (className) {
  3903. var arr = className.split(".");
  3904. var fn = (window || this);
  3905. for (var i = 0, len = arr.length; i < len; i++) {
  3906. fn = fn[arr[i]];
  3907. }
  3908. if (typeof fn !== "function") {
  3909. return null;
  3910. }
  3911. return fn;
  3912. };
  3913. Tools.GetConstructorName = function (obj) {
  3914. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3915. var cname = str.match(/function\s(\w*)/)[1];
  3916. var aliases = ["", "anonymous", "Anonymous"];
  3917. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3918. };
  3919. Tools.ToHex = function (i) {
  3920. var str = i.toString(16);
  3921. if (i <= 15) {
  3922. return ("0" + str).toUpperCase();
  3923. }
  3924. return str.toUpperCase();
  3925. };
  3926. Tools.SetImmediate = function (action) {
  3927. if (window.setImmediate) {
  3928. window.setImmediate(action);
  3929. }
  3930. else {
  3931. setTimeout(action, 1);
  3932. }
  3933. };
  3934. Tools.IsExponentOfTwo = function (value) {
  3935. var count = 1;
  3936. do {
  3937. count *= 2;
  3938. } while (count < value);
  3939. return count === value;
  3940. };
  3941. Tools.GetExponentOfTwo = function (value, max) {
  3942. var count = 1;
  3943. do {
  3944. count *= 2;
  3945. } while (count < value);
  3946. if (count > max)
  3947. count = max;
  3948. return count;
  3949. };
  3950. Tools.GetFilename = function (path) {
  3951. var index = path.lastIndexOf("/");
  3952. if (index < 0)
  3953. return path;
  3954. return path.substring(index + 1);
  3955. };
  3956. Tools.GetDOMTextContent = function (element) {
  3957. var result = "";
  3958. var child = element.firstChild;
  3959. while (child) {
  3960. if (child.nodeType === 3) {
  3961. result += child.textContent;
  3962. }
  3963. child = child.nextSibling;
  3964. }
  3965. return result;
  3966. };
  3967. Tools.ToDegrees = function (angle) {
  3968. return angle * 180 / Math.PI;
  3969. };
  3970. Tools.ToRadians = function (angle) {
  3971. return angle * Math.PI / 180;
  3972. };
  3973. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3974. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3975. var output = "";
  3976. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3977. var i = 0;
  3978. var bytes = new Uint8Array(buffer);
  3979. while (i < bytes.length) {
  3980. chr1 = bytes[i++];
  3981. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3982. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3983. enc1 = chr1 >> 2;
  3984. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3985. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3986. enc4 = chr3 & 63;
  3987. if (isNaN(chr2)) {
  3988. enc3 = enc4 = 64;
  3989. }
  3990. else if (isNaN(chr3)) {
  3991. enc4 = 64;
  3992. }
  3993. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3994. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3995. }
  3996. return "data:image/png;base64," + output;
  3997. };
  3998. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3999. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4000. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4001. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4002. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4003. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4004. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4005. }
  4006. return {
  4007. minimum: minimum,
  4008. maximum: maximum
  4009. };
  4010. };
  4011. Tools.ExtractMinAndMax = function (positions, start, count) {
  4012. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4013. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4014. for (var index = start; index < start + count; index++) {
  4015. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4016. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4017. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4018. }
  4019. return {
  4020. minimum: minimum,
  4021. maximum: maximum
  4022. };
  4023. };
  4024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4026. return undefined;
  4027. return Array.isArray(obj) ? obj : [obj];
  4028. };
  4029. // Misc.
  4030. Tools.GetPointerPrefix = function () {
  4031. var eventPrefix = "pointer";
  4032. // Check if pointer events are supported
  4033. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4034. eventPrefix = "mouse";
  4035. }
  4036. return eventPrefix;
  4037. };
  4038. Tools.QueueNewFrame = function (func) {
  4039. if (window.requestAnimationFrame)
  4040. window.requestAnimationFrame(func);
  4041. else if (window.msRequestAnimationFrame)
  4042. window.msRequestAnimationFrame(func);
  4043. else if (window.webkitRequestAnimationFrame)
  4044. window.webkitRequestAnimationFrame(func);
  4045. else if (window.mozRequestAnimationFrame)
  4046. window.mozRequestAnimationFrame(func);
  4047. else if (window.oRequestAnimationFrame)
  4048. window.oRequestAnimationFrame(func);
  4049. else {
  4050. window.setTimeout(func, 16);
  4051. }
  4052. };
  4053. Tools.RequestFullscreen = function (element) {
  4054. if (element.requestFullscreen)
  4055. element.requestFullscreen();
  4056. else if (element.msRequestFullscreen)
  4057. element.msRequestFullscreen();
  4058. else if (element.webkitRequestFullscreen)
  4059. element.webkitRequestFullscreen();
  4060. else if (element.mozRequestFullScreen)
  4061. element.mozRequestFullScreen();
  4062. };
  4063. Tools.ExitFullscreen = function () {
  4064. if (document.exitFullscreen) {
  4065. document.exitFullscreen();
  4066. }
  4067. else if (document.mozCancelFullScreen) {
  4068. document.mozCancelFullScreen();
  4069. }
  4070. else if (document.webkitCancelFullScreen) {
  4071. document.webkitCancelFullScreen();
  4072. }
  4073. else if (document.msCancelFullScreen) {
  4074. document.msCancelFullScreen();
  4075. }
  4076. };
  4077. // External files
  4078. Tools.CleanUrl = function (url) {
  4079. url = url.replace(/#/mg, "%23");
  4080. return url;
  4081. };
  4082. Tools.LoadImage = function (url, onload, onerror, database) {
  4083. if (url instanceof ArrayBuffer) {
  4084. url = Tools.EncodeArrayBufferTobase64(url);
  4085. }
  4086. url = Tools.CleanUrl(url);
  4087. var img = new Image();
  4088. if (url.substr(0, 5) !== "data:") {
  4089. if (Tools.CorsBehavior) {
  4090. switch (typeof (Tools.CorsBehavior)) {
  4091. case "function":
  4092. var result = Tools.CorsBehavior(url);
  4093. if (result) {
  4094. img.crossOrigin = result;
  4095. }
  4096. break;
  4097. case "string":
  4098. default:
  4099. img.crossOrigin = Tools.CorsBehavior;
  4100. break;
  4101. }
  4102. }
  4103. }
  4104. img.onload = function () {
  4105. onload(img);
  4106. };
  4107. img.onerror = function (err) {
  4108. Tools.Error("Error while trying to load texture: " + url);
  4109. 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";
  4110. onload(img);
  4111. };
  4112. var noIndexedDB = function () {
  4113. img.src = url;
  4114. };
  4115. var loadFromIndexedDB = function () {
  4116. database.loadImageFromDB(url, img);
  4117. };
  4118. //ANY database to do!
  4119. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4120. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4121. }
  4122. else {
  4123. if (url.indexOf("file:") === -1) {
  4124. noIndexedDB();
  4125. }
  4126. else {
  4127. try {
  4128. var textureName = url.substring(5);
  4129. var blobURL;
  4130. try {
  4131. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4132. }
  4133. catch (ex) {
  4134. // Chrome doesn't support oneTimeOnly parameter
  4135. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4136. }
  4137. img.src = blobURL;
  4138. }
  4139. catch (e) {
  4140. img.src = null;
  4141. }
  4142. }
  4143. }
  4144. return img;
  4145. };
  4146. //ANY
  4147. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4148. url = Tools.CleanUrl(url);
  4149. var noIndexedDB = function () {
  4150. var request = new XMLHttpRequest();
  4151. var loadUrl = Tools.BaseUrl + url;
  4152. request.open('GET', loadUrl, true);
  4153. if (useArrayBuffer) {
  4154. request.responseType = "arraybuffer";
  4155. }
  4156. request.onprogress = progressCallBack;
  4157. request.onreadystatechange = function () {
  4158. if (request.readyState === 4) {
  4159. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4160. callback(!useArrayBuffer ? request.responseText : request.response);
  4161. }
  4162. else {
  4163. if (onError) {
  4164. onError();
  4165. }
  4166. else {
  4167. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4168. }
  4169. }
  4170. }
  4171. };
  4172. request.send(null);
  4173. };
  4174. var loadFromIndexedDB = function () {
  4175. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4176. };
  4177. if (url.indexOf("file:") !== -1) {
  4178. var fileName = url.substring(5);
  4179. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4180. }
  4181. else {
  4182. // Caching all files
  4183. if (database && database.enableSceneOffline) {
  4184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4185. }
  4186. else {
  4187. noIndexedDB();
  4188. }
  4189. }
  4190. };
  4191. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4192. var reader = new FileReader();
  4193. reader.onload = function (e) {
  4194. //target doesn't have result from ts 1.3
  4195. callback(e.target['result']);
  4196. };
  4197. reader.onprogress = progressCallback;
  4198. reader.readAsDataURL(fileToLoad);
  4199. };
  4200. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4201. var reader = new FileReader();
  4202. reader.onerror = function (e) {
  4203. Tools.Log("Error while reading file: " + fileToLoad.name);
  4204. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4205. };
  4206. reader.onload = function (e) {
  4207. //target doesn't have result from ts 1.3
  4208. callback(e.target['result']);
  4209. };
  4210. reader.onprogress = progressCallBack;
  4211. if (!useArrayBuffer) {
  4212. // Asynchronous read
  4213. reader.readAsText(fileToLoad);
  4214. }
  4215. else {
  4216. reader.readAsArrayBuffer(fileToLoad);
  4217. }
  4218. };
  4219. //returns a downloadable url to a file content.
  4220. Tools.FileAsURL = function (content) {
  4221. var fileBlob = new Blob([content]);
  4222. var url = window.URL || window.webkitURL;
  4223. var link = url.createObjectURL(fileBlob);
  4224. return link;
  4225. };
  4226. // Misc.
  4227. Tools.Clamp = function (value, min, max) {
  4228. if (min === void 0) { min = 0; }
  4229. if (max === void 0) { max = 1; }
  4230. return Math.min(max, Math.max(min, value));
  4231. };
  4232. // Returns -1 when value is a negative number and
  4233. // +1 when value is a positive number.
  4234. Tools.Sign = function (value) {
  4235. value = +value; // convert to a number
  4236. if (value === 0 || isNaN(value))
  4237. return value;
  4238. return value > 0 ? 1 : -1;
  4239. };
  4240. Tools.Format = function (value, decimals) {
  4241. if (decimals === void 0) { decimals = 2; }
  4242. return value.toFixed(decimals);
  4243. };
  4244. Tools.CheckExtends = function (v, min, max) {
  4245. if (v.x < min.x)
  4246. min.x = v.x;
  4247. if (v.y < min.y)
  4248. min.y = v.y;
  4249. if (v.z < min.z)
  4250. min.z = v.z;
  4251. if (v.x > max.x)
  4252. max.x = v.x;
  4253. if (v.y > max.y)
  4254. max.y = v.y;
  4255. if (v.z > max.z)
  4256. max.z = v.z;
  4257. };
  4258. Tools.WithinEpsilon = function (a, b, epsilon) {
  4259. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4260. var num = a - b;
  4261. return -epsilon <= num && num <= epsilon;
  4262. };
  4263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4264. for (var prop in source) {
  4265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4266. continue;
  4267. }
  4268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4269. continue;
  4270. }
  4271. var sourceValue = source[prop];
  4272. var typeOfSourceValue = typeof sourceValue;
  4273. if (typeOfSourceValue === "function") {
  4274. continue;
  4275. }
  4276. if (typeOfSourceValue === "object") {
  4277. if (sourceValue instanceof Array) {
  4278. destination[prop] = [];
  4279. if (sourceValue.length > 0) {
  4280. if (typeof sourceValue[0] == "object") {
  4281. for (var index = 0; index < sourceValue.length; index++) {
  4282. var clonedValue = cloneValue(sourceValue[index], destination);
  4283. if (destination[prop].indexOf(clonedValue) === -1) {
  4284. destination[prop].push(clonedValue);
  4285. }
  4286. }
  4287. }
  4288. else {
  4289. destination[prop] = sourceValue.slice(0);
  4290. }
  4291. }
  4292. }
  4293. else {
  4294. destination[prop] = cloneValue(sourceValue, destination);
  4295. }
  4296. }
  4297. else {
  4298. destination[prop] = sourceValue;
  4299. }
  4300. }
  4301. };
  4302. Tools.IsEmpty = function (obj) {
  4303. for (var i in obj) {
  4304. return false;
  4305. }
  4306. return true;
  4307. };
  4308. Tools.RegisterTopRootEvents = function (events) {
  4309. for (var index = 0; index < events.length; index++) {
  4310. var event = events[index];
  4311. window.addEventListener(event.name, event.handler, false);
  4312. try {
  4313. if (window.parent) {
  4314. window.parent.addEventListener(event.name, event.handler, false);
  4315. }
  4316. }
  4317. catch (e) {
  4318. }
  4319. }
  4320. };
  4321. Tools.UnregisterTopRootEvents = function (events) {
  4322. for (var index = 0; index < events.length; index++) {
  4323. var event = events[index];
  4324. window.removeEventListener(event.name, event.handler);
  4325. try {
  4326. if (window.parent) {
  4327. window.parent.removeEventListener(event.name, event.handler);
  4328. }
  4329. }
  4330. catch (e) {
  4331. }
  4332. }
  4333. };
  4334. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4335. // Read the contents of the framebuffer
  4336. var numberOfChannelsByLine = width * 4;
  4337. var halfHeight = height / 2;
  4338. //Reading datas from WebGL
  4339. var data = engine.readPixels(0, 0, width, height);
  4340. //To flip image on Y axis.
  4341. for (var i = 0; i < halfHeight; i++) {
  4342. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4343. var currentCell = j + i * numberOfChannelsByLine;
  4344. var targetLine = height - i - 1;
  4345. var targetCell = j + targetLine * numberOfChannelsByLine;
  4346. var temp = data[currentCell];
  4347. data[currentCell] = data[targetCell];
  4348. data[targetCell] = temp;
  4349. }
  4350. }
  4351. // Create a 2D canvas to store the result
  4352. if (!screenshotCanvas) {
  4353. screenshotCanvas = document.createElement('canvas');
  4354. }
  4355. screenshotCanvas.width = width;
  4356. screenshotCanvas.height = height;
  4357. var context = screenshotCanvas.getContext('2d');
  4358. // Copy the pixels to a 2D canvas
  4359. var imageData = context.createImageData(width, height);
  4360. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4361. var castData = imageData.data;
  4362. castData.set(data);
  4363. context.putImageData(imageData, 0, 0);
  4364. var base64Image = screenshotCanvas.toDataURL();
  4365. if (successCallback) {
  4366. successCallback(base64Image);
  4367. }
  4368. else {
  4369. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4370. if (("download" in document.createElement("a"))) {
  4371. var a = window.document.createElement("a");
  4372. a.href = base64Image;
  4373. var date = new Date();
  4374. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4375. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4376. window.document.body.appendChild(a);
  4377. a.addEventListener("click", function () {
  4378. a.parentElement.removeChild(a);
  4379. });
  4380. a.click();
  4381. }
  4382. else {
  4383. var newWindow = window.open("");
  4384. var img = newWindow.document.createElement("img");
  4385. img.src = base64Image;
  4386. newWindow.document.body.appendChild(img);
  4387. }
  4388. }
  4389. };
  4390. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4391. var width;
  4392. var height;
  4393. //If a precision value is specified
  4394. if (size.precision) {
  4395. width = Math.round(engine.getRenderWidth() * size.precision);
  4396. height = Math.round(width / engine.getAspectRatio(camera));
  4397. size = { width: width, height: height };
  4398. }
  4399. else if (size.width && size.height) {
  4400. width = size.width;
  4401. height = size.height;
  4402. }
  4403. else if (size.width && !size.height) {
  4404. width = size.width;
  4405. height = Math.round(width / engine.getAspectRatio(camera));
  4406. size = { width: width, height: height };
  4407. }
  4408. else if (size.height && !size.width) {
  4409. height = size.height;
  4410. width = Math.round(height * engine.getAspectRatio(camera));
  4411. size = { width: width, height: height };
  4412. }
  4413. else if (!isNaN(size)) {
  4414. height = size;
  4415. width = size;
  4416. }
  4417. else {
  4418. Tools.Error("Invalid 'size' parameter !");
  4419. return;
  4420. }
  4421. var scene = camera.getScene();
  4422. var previousCamera = null;
  4423. if (scene.activeCamera !== camera) {
  4424. previousCamera = scene.activeCamera;
  4425. scene.activeCamera = camera;
  4426. }
  4427. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4428. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4429. texture.renderList = scene.meshes;
  4430. texture.onAfterRender = function () {
  4431. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4432. };
  4433. scene.incrementRenderId();
  4434. texture.render(true);
  4435. texture.dispose();
  4436. if (previousCamera) {
  4437. scene.activeCamera = previousCamera;
  4438. }
  4439. };
  4440. // XHR response validator for local file scenario
  4441. Tools.ValidateXHRData = function (xhr, dataType) {
  4442. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4443. if (dataType === void 0) { dataType = 7; }
  4444. try {
  4445. if (dataType & 1) {
  4446. if (xhr.responseText && xhr.responseText.length > 0) {
  4447. return true;
  4448. }
  4449. else if (dataType === 1) {
  4450. return false;
  4451. }
  4452. }
  4453. if (dataType & 2) {
  4454. // Check header width and height since there is no "TGA" magic number
  4455. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4456. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4457. return true;
  4458. }
  4459. else if (dataType === 2) {
  4460. return false;
  4461. }
  4462. }
  4463. if (dataType & 4) {
  4464. // Check for the "DDS" magic number
  4465. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4466. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4467. return true;
  4468. }
  4469. else {
  4470. return false;
  4471. }
  4472. }
  4473. }
  4474. catch (e) {
  4475. }
  4476. return false;
  4477. };
  4478. Object.defineProperty(Tools, "NoneLogLevel", {
  4479. get: function () {
  4480. return Tools._NoneLogLevel;
  4481. },
  4482. enumerable: true,
  4483. configurable: true
  4484. });
  4485. Object.defineProperty(Tools, "MessageLogLevel", {
  4486. get: function () {
  4487. return Tools._MessageLogLevel;
  4488. },
  4489. enumerable: true,
  4490. configurable: true
  4491. });
  4492. Object.defineProperty(Tools, "WarningLogLevel", {
  4493. get: function () {
  4494. return Tools._WarningLogLevel;
  4495. },
  4496. enumerable: true,
  4497. configurable: true
  4498. });
  4499. Object.defineProperty(Tools, "ErrorLogLevel", {
  4500. get: function () {
  4501. return Tools._ErrorLogLevel;
  4502. },
  4503. enumerable: true,
  4504. configurable: true
  4505. });
  4506. Object.defineProperty(Tools, "AllLogLevel", {
  4507. get: function () {
  4508. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. Tools._AddLogEntry = function (entry) {
  4514. Tools._LogCache = entry + Tools._LogCache;
  4515. if (Tools.OnNewCacheEntry) {
  4516. Tools.OnNewCacheEntry(entry);
  4517. }
  4518. };
  4519. Tools._FormatMessage = function (message) {
  4520. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4521. var date = new Date();
  4522. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4523. };
  4524. Tools._LogDisabled = function (message) {
  4525. // nothing to do
  4526. };
  4527. Tools._LogEnabled = function (message) {
  4528. var formattedMessage = Tools._FormatMessage(message);
  4529. console.log("BJS - " + formattedMessage);
  4530. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4531. Tools._AddLogEntry(entry);
  4532. };
  4533. Tools._WarnDisabled = function (message) {
  4534. // nothing to do
  4535. };
  4536. Tools._WarnEnabled = function (message) {
  4537. var formattedMessage = Tools._FormatMessage(message);
  4538. console.warn("BJS - " + formattedMessage);
  4539. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4540. Tools._AddLogEntry(entry);
  4541. };
  4542. Tools._ErrorDisabled = function (message) {
  4543. // nothing to do
  4544. };
  4545. Tools._ErrorEnabled = function (message) {
  4546. Tools.errorsCount++;
  4547. var formattedMessage = Tools._FormatMessage(message);
  4548. console.error("BJS - " + formattedMessage);
  4549. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4550. Tools._AddLogEntry(entry);
  4551. };
  4552. Object.defineProperty(Tools, "LogCache", {
  4553. get: function () {
  4554. return Tools._LogCache;
  4555. },
  4556. enumerable: true,
  4557. configurable: true
  4558. });
  4559. Tools.ClearLogCache = function () {
  4560. Tools._LogCache = "";
  4561. Tools.errorsCount = 0;
  4562. };
  4563. Object.defineProperty(Tools, "LogLevels", {
  4564. set: function (level) {
  4565. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4566. Tools.Log = Tools._LogEnabled;
  4567. }
  4568. else {
  4569. Tools.Log = Tools._LogDisabled;
  4570. }
  4571. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4572. Tools.Warn = Tools._WarnEnabled;
  4573. }
  4574. else {
  4575. Tools.Warn = Tools._WarnDisabled;
  4576. }
  4577. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4578. Tools.Error = Tools._ErrorEnabled;
  4579. }
  4580. else {
  4581. Tools.Error = Tools._ErrorDisabled;
  4582. }
  4583. },
  4584. enumerable: true,
  4585. configurable: true
  4586. });
  4587. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4588. get: function () {
  4589. return Tools._PerformanceNoneLogLevel;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4595. get: function () {
  4596. return Tools._PerformanceUserMarkLogLevel;
  4597. },
  4598. enumerable: true,
  4599. configurable: true
  4600. });
  4601. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4602. get: function () {
  4603. return Tools._PerformanceConsoleLogLevel;
  4604. },
  4605. enumerable: true,
  4606. configurable: true
  4607. });
  4608. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4609. set: function (level) {
  4610. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4611. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4612. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4613. return;
  4614. }
  4615. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4616. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4617. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4618. return;
  4619. }
  4620. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4621. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4622. },
  4623. enumerable: true,
  4624. configurable: true
  4625. });
  4626. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4627. };
  4628. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4629. };
  4630. Tools._StartUserMark = function (counterName, condition) {
  4631. if (condition === void 0) { condition = true; }
  4632. if (!condition || !Tools._performance.mark) {
  4633. return;
  4634. }
  4635. Tools._performance.mark(counterName + "-Begin");
  4636. };
  4637. Tools._EndUserMark = function (counterName, condition) {
  4638. if (condition === void 0) { condition = true; }
  4639. if (!condition || !Tools._performance.mark) {
  4640. return;
  4641. }
  4642. Tools._performance.mark(counterName + "-End");
  4643. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4644. };
  4645. Tools._StartPerformanceConsole = function (counterName, condition) {
  4646. if (condition === void 0) { condition = true; }
  4647. if (!condition) {
  4648. return;
  4649. }
  4650. Tools._StartUserMark(counterName, condition);
  4651. if (console.time) {
  4652. console.time(counterName);
  4653. }
  4654. };
  4655. Tools._EndPerformanceConsole = function (counterName, condition) {
  4656. if (condition === void 0) { condition = true; }
  4657. if (!condition) {
  4658. return;
  4659. }
  4660. Tools._EndUserMark(counterName, condition);
  4661. if (console.time) {
  4662. console.timeEnd(counterName);
  4663. }
  4664. };
  4665. Object.defineProperty(Tools, "Now", {
  4666. get: function () {
  4667. if (window.performance && window.performance.now) {
  4668. return window.performance.now();
  4669. }
  4670. return new Date().getTime();
  4671. },
  4672. enumerable: true,
  4673. configurable: true
  4674. });
  4675. Tools.BaseUrl = "";
  4676. Tools.CorsBehavior = "anonymous";
  4677. // Logs
  4678. Tools._NoneLogLevel = 0;
  4679. Tools._MessageLogLevel = 1;
  4680. Tools._WarningLogLevel = 2;
  4681. Tools._ErrorLogLevel = 4;
  4682. Tools._LogCache = "";
  4683. Tools.errorsCount = 0;
  4684. Tools.Log = Tools._LogEnabled;
  4685. Tools.Warn = Tools._WarnEnabled;
  4686. Tools.Error = Tools._ErrorEnabled;
  4687. // Performances
  4688. Tools._PerformanceNoneLogLevel = 0;
  4689. Tools._PerformanceUserMarkLogLevel = 1;
  4690. Tools._PerformanceConsoleLogLevel = 2;
  4691. Tools._performance = window.performance;
  4692. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4693. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4694. return Tools;
  4695. })();
  4696. BABYLON.Tools = Tools;
  4697. /**
  4698. * An implementation of a loop for asynchronous functions.
  4699. */
  4700. var AsyncLoop = (function () {
  4701. /**
  4702. * Constroctor.
  4703. * @param iterations the number of iterations.
  4704. * @param _fn the function to run each iteration
  4705. * @param _successCallback the callback that will be called upon succesful execution
  4706. * @param offset starting offset.
  4707. */
  4708. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4709. if (offset === void 0) { offset = 0; }
  4710. this.iterations = iterations;
  4711. this._fn = _fn;
  4712. this._successCallback = _successCallback;
  4713. this.index = offset - 1;
  4714. this._done = false;
  4715. }
  4716. /**
  4717. * Execute the next iteration. Must be called after the last iteration was finished.
  4718. */
  4719. AsyncLoop.prototype.executeNext = function () {
  4720. if (!this._done) {
  4721. if (this.index + 1 < this.iterations) {
  4722. ++this.index;
  4723. this._fn(this);
  4724. }
  4725. else {
  4726. this.breakLoop();
  4727. }
  4728. }
  4729. };
  4730. /**
  4731. * Break the loop and run the success callback.
  4732. */
  4733. AsyncLoop.prototype.breakLoop = function () {
  4734. this._done = true;
  4735. this._successCallback();
  4736. };
  4737. /**
  4738. * Helper function
  4739. */
  4740. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4741. if (offset === void 0) { offset = 0; }
  4742. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4743. loop.executeNext();
  4744. return loop;
  4745. };
  4746. /**
  4747. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4748. * @param iterations total number of iterations
  4749. * @param syncedIterations number of synchronous iterations in each async iteration.
  4750. * @param fn the function to call each iteration.
  4751. * @param callback a success call back that will be called when iterating stops.
  4752. * @param breakFunction a break condition (optional)
  4753. * @param timeout timeout settings for the setTimeout function. default - 0.
  4754. * @constructor
  4755. */
  4756. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4757. if (timeout === void 0) { timeout = 0; }
  4758. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4759. if (breakFunction && breakFunction())
  4760. loop.breakLoop();
  4761. else {
  4762. setTimeout(function () {
  4763. for (var i = 0; i < syncedIterations; ++i) {
  4764. var iteration = (loop.index * syncedIterations) + i;
  4765. if (iteration >= iterations)
  4766. break;
  4767. fn(iteration);
  4768. if (breakFunction && breakFunction()) {
  4769. loop.breakLoop();
  4770. break;
  4771. }
  4772. }
  4773. loop.executeNext();
  4774. }, timeout);
  4775. }
  4776. }, callback);
  4777. };
  4778. return AsyncLoop;
  4779. })();
  4780. BABYLON.AsyncLoop = AsyncLoop;
  4781. })(BABYLON || (BABYLON = {}));
  4782. var BABYLON;
  4783. (function (BABYLON) {
  4784. var _DepthCullingState = (function () {
  4785. function _DepthCullingState() {
  4786. this._isDepthTestDirty = false;
  4787. this._isDepthMaskDirty = false;
  4788. this._isDepthFuncDirty = false;
  4789. this._isCullFaceDirty = false;
  4790. this._isCullDirty = false;
  4791. this._isZOffsetDirty = false;
  4792. }
  4793. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4794. get: function () {
  4795. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4801. get: function () {
  4802. return this._zOffset;
  4803. },
  4804. set: function (value) {
  4805. if (this._zOffset === value) {
  4806. return;
  4807. }
  4808. this._zOffset = value;
  4809. this._isZOffsetDirty = true;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4815. get: function () {
  4816. return this._cullFace;
  4817. },
  4818. set: function (value) {
  4819. if (this._cullFace === value) {
  4820. return;
  4821. }
  4822. this._cullFace = value;
  4823. this._isCullFaceDirty = true;
  4824. },
  4825. enumerable: true,
  4826. configurable: true
  4827. });
  4828. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4829. get: function () {
  4830. return this._cull;
  4831. },
  4832. set: function (value) {
  4833. if (this._cull === value) {
  4834. return;
  4835. }
  4836. this._cull = value;
  4837. this._isCullDirty = true;
  4838. },
  4839. enumerable: true,
  4840. configurable: true
  4841. });
  4842. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4843. get: function () {
  4844. return this._depthFunc;
  4845. },
  4846. set: function (value) {
  4847. if (this._depthFunc === value) {
  4848. return;
  4849. }
  4850. this._depthFunc = value;
  4851. this._isDepthFuncDirty = true;
  4852. },
  4853. enumerable: true,
  4854. configurable: true
  4855. });
  4856. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4857. get: function () {
  4858. return this._depthMask;
  4859. },
  4860. set: function (value) {
  4861. if (this._depthMask === value) {
  4862. return;
  4863. }
  4864. this._depthMask = value;
  4865. this._isDepthMaskDirty = true;
  4866. },
  4867. enumerable: true,
  4868. configurable: true
  4869. });
  4870. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4871. get: function () {
  4872. return this._depthTest;
  4873. },
  4874. set: function (value) {
  4875. if (this._depthTest === value) {
  4876. return;
  4877. }
  4878. this._depthTest = value;
  4879. this._isDepthTestDirty = true;
  4880. },
  4881. enumerable: true,
  4882. configurable: true
  4883. });
  4884. _DepthCullingState.prototype.reset = function () {
  4885. this._depthMask = true;
  4886. this._depthTest = true;
  4887. this._depthFunc = null;
  4888. this._cull = null;
  4889. this._cullFace = null;
  4890. this._zOffset = 0;
  4891. this._isDepthTestDirty = true;
  4892. this._isDepthMaskDirty = true;
  4893. this._isDepthFuncDirty = false;
  4894. this._isCullFaceDirty = false;
  4895. this._isCullDirty = false;
  4896. this._isZOffsetDirty = false;
  4897. };
  4898. _DepthCullingState.prototype.apply = function (gl) {
  4899. if (!this.isDirty) {
  4900. return;
  4901. }
  4902. // Cull
  4903. if (this._isCullDirty) {
  4904. if (this.cull) {
  4905. gl.enable(gl.CULL_FACE);
  4906. }
  4907. else {
  4908. gl.disable(gl.CULL_FACE);
  4909. }
  4910. this._isCullDirty = false;
  4911. }
  4912. // Cull face
  4913. if (this._isCullFaceDirty) {
  4914. gl.cullFace(this.cullFace);
  4915. this._isCullFaceDirty = false;
  4916. }
  4917. // Depth mask
  4918. if (this._isDepthMaskDirty) {
  4919. gl.depthMask(this.depthMask);
  4920. this._isDepthMaskDirty = false;
  4921. }
  4922. // Depth test
  4923. if (this._isDepthTestDirty) {
  4924. if (this.depthTest) {
  4925. gl.enable(gl.DEPTH_TEST);
  4926. }
  4927. else {
  4928. gl.disable(gl.DEPTH_TEST);
  4929. }
  4930. this._isDepthTestDirty = false;
  4931. }
  4932. // Depth func
  4933. if (this._isDepthFuncDirty) {
  4934. gl.depthFunc(this.depthFunc);
  4935. this._isDepthFuncDirty = false;
  4936. }
  4937. // zOffset
  4938. if (this._isZOffsetDirty) {
  4939. if (this.zOffset) {
  4940. gl.enable(gl.POLYGON_OFFSET_FILL);
  4941. gl.polygonOffset(this.zOffset, 0);
  4942. }
  4943. else {
  4944. gl.disable(gl.POLYGON_OFFSET_FILL);
  4945. }
  4946. this._isZOffsetDirty = false;
  4947. }
  4948. };
  4949. return _DepthCullingState;
  4950. })();
  4951. BABYLON._DepthCullingState = _DepthCullingState;
  4952. var _AlphaState = (function () {
  4953. function _AlphaState() {
  4954. this._isAlphaBlendDirty = false;
  4955. this._isBlendFunctionParametersDirty = false;
  4956. this._alphaBlend = false;
  4957. this._blendFunctionParameters = new Array(4);
  4958. }
  4959. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4960. get: function () {
  4961. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4967. get: function () {
  4968. return this._alphaBlend;
  4969. },
  4970. set: function (value) {
  4971. if (this._alphaBlend === value) {
  4972. return;
  4973. }
  4974. this._alphaBlend = value;
  4975. this._isAlphaBlendDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4981. if (this._blendFunctionParameters[0] === value0 &&
  4982. this._blendFunctionParameters[1] === value1 &&
  4983. this._blendFunctionParameters[2] === value2 &&
  4984. this._blendFunctionParameters[3] === value3) {
  4985. return;
  4986. }
  4987. this._blendFunctionParameters[0] = value0;
  4988. this._blendFunctionParameters[1] = value1;
  4989. this._blendFunctionParameters[2] = value2;
  4990. this._blendFunctionParameters[3] = value3;
  4991. this._isBlendFunctionParametersDirty = true;
  4992. };
  4993. _AlphaState.prototype.reset = function () {
  4994. this._alphaBlend = false;
  4995. this._blendFunctionParameters[0] = null;
  4996. this._blendFunctionParameters[1] = null;
  4997. this._blendFunctionParameters[2] = null;
  4998. this._blendFunctionParameters[3] = null;
  4999. this._isAlphaBlendDirty = true;
  5000. this._isBlendFunctionParametersDirty = false;
  5001. };
  5002. _AlphaState.prototype.apply = function (gl) {
  5003. if (!this.isDirty) {
  5004. return;
  5005. }
  5006. // Alpha blend
  5007. if (this._isAlphaBlendDirty) {
  5008. if (this._alphaBlend) {
  5009. gl.enable(gl.BLEND);
  5010. }
  5011. else {
  5012. gl.disable(gl.BLEND);
  5013. }
  5014. this._isAlphaBlendDirty = false;
  5015. }
  5016. // Alpha function
  5017. if (this._isBlendFunctionParametersDirty) {
  5018. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5019. this._isBlendFunctionParametersDirty = false;
  5020. }
  5021. };
  5022. return _AlphaState;
  5023. })();
  5024. BABYLON._AlphaState = _AlphaState;
  5025. var compileShader = function (gl, source, type, defines) {
  5026. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5027. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5028. gl.compileShader(shader);
  5029. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5030. throw new Error(gl.getShaderInfoLog(shader));
  5031. }
  5032. return shader;
  5033. };
  5034. var getWebGLTextureType = function (gl, type) {
  5035. var textureType = gl.UNSIGNED_BYTE;
  5036. if (type === Engine.TEXTURETYPE_FLOAT)
  5037. textureType = gl.FLOAT;
  5038. return textureType;
  5039. };
  5040. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5041. var magFilter = gl.NEAREST;
  5042. var minFilter = gl.NEAREST;
  5043. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5044. magFilter = gl.LINEAR;
  5045. if (generateMipMaps) {
  5046. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5047. }
  5048. else {
  5049. minFilter = gl.LINEAR;
  5050. }
  5051. }
  5052. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5053. magFilter = gl.LINEAR;
  5054. if (generateMipMaps) {
  5055. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5056. }
  5057. else {
  5058. minFilter = gl.LINEAR;
  5059. }
  5060. }
  5061. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5062. magFilter = gl.NEAREST;
  5063. if (generateMipMaps) {
  5064. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5065. }
  5066. else {
  5067. minFilter = gl.NEAREST;
  5068. }
  5069. }
  5070. return {
  5071. min: minFilter,
  5072. mag: magFilter
  5073. };
  5074. };
  5075. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5077. var engine = scene.getEngine();
  5078. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5079. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5080. gl.bindTexture(gl.TEXTURE_2D, texture);
  5081. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5082. texture._baseWidth = width;
  5083. texture._baseHeight = height;
  5084. texture._width = potWidth;
  5085. texture._height = potHeight;
  5086. texture.isReady = true;
  5087. processFunction(potWidth, potHeight);
  5088. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5091. if (!noMipmap && !isCompressed) {
  5092. gl.generateMipmap(gl.TEXTURE_2D);
  5093. }
  5094. gl.bindTexture(gl.TEXTURE_2D, null);
  5095. engine.resetTextureCache();
  5096. scene._removePendingData(texture);
  5097. };
  5098. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5099. var img;
  5100. var onload = function () {
  5101. loadedImages[index] = img;
  5102. loadedImages._internalCount++;
  5103. scene._removePendingData(img);
  5104. if (loadedImages._internalCount === 6) {
  5105. onfinish(loadedImages);
  5106. }
  5107. };
  5108. var onerror = function () {
  5109. scene._removePendingData(img);
  5110. };
  5111. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5112. scene._addPendingData(img);
  5113. };
  5114. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5115. var loadedImages = [];
  5116. loadedImages._internalCount = 0;
  5117. for (var index = 0; index < 6; index++) {
  5118. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5119. }
  5120. };
  5121. var EngineCapabilities = (function () {
  5122. function EngineCapabilities() {
  5123. }
  5124. return EngineCapabilities;
  5125. })();
  5126. BABYLON.EngineCapabilities = EngineCapabilities;
  5127. /**
  5128. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5129. */
  5130. var Engine = (function () {
  5131. /**
  5132. * @constructor
  5133. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5134. * @param {boolean} [antialias] - enable antialias
  5135. * @param options - further options to be sent to the getContext function
  5136. */
  5137. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5138. var _this = this;
  5139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5140. // Public members
  5141. this.isFullscreen = false;
  5142. this.isPointerLock = false;
  5143. this.cullBackFaces = true;
  5144. this.renderEvenInBackground = true;
  5145. // To enable/disable IDB support and avoid XHR on .manifest
  5146. this.enableOfflineSupport = true;
  5147. this.scenes = new Array();
  5148. this._windowIsBackground = false;
  5149. this._drawCalls = 0;
  5150. this._renderingQueueLaunched = false;
  5151. this._activeRenderLoops = [];
  5152. // FPS
  5153. this.fpsRange = 60;
  5154. this.previousFramesDuration = [];
  5155. this.fps = 60;
  5156. this.deltaTime = 0;
  5157. // States
  5158. this._depthCullingState = new _DepthCullingState();
  5159. this._alphaState = new _AlphaState();
  5160. this._alphaMode = Engine.ALPHA_DISABLE;
  5161. // Cache
  5162. this._loadedTexturesCache = new Array();
  5163. this._maxTextureChannels = 16;
  5164. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5165. this._compiledEffects = {};
  5166. this._uintIndicesCurrentlySet = false;
  5167. this._renderingCanvas = canvas;
  5168. options = options || {};
  5169. options.antialias = antialias;
  5170. if (options.preserveDrawingBuffer === undefined) {
  5171. options.preserveDrawingBuffer = false;
  5172. }
  5173. // GL
  5174. try {
  5175. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5176. }
  5177. catch (e) {
  5178. throw new Error("WebGL not supported");
  5179. }
  5180. if (!this._gl) {
  5181. throw new Error("WebGL not supported");
  5182. }
  5183. this._onBlur = function () {
  5184. _this._windowIsBackground = true;
  5185. };
  5186. this._onFocus = function () {
  5187. _this._windowIsBackground = false;
  5188. };
  5189. window.addEventListener("blur", this._onBlur);
  5190. window.addEventListener("focus", this._onFocus);
  5191. // Viewport
  5192. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5193. this.resize();
  5194. // Caps
  5195. this._caps = new EngineCapabilities();
  5196. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5197. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5198. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5199. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5200. // Infos
  5201. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5202. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5203. if (rendererInfo != null) {
  5204. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5205. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5206. }
  5207. if (!this._glVendor) {
  5208. this._glVendor = "Unknown vendor";
  5209. }
  5210. if (!this._glRenderer) {
  5211. this._glRenderer = "Unknown renderer";
  5212. }
  5213. // Extensions
  5214. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5215. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5216. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5217. 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');
  5218. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5219. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5220. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5221. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5222. this._caps.highPrecisionShaderSupported = true;
  5223. if (this._gl.getShaderPrecisionFormat) {
  5224. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5225. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5226. }
  5227. // Depth buffer
  5228. this.setDepthBuffer(true);
  5229. this.setDepthFunctionToLessOrEqual();
  5230. this.setDepthWrite(true);
  5231. // Fullscreen
  5232. this._onFullscreenChange = function () {
  5233. if (document.fullscreen !== undefined) {
  5234. _this.isFullscreen = document.fullscreen;
  5235. }
  5236. else if (document.mozFullScreen !== undefined) {
  5237. _this.isFullscreen = document.mozFullScreen;
  5238. }
  5239. else if (document.webkitIsFullScreen !== undefined) {
  5240. _this.isFullscreen = document.webkitIsFullScreen;
  5241. }
  5242. else if (document.msIsFullScreen !== undefined) {
  5243. _this.isFullscreen = document.msIsFullScreen;
  5244. }
  5245. // Pointer lock
  5246. if (_this.isFullscreen && _this._pointerLockRequested) {
  5247. canvas.requestPointerLock = canvas.requestPointerLock ||
  5248. canvas.msRequestPointerLock ||
  5249. canvas.mozRequestPointerLock ||
  5250. canvas.webkitRequestPointerLock;
  5251. if (canvas.requestPointerLock) {
  5252. canvas.requestPointerLock();
  5253. }
  5254. }
  5255. };
  5256. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5257. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5258. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5259. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5260. // Pointer lock
  5261. this._onPointerLockChange = function () {
  5262. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5263. document.webkitPointerLockElement === canvas ||
  5264. document.msPointerLockElement === canvas ||
  5265. document.pointerLockElement === canvas);
  5266. };
  5267. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5268. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5269. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5270. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5271. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5272. Engine.audioEngine = new BABYLON.AudioEngine();
  5273. }
  5274. //default loading screen
  5275. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5276. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5277. }
  5278. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5279. get: function () {
  5280. return Engine._ALPHA_DISABLE;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5286. get: function () {
  5287. return Engine._ALPHA_ONEONE;
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Object.defineProperty(Engine, "ALPHA_ADD", {
  5293. get: function () {
  5294. return Engine._ALPHA_ADD;
  5295. },
  5296. enumerable: true,
  5297. configurable: true
  5298. });
  5299. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5300. get: function () {
  5301. return Engine._ALPHA_COMBINE;
  5302. },
  5303. enumerable: true,
  5304. configurable: true
  5305. });
  5306. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5307. get: function () {
  5308. return Engine._ALPHA_SUBTRACT;
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5314. get: function () {
  5315. return Engine._ALPHA_MULTIPLY;
  5316. },
  5317. enumerable: true,
  5318. configurable: true
  5319. });
  5320. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5321. get: function () {
  5322. return Engine._ALPHA_MAXIMIZED;
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5328. get: function () {
  5329. return Engine._DELAYLOADSTATE_NONE;
  5330. },
  5331. enumerable: true,
  5332. configurable: true
  5333. });
  5334. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5335. get: function () {
  5336. return Engine._DELAYLOADSTATE_LOADED;
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5342. get: function () {
  5343. return Engine._DELAYLOADSTATE_LOADING;
  5344. },
  5345. enumerable: true,
  5346. configurable: true
  5347. });
  5348. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5349. get: function () {
  5350. return Engine._DELAYLOADSTATE_NOTLOADED;
  5351. },
  5352. enumerable: true,
  5353. configurable: true
  5354. });
  5355. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5356. get: function () {
  5357. return Engine._TEXTUREFORMAT_ALPHA;
  5358. },
  5359. enumerable: true,
  5360. configurable: true
  5361. });
  5362. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5363. get: function () {
  5364. return Engine._TEXTUREFORMAT_LUMINANCE;
  5365. },
  5366. enumerable: true,
  5367. configurable: true
  5368. });
  5369. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5370. get: function () {
  5371. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5372. },
  5373. enumerable: true,
  5374. configurable: true
  5375. });
  5376. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5377. get: function () {
  5378. return Engine._TEXTUREFORMAT_RGB;
  5379. },
  5380. enumerable: true,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5384. get: function () {
  5385. return Engine._TEXTUREFORMAT_RGBA;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5391. get: function () {
  5392. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5393. },
  5394. enumerable: true,
  5395. configurable: true
  5396. });
  5397. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5398. get: function () {
  5399. return Engine._TEXTURETYPE_FLOAT;
  5400. },
  5401. enumerable: true,
  5402. configurable: true
  5403. });
  5404. Object.defineProperty(Engine, "Version", {
  5405. get: function () {
  5406. return "2.3.0-alpha";
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Engine.prototype._prepareWorkingCanvas = function () {
  5412. if (this._workingCanvas) {
  5413. return;
  5414. }
  5415. this._workingCanvas = document.createElement("canvas");
  5416. this._workingContext = this._workingCanvas.getContext("2d");
  5417. };
  5418. Engine.prototype.resetTextureCache = function () {
  5419. for (var index = 0; index < this._maxTextureChannels; index++) {
  5420. this._activeTexturesCache[index] = null;
  5421. }
  5422. };
  5423. Engine.prototype.getGlInfo = function () {
  5424. return {
  5425. vendor: this._glVendor,
  5426. renderer: this._glRenderer,
  5427. version: this._glVersion
  5428. };
  5429. };
  5430. Engine.prototype.getAspectRatio = function (camera) {
  5431. var viewport = camera.viewport;
  5432. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5433. };
  5434. Engine.prototype.getRenderWidth = function () {
  5435. if (this._currentRenderTarget) {
  5436. return this._currentRenderTarget._width;
  5437. }
  5438. return this._renderingCanvas.width;
  5439. };
  5440. Engine.prototype.getRenderHeight = function () {
  5441. if (this._currentRenderTarget) {
  5442. return this._currentRenderTarget._height;
  5443. }
  5444. return this._renderingCanvas.height;
  5445. };
  5446. Engine.prototype.getRenderingCanvas = function () {
  5447. return this._renderingCanvas;
  5448. };
  5449. Engine.prototype.getRenderingCanvasClientRect = function () {
  5450. return this._renderingCanvas.getBoundingClientRect();
  5451. };
  5452. Engine.prototype.setHardwareScalingLevel = function (level) {
  5453. this._hardwareScalingLevel = level;
  5454. this.resize();
  5455. };
  5456. Engine.prototype.getHardwareScalingLevel = function () {
  5457. return this._hardwareScalingLevel;
  5458. };
  5459. Engine.prototype.getLoadedTexturesCache = function () {
  5460. return this._loadedTexturesCache;
  5461. };
  5462. Engine.prototype.getCaps = function () {
  5463. return this._caps;
  5464. };
  5465. Object.defineProperty(Engine.prototype, "drawCalls", {
  5466. get: function () {
  5467. return this._drawCalls;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. // Methods
  5473. Engine.prototype.resetDrawCalls = function () {
  5474. this._drawCalls = 0;
  5475. };
  5476. Engine.prototype.setDepthFunctionToGreater = function () {
  5477. this._depthCullingState.depthFunc = this._gl.GREATER;
  5478. };
  5479. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5480. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5481. };
  5482. Engine.prototype.setDepthFunctionToLess = function () {
  5483. this._depthCullingState.depthFunc = this._gl.LESS;
  5484. };
  5485. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5486. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5487. };
  5488. /**
  5489. * stop executing a render loop function and remove it from the execution array
  5490. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5491. */
  5492. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5493. if (!renderFunction) {
  5494. this._activeRenderLoops = [];
  5495. return;
  5496. }
  5497. var index = this._activeRenderLoops.indexOf(renderFunction);
  5498. if (index >= 0) {
  5499. this._activeRenderLoops.splice(index, 1);
  5500. }
  5501. };
  5502. Engine.prototype._renderLoop = function () {
  5503. var shouldRender = true;
  5504. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5505. shouldRender = false;
  5506. }
  5507. if (shouldRender) {
  5508. // Start new frame
  5509. this.beginFrame();
  5510. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5511. var renderFunction = this._activeRenderLoops[index];
  5512. renderFunction();
  5513. }
  5514. // Present
  5515. this.endFrame();
  5516. }
  5517. if (this._activeRenderLoops.length > 0) {
  5518. // Register new frame
  5519. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5520. }
  5521. else {
  5522. this._renderingQueueLaunched = false;
  5523. }
  5524. };
  5525. /**
  5526. * Register and execute a render loop. The engine can have more than one render function.
  5527. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5528. * @example
  5529. * engine.runRenderLoop(function () {
  5530. * scene.render()
  5531. * })
  5532. */
  5533. Engine.prototype.runRenderLoop = function (renderFunction) {
  5534. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5535. return;
  5536. }
  5537. this._activeRenderLoops.push(renderFunction);
  5538. if (!this._renderingQueueLaunched) {
  5539. this._renderingQueueLaunched = true;
  5540. this._bindedRenderFunction = this._renderLoop.bind(this);
  5541. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5542. }
  5543. };
  5544. /**
  5545. * Toggle full screen mode.
  5546. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5547. */
  5548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5549. if (this.isFullscreen) {
  5550. BABYLON.Tools.ExitFullscreen();
  5551. }
  5552. else {
  5553. this._pointerLockRequested = requestPointerLock;
  5554. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5555. }
  5556. };
  5557. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5558. this.applyStates();
  5559. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5560. if (this._depthCullingState.depthMask) {
  5561. this._gl.clearDepth(1.0);
  5562. }
  5563. var mode = 0;
  5564. if (backBuffer)
  5565. mode |= this._gl.COLOR_BUFFER_BIT;
  5566. if (depthStencil && this._depthCullingState.depthMask)
  5567. mode |= this._gl.DEPTH_BUFFER_BIT;
  5568. this._gl.clear(mode);
  5569. };
  5570. /**
  5571. * Set the WebGL's viewport
  5572. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5573. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5574. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5575. */
  5576. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5577. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5578. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5579. var x = viewport.x || 0;
  5580. var y = viewport.y || 0;
  5581. this._cachedViewport = viewport;
  5582. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5583. };
  5584. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5585. this._cachedViewport = null;
  5586. this._gl.viewport(x, y, width, height);
  5587. };
  5588. Engine.prototype.beginFrame = function () {
  5589. this._measureFps();
  5590. };
  5591. Engine.prototype.endFrame = function () {
  5592. //this.flushFramebuffer();
  5593. };
  5594. /**
  5595. * resize the view according to the canvas' size.
  5596. * @example
  5597. * window.addEventListener("resize", function () {
  5598. * engine.resize();
  5599. * });
  5600. */
  5601. Engine.prototype.resize = function () {
  5602. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5603. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5604. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5605. for (var index = 0; index < this.scenes.length; index++) {
  5606. var scene = this.scenes[index];
  5607. if (scene.debugLayer.isVisible()) {
  5608. scene.debugLayer._syncPositions();
  5609. }
  5610. }
  5611. };
  5612. /**
  5613. * force a specific size of the canvas
  5614. * @param {number} width - the new canvas' width
  5615. * @param {number} height - the new canvas' height
  5616. */
  5617. Engine.prototype.setSize = function (width, height) {
  5618. this._renderingCanvas.width = width;
  5619. this._renderingCanvas.height = height;
  5620. for (var index = 0; index < this.scenes.length; index++) {
  5621. var scene = this.scenes[index];
  5622. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5623. var cam = scene.cameras[camIndex];
  5624. cam._currentRenderId = 0;
  5625. }
  5626. }
  5627. };
  5628. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5629. this._currentRenderTarget = texture;
  5630. var gl = this._gl;
  5631. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5632. if (texture.isCube) {
  5633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5634. }
  5635. else {
  5636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5637. }
  5638. this._gl.viewport(0, 0, texture._width, texture._height);
  5639. this.wipeCaches();
  5640. };
  5641. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5642. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5643. this._currentRenderTarget = null;
  5644. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5645. var gl = this._gl;
  5646. gl.bindTexture(gl.TEXTURE_2D, texture);
  5647. gl.generateMipmap(gl.TEXTURE_2D);
  5648. gl.bindTexture(gl.TEXTURE_2D, null);
  5649. }
  5650. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5651. };
  5652. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5653. if (texture.generateMipMaps) {
  5654. var gl = this._gl;
  5655. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5656. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5657. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5658. }
  5659. };
  5660. Engine.prototype.flushFramebuffer = function () {
  5661. this._gl.flush();
  5662. };
  5663. Engine.prototype.restoreDefaultFramebuffer = function () {
  5664. this._currentRenderTarget = null;
  5665. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5666. this.setViewport(this._cachedViewport);
  5667. this.wipeCaches();
  5668. };
  5669. // VBOs
  5670. Engine.prototype._resetVertexBufferBinding = function () {
  5671. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5672. this._cachedVertexBuffers = null;
  5673. };
  5674. Engine.prototype.createVertexBuffer = function (vertices) {
  5675. var vbo = this._gl.createBuffer();
  5676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5677. if (vertices instanceof Float32Array) {
  5678. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5679. }
  5680. else {
  5681. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5682. }
  5683. this._resetVertexBufferBinding();
  5684. vbo.references = 1;
  5685. return vbo;
  5686. };
  5687. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5688. var vbo = this._gl.createBuffer();
  5689. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5690. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5691. this._resetVertexBufferBinding();
  5692. vbo.references = 1;
  5693. return vbo;
  5694. };
  5695. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5696. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5697. if (offset === undefined) {
  5698. offset = 0;
  5699. }
  5700. if (vertices instanceof Float32Array) {
  5701. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5702. }
  5703. else {
  5704. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5705. }
  5706. this._resetVertexBufferBinding();
  5707. };
  5708. Engine.prototype._resetIndexBufferBinding = function () {
  5709. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5710. this._cachedIndexBuffer = null;
  5711. };
  5712. Engine.prototype.createIndexBuffer = function (indices) {
  5713. var vbo = this._gl.createBuffer();
  5714. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5715. // Check for 32 bits indices
  5716. var arrayBuffer;
  5717. var need32Bits = false;
  5718. if (this._caps.uintIndices) {
  5719. for (var index = 0; index < indices.length; index++) {
  5720. if (indices[index] > 65535) {
  5721. need32Bits = true;
  5722. break;
  5723. }
  5724. }
  5725. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5726. }
  5727. else {
  5728. arrayBuffer = new Uint16Array(indices);
  5729. }
  5730. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5731. this._resetIndexBufferBinding();
  5732. vbo.references = 1;
  5733. vbo.is32Bits = need32Bits;
  5734. return vbo;
  5735. };
  5736. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5737. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5738. this._cachedVertexBuffers = vertexBuffer;
  5739. this._cachedEffectForVertexBuffers = effect;
  5740. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5741. var offset = 0;
  5742. for (var index = 0; index < vertexDeclaration.length; index++) {
  5743. var order = effect.getAttributeLocation(index);
  5744. if (order >= 0) {
  5745. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5746. }
  5747. offset += vertexDeclaration[index] * 4;
  5748. }
  5749. }
  5750. if (this._cachedIndexBuffer !== indexBuffer) {
  5751. this._cachedIndexBuffer = indexBuffer;
  5752. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5753. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5754. }
  5755. };
  5756. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5757. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5758. this._cachedVertexBuffers = vertexBuffers;
  5759. this._cachedEffectForVertexBuffers = effect;
  5760. var attributes = effect.getAttributesNames();
  5761. for (var index = 0; index < attributes.length; index++) {
  5762. var order = effect.getAttributeLocation(index);
  5763. if (order >= 0) {
  5764. var vertexBuffer = vertexBuffers[attributes[index]];
  5765. if (!vertexBuffer) {
  5766. continue;
  5767. }
  5768. var stride = vertexBuffer.getStrideSize();
  5769. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5770. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5771. }
  5772. }
  5773. }
  5774. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5775. this._cachedIndexBuffer = indexBuffer;
  5776. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5777. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5778. }
  5779. };
  5780. Engine.prototype._releaseBuffer = function (buffer) {
  5781. buffer.references--;
  5782. if (buffer.references === 0) {
  5783. this._gl.deleteBuffer(buffer);
  5784. return true;
  5785. }
  5786. return false;
  5787. };
  5788. Engine.prototype.createInstancesBuffer = function (capacity) {
  5789. var buffer = this._gl.createBuffer();
  5790. buffer.capacity = capacity;
  5791. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5792. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5793. return buffer;
  5794. };
  5795. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5796. this._gl.deleteBuffer(buffer);
  5797. };
  5798. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5799. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5801. for (var index = 0; index < 4; index++) {
  5802. var offsetLocation = offsetLocations[index];
  5803. this._gl.enableVertexAttribArray(offsetLocation);
  5804. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5805. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5806. }
  5807. };
  5808. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5809. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5810. for (var index = 0; index < 4; index++) {
  5811. var offsetLocation = offsetLocations[index];
  5812. this._gl.disableVertexAttribArray(offsetLocation);
  5813. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5814. }
  5815. };
  5816. Engine.prototype.applyStates = function () {
  5817. this._depthCullingState.apply(this._gl);
  5818. this._alphaState.apply(this._gl);
  5819. };
  5820. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5821. // Apply states
  5822. this.applyStates();
  5823. this._drawCalls++;
  5824. // Render
  5825. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5826. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5827. if (instancesCount) {
  5828. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5829. return;
  5830. }
  5831. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5832. };
  5833. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5834. // Apply states
  5835. this.applyStates();
  5836. this._drawCalls++;
  5837. if (instancesCount) {
  5838. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5839. return;
  5840. }
  5841. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5842. };
  5843. // Shaders
  5844. Engine.prototype._releaseEffect = function (effect) {
  5845. if (this._compiledEffects[effect._key]) {
  5846. delete this._compiledEffects[effect._key];
  5847. if (effect.getProgram()) {
  5848. this._gl.deleteProgram(effect.getProgram());
  5849. }
  5850. }
  5851. };
  5852. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5853. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5854. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5855. var name = vertex + "+" + fragment + "@" + defines;
  5856. if (this._compiledEffects[name]) {
  5857. return this._compiledEffects[name];
  5858. }
  5859. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5860. effect._key = name;
  5861. this._compiledEffects[name] = effect;
  5862. return effect;
  5863. };
  5864. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5865. if (uniformsNames === void 0) { uniformsNames = []; }
  5866. if (samplers === void 0) { samplers = []; }
  5867. if (defines === void 0) { defines = ""; }
  5868. return this.createEffect({
  5869. vertex: "particles",
  5870. fragmentElement: fragmentName
  5871. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5872. };
  5873. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5874. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5875. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5876. var shaderProgram = this._gl.createProgram();
  5877. this._gl.attachShader(shaderProgram, vertexShader);
  5878. this._gl.attachShader(shaderProgram, fragmentShader);
  5879. this._gl.linkProgram(shaderProgram);
  5880. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5881. if (!linked) {
  5882. var error = this._gl.getProgramInfoLog(shaderProgram);
  5883. if (error) {
  5884. throw new Error(error);
  5885. }
  5886. }
  5887. this._gl.deleteShader(vertexShader);
  5888. this._gl.deleteShader(fragmentShader);
  5889. return shaderProgram;
  5890. };
  5891. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5892. var results = [];
  5893. for (var index = 0; index < uniformsNames.length; index++) {
  5894. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5895. }
  5896. return results;
  5897. };
  5898. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5899. var results = [];
  5900. for (var index = 0; index < attributesNames.length; index++) {
  5901. try {
  5902. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5903. }
  5904. catch (e) {
  5905. results.push(-1);
  5906. }
  5907. }
  5908. return results;
  5909. };
  5910. Engine.prototype.enableEffect = function (effect) {
  5911. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5912. if (effect && effect.onBind) {
  5913. effect.onBind(effect);
  5914. }
  5915. return;
  5916. }
  5917. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5918. // Use program
  5919. this._gl.useProgram(effect.getProgram());
  5920. for (var i in this._vertexAttribArrays) {
  5921. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5922. continue;
  5923. }
  5924. this._vertexAttribArrays[i] = false;
  5925. this._gl.disableVertexAttribArray(i);
  5926. }
  5927. var attributesCount = effect.getAttributesCount();
  5928. for (var index = 0; index < attributesCount; index++) {
  5929. // Attributes
  5930. var order = effect.getAttributeLocation(index);
  5931. if (order >= 0) {
  5932. this._vertexAttribArrays[order] = true;
  5933. this._gl.enableVertexAttribArray(order);
  5934. }
  5935. }
  5936. this._currentEffect = effect;
  5937. if (effect.onBind) {
  5938. effect.onBind(effect);
  5939. }
  5940. };
  5941. Engine.prototype.setArray = function (uniform, array) {
  5942. if (!uniform)
  5943. return;
  5944. this._gl.uniform1fv(uniform, array);
  5945. };
  5946. Engine.prototype.setArray2 = function (uniform, array) {
  5947. if (!uniform || array.length % 2 !== 0)
  5948. return;
  5949. this._gl.uniform2fv(uniform, array);
  5950. };
  5951. Engine.prototype.setArray3 = function (uniform, array) {
  5952. if (!uniform || array.length % 3 !== 0)
  5953. return;
  5954. this._gl.uniform3fv(uniform, array);
  5955. };
  5956. Engine.prototype.setArray4 = function (uniform, array) {
  5957. if (!uniform || array.length % 4 !== 0)
  5958. return;
  5959. this._gl.uniform4fv(uniform, array);
  5960. };
  5961. Engine.prototype.setMatrices = function (uniform, matrices) {
  5962. if (!uniform)
  5963. return;
  5964. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5965. };
  5966. Engine.prototype.setMatrix = function (uniform, matrix) {
  5967. if (!uniform)
  5968. return;
  5969. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5970. };
  5971. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5972. if (!uniform)
  5973. return;
  5974. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5975. };
  5976. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5977. if (!uniform)
  5978. return;
  5979. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5980. };
  5981. Engine.prototype.setFloat = function (uniform, value) {
  5982. if (!uniform)
  5983. return;
  5984. this._gl.uniform1f(uniform, value);
  5985. };
  5986. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5987. if (!uniform)
  5988. return;
  5989. this._gl.uniform2f(uniform, x, y);
  5990. };
  5991. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5992. if (!uniform)
  5993. return;
  5994. this._gl.uniform3f(uniform, x, y, z);
  5995. };
  5996. Engine.prototype.setBool = function (uniform, bool) {
  5997. if (!uniform)
  5998. return;
  5999. this._gl.uniform1i(uniform, bool);
  6000. };
  6001. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6002. if (!uniform)
  6003. return;
  6004. this._gl.uniform4f(uniform, x, y, z, w);
  6005. };
  6006. Engine.prototype.setColor3 = function (uniform, color3) {
  6007. if (!uniform)
  6008. return;
  6009. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6010. };
  6011. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6012. if (!uniform)
  6013. return;
  6014. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6015. };
  6016. // States
  6017. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6018. if (zOffset === void 0) { zOffset = 0; }
  6019. if (reverseSide === void 0) { reverseSide = false; }
  6020. // Culling
  6021. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6022. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6023. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6024. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6025. if (culling) {
  6026. this._depthCullingState.cullFace = cullFace;
  6027. this._depthCullingState.cull = true;
  6028. }
  6029. else {
  6030. this._depthCullingState.cull = false;
  6031. }
  6032. }
  6033. // Z offset
  6034. this._depthCullingState.zOffset = zOffset;
  6035. };
  6036. Engine.prototype.setDepthBuffer = function (enable) {
  6037. this._depthCullingState.depthTest = enable;
  6038. };
  6039. Engine.prototype.getDepthWrite = function () {
  6040. return this._depthCullingState.depthMask;
  6041. };
  6042. Engine.prototype.setDepthWrite = function (enable) {
  6043. this._depthCullingState.depthMask = enable;
  6044. };
  6045. Engine.prototype.setColorWrite = function (enable) {
  6046. this._gl.colorMask(enable, enable, enable, enable);
  6047. };
  6048. Engine.prototype.setAlphaMode = function (mode) {
  6049. if (this._alphaMode === mode) {
  6050. return;
  6051. }
  6052. switch (mode) {
  6053. case Engine.ALPHA_DISABLE:
  6054. this.setDepthWrite(true);
  6055. this._alphaState.alphaBlend = false;
  6056. break;
  6057. case Engine.ALPHA_COMBINE:
  6058. this.setDepthWrite(false);
  6059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6060. this._alphaState.alphaBlend = true;
  6061. break;
  6062. case Engine.ALPHA_ONEONE:
  6063. this.setDepthWrite(false);
  6064. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6065. this._alphaState.alphaBlend = true;
  6066. break;
  6067. case Engine.ALPHA_ADD:
  6068. this.setDepthWrite(false);
  6069. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6070. this._alphaState.alphaBlend = true;
  6071. break;
  6072. case Engine.ALPHA_SUBTRACT:
  6073. this.setDepthWrite(false);
  6074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6075. this._alphaState.alphaBlend = true;
  6076. break;
  6077. case Engine.ALPHA_MULTIPLY:
  6078. this.setDepthWrite(false);
  6079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6080. this._alphaState.alphaBlend = true;
  6081. break;
  6082. case Engine.ALPHA_MAXIMIZED:
  6083. this.setDepthWrite(false);
  6084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6085. this._alphaState.alphaBlend = true;
  6086. break;
  6087. }
  6088. this._alphaMode = mode;
  6089. };
  6090. Engine.prototype.getAlphaMode = function () {
  6091. return this._alphaMode;
  6092. };
  6093. Engine.prototype.setAlphaTesting = function (enable) {
  6094. this._alphaTest = enable;
  6095. };
  6096. Engine.prototype.getAlphaTesting = function () {
  6097. return this._alphaTest;
  6098. };
  6099. // Textures
  6100. Engine.prototype.wipeCaches = function () {
  6101. this.resetTextureCache();
  6102. this._currentEffect = null;
  6103. this._depthCullingState.reset();
  6104. this._alphaState.reset();
  6105. this._cachedVertexBuffers = null;
  6106. this._cachedIndexBuffer = null;
  6107. this._cachedEffectForVertexBuffers = null;
  6108. };
  6109. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6110. var gl = this._gl;
  6111. gl.bindTexture(gl.TEXTURE_2D, texture);
  6112. var magFilter = gl.NEAREST;
  6113. var minFilter = gl.NEAREST;
  6114. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6115. magFilter = gl.LINEAR;
  6116. minFilter = gl.LINEAR;
  6117. }
  6118. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6119. magFilter = gl.LINEAR;
  6120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6121. }
  6122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6124. gl.bindTexture(gl.TEXTURE_2D, null);
  6125. texture.samplingMode = samplingMode;
  6126. };
  6127. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6128. var _this = this;
  6129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6130. if (onLoad === void 0) { onLoad = null; }
  6131. if (onError === void 0) { onError = null; }
  6132. if (buffer === void 0) { buffer = null; }
  6133. var texture = this._gl.createTexture();
  6134. var extension;
  6135. var fromData = false;
  6136. if (url.substr(0, 5) === "data:") {
  6137. fromData = true;
  6138. }
  6139. if (!fromData)
  6140. extension = url.substr(url.length - 4, 4).toLowerCase();
  6141. else {
  6142. var oldUrl = url;
  6143. fromData = oldUrl.split(':');
  6144. url = oldUrl;
  6145. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6146. }
  6147. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6148. var isTGA = (extension === ".tga");
  6149. scene._addPendingData(texture);
  6150. texture.url = url;
  6151. texture.noMipmap = noMipmap;
  6152. texture.references = 1;
  6153. texture.samplingMode = samplingMode;
  6154. this._loadedTexturesCache.push(texture);
  6155. var onerror = function () {
  6156. scene._removePendingData(texture);
  6157. if (onError) {
  6158. onError();
  6159. }
  6160. };
  6161. var callback;
  6162. if (isTGA) {
  6163. callback = function (arrayBuffer) {
  6164. var data = new Uint8Array(arrayBuffer);
  6165. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6166. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6167. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6168. if (onLoad) {
  6169. onLoad();
  6170. }
  6171. }, samplingMode);
  6172. };
  6173. if (!(fromData instanceof Array))
  6174. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6175. callback(arrayBuffer);
  6176. }, onerror, scene.database, true);
  6177. else
  6178. callback(buffer);
  6179. }
  6180. else if (isDDS) {
  6181. callback = function (data) {
  6182. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6183. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6184. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6185. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6186. if (onLoad) {
  6187. onLoad();
  6188. }
  6189. }, samplingMode);
  6190. };
  6191. if (!(fromData instanceof Array))
  6192. BABYLON.Tools.LoadFile(url, function (data) {
  6193. callback(data);
  6194. }, onerror, scene.database, true);
  6195. else
  6196. callback(buffer);
  6197. }
  6198. else {
  6199. var onload = function (img) {
  6200. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6201. var isPot = (img.width === potWidth && img.height === potHeight);
  6202. if (!isPot) {
  6203. _this._prepareWorkingCanvas();
  6204. _this._workingCanvas.width = potWidth;
  6205. _this._workingCanvas.height = potHeight;
  6206. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6207. _this._workingContext.imageSmoothingEnabled = false;
  6208. _this._workingContext.mozImageSmoothingEnabled = false;
  6209. _this._workingContext.oImageSmoothingEnabled = false;
  6210. _this._workingContext.webkitImageSmoothingEnabled = false;
  6211. _this._workingContext.msImageSmoothingEnabled = false;
  6212. }
  6213. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6214. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6215. _this._workingContext.imageSmoothingEnabled = true;
  6216. _this._workingContext.mozImageSmoothingEnabled = true;
  6217. _this._workingContext.oImageSmoothingEnabled = true;
  6218. _this._workingContext.webkitImageSmoothingEnabled = true;
  6219. _this._workingContext.msImageSmoothingEnabled = true;
  6220. }
  6221. }
  6222. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6223. if (onLoad) {
  6224. onLoad();
  6225. }
  6226. }, samplingMode);
  6227. };
  6228. if (!(fromData instanceof Array))
  6229. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6230. else
  6231. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6232. }
  6233. return texture;
  6234. };
  6235. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6236. if (compression === void 0) { compression = null; }
  6237. var internalFormat = this._gl.RGBA;
  6238. switch (format) {
  6239. case Engine.TEXTUREFORMAT_ALPHA:
  6240. internalFormat = this._gl.ALPHA;
  6241. break;
  6242. case Engine.TEXTUREFORMAT_LUMINANCE:
  6243. internalFormat = this._gl.LUMINANCE;
  6244. break;
  6245. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6246. internalFormat = this._gl.LUMINANCE_ALPHA;
  6247. break;
  6248. case Engine.TEXTUREFORMAT_RGB:
  6249. internalFormat = this._gl.RGB;
  6250. break;
  6251. case Engine.TEXTUREFORMAT_RGBA:
  6252. internalFormat = this._gl.RGBA;
  6253. break;
  6254. }
  6255. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6256. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6257. if (compression) {
  6258. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6259. }
  6260. else {
  6261. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6262. }
  6263. if (texture.generateMipMaps) {
  6264. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6265. }
  6266. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6267. this.resetTextureCache();
  6268. texture.isReady = true;
  6269. };
  6270. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6271. if (compression === void 0) { compression = null; }
  6272. var texture = this._gl.createTexture();
  6273. texture._baseWidth = width;
  6274. texture._baseHeight = height;
  6275. texture._width = width;
  6276. texture._height = height;
  6277. texture.references = 1;
  6278. this.updateRawTexture(texture, data, format, invertY, compression);
  6279. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6280. // Filters
  6281. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6282. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6284. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6285. texture.samplingMode = samplingMode;
  6286. this._loadedTexturesCache.push(texture);
  6287. return texture;
  6288. };
  6289. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6290. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6291. var texture = this._gl.createTexture();
  6292. texture._baseWidth = width;
  6293. texture._baseHeight = height;
  6294. if (forceExponantOfTwo) {
  6295. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6296. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6297. }
  6298. this.resetTextureCache();
  6299. texture._width = width;
  6300. texture._height = height;
  6301. texture.isReady = false;
  6302. texture.generateMipMaps = generateMipMaps;
  6303. texture.references = 1;
  6304. texture.samplingMode = samplingMode;
  6305. this.updateTextureSamplingMode(samplingMode, texture);
  6306. this._loadedTexturesCache.push(texture);
  6307. return texture;
  6308. };
  6309. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6310. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6311. if (texture.isCube) {
  6312. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6313. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6314. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6315. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6316. }
  6317. else {
  6318. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6319. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6322. }
  6323. };
  6324. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6325. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6326. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6328. if (texture.generateMipMaps) {
  6329. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6330. }
  6331. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6332. this.resetTextureCache();
  6333. texture.isReady = true;
  6334. };
  6335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6336. if (texture._isDisabled) {
  6337. return;
  6338. }
  6339. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6341. try {
  6342. // Testing video texture support
  6343. if (this._videoTextureSupported === undefined) {
  6344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6345. if (this._gl.getError() !== 0) {
  6346. this._videoTextureSupported = false;
  6347. }
  6348. else {
  6349. this._videoTextureSupported = true;
  6350. }
  6351. }
  6352. // Copy video through the current working canvas if video texture is not supported
  6353. if (!this._videoTextureSupported) {
  6354. if (!texture._workingCanvas) {
  6355. texture._workingCanvas = document.createElement("canvas");
  6356. texture._workingContext = texture._workingCanvas.getContext("2d");
  6357. texture._workingCanvas.width = texture._width;
  6358. texture._workingCanvas.height = texture._height;
  6359. }
  6360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6362. }
  6363. else {
  6364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6365. }
  6366. if (texture.generateMipMaps) {
  6367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6368. }
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. this.resetTextureCache();
  6371. texture.isReady = true;
  6372. }
  6373. catch (ex) {
  6374. // Something unexpected
  6375. // Let's disable the texture
  6376. texture._isDisabled = true;
  6377. }
  6378. };
  6379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6380. // old version had a "generateMipMaps" arg instead of options.
  6381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6382. // in the same way, generateDepthBuffer is defaulted to true
  6383. var generateMipMaps = false;
  6384. var generateDepthBuffer = true;
  6385. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6386. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6387. if (options !== undefined) {
  6388. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6389. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6390. type = options.type === undefined ? type : options.type;
  6391. if (options.samplingMode !== undefined) {
  6392. samplingMode = options.samplingMode;
  6393. }
  6394. if (type === Engine.TEXTURETYPE_FLOAT) {
  6395. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6396. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6397. }
  6398. }
  6399. var gl = this._gl;
  6400. var texture = gl.createTexture();
  6401. gl.bindTexture(gl.TEXTURE_2D, texture);
  6402. var width = size.width || size;
  6403. var height = size.height || size;
  6404. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6405. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6406. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6407. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6408. }
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6413. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6414. var depthBuffer;
  6415. // Create the depth buffer
  6416. if (generateDepthBuffer) {
  6417. depthBuffer = gl.createRenderbuffer();
  6418. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6419. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6420. }
  6421. // Create the framebuffer
  6422. var framebuffer = gl.createFramebuffer();
  6423. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6424. if (generateDepthBuffer) {
  6425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6426. }
  6427. if (generateMipMaps) {
  6428. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6429. }
  6430. // Unbind
  6431. gl.bindTexture(gl.TEXTURE_2D, null);
  6432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6433. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6434. texture._framebuffer = framebuffer;
  6435. if (generateDepthBuffer) {
  6436. texture._depthBuffer = depthBuffer;
  6437. }
  6438. texture._width = width;
  6439. texture._height = height;
  6440. texture.isReady = true;
  6441. texture.generateMipMaps = generateMipMaps;
  6442. texture.references = 1;
  6443. texture.samplingMode = samplingMode;
  6444. this.resetTextureCache();
  6445. this._loadedTexturesCache.push(texture);
  6446. return texture;
  6447. };
  6448. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6449. var gl = this._gl;
  6450. var texture = gl.createTexture();
  6451. var generateMipMaps = true;
  6452. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6453. if (options !== undefined) {
  6454. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6455. if (options.samplingMode !== undefined) {
  6456. samplingMode = options.samplingMode;
  6457. }
  6458. }
  6459. texture.isCube = true;
  6460. texture.references = 1;
  6461. texture.generateMipMaps = generateMipMaps;
  6462. texture.references = 1;
  6463. texture.samplingMode = samplingMode;
  6464. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6465. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6466. for (var face = 0; face < 6; face++) {
  6467. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6468. }
  6469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6473. // Create the depth buffer
  6474. var depthBuffer = gl.createRenderbuffer();
  6475. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6476. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6477. // Create the framebuffer
  6478. var framebuffer = gl.createFramebuffer();
  6479. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6480. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6481. // mipmaps
  6482. if (texture.generateMipMaps) {
  6483. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6484. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6485. }
  6486. // Unbind
  6487. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6489. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6490. texture._framebuffer = framebuffer;
  6491. texture._depthBuffer = depthBuffer;
  6492. this.resetTextureCache();
  6493. texture._width = size;
  6494. texture._height = size;
  6495. texture.isReady = true;
  6496. return texture;
  6497. };
  6498. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6499. var _this = this;
  6500. var gl = this._gl;
  6501. var texture = gl.createTexture();
  6502. texture.isCube = true;
  6503. texture.url = rootUrl;
  6504. texture.references = 1;
  6505. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6506. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6507. if (isDDS) {
  6508. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6509. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6510. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6511. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6512. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6513. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6514. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6515. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6516. }
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6522. _this.resetTextureCache();
  6523. texture._width = info.width;
  6524. texture._height = info.height;
  6525. texture.isReady = true;
  6526. }, null, null, true);
  6527. }
  6528. else {
  6529. cascadeLoad(rootUrl, scene, function (imgs) {
  6530. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6531. var height = width;
  6532. _this._prepareWorkingCanvas();
  6533. _this._workingCanvas.width = width;
  6534. _this._workingCanvas.height = height;
  6535. var faces = [
  6536. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6537. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6538. ];
  6539. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6540. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6541. for (var index = 0; index < faces.length; index++) {
  6542. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6543. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6544. }
  6545. if (!noMipmap) {
  6546. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6547. }
  6548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6552. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6553. _this.resetTextureCache();
  6554. texture._width = width;
  6555. texture._height = height;
  6556. texture.isReady = true;
  6557. }, extensions);
  6558. }
  6559. return texture;
  6560. };
  6561. Engine.prototype._releaseTexture = function (texture) {
  6562. var gl = this._gl;
  6563. if (texture._framebuffer) {
  6564. gl.deleteFramebuffer(texture._framebuffer);
  6565. }
  6566. if (texture._depthBuffer) {
  6567. gl.deleteRenderbuffer(texture._depthBuffer);
  6568. }
  6569. gl.deleteTexture(texture);
  6570. // Unbind channels
  6571. this.unbindAllTextures();
  6572. var index = this._loadedTexturesCache.indexOf(texture);
  6573. if (index !== -1) {
  6574. this._loadedTexturesCache.splice(index, 1);
  6575. }
  6576. };
  6577. Engine.prototype.bindSamplers = function (effect) {
  6578. this._gl.useProgram(effect.getProgram());
  6579. var samplers = effect.getSamplers();
  6580. for (var index = 0; index < samplers.length; index++) {
  6581. var uniform = effect.getUniform(samplers[index]);
  6582. this._gl.uniform1i(uniform, index);
  6583. }
  6584. this._currentEffect = null;
  6585. };
  6586. Engine.prototype._bindTexture = function (channel, texture) {
  6587. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6588. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6589. this._activeTexturesCache[channel] = null;
  6590. };
  6591. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6592. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6593. };
  6594. Engine.prototype.unbindAllTextures = function () {
  6595. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6596. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6598. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6599. this._activeTexturesCache[channel] = null;
  6600. }
  6601. };
  6602. Engine.prototype.setTexture = function (channel, texture) {
  6603. if (channel < 0) {
  6604. return;
  6605. }
  6606. // Not ready?
  6607. if (!texture || !texture.isReady()) {
  6608. if (this._activeTexturesCache[channel] != null) {
  6609. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6610. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6611. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6612. this._activeTexturesCache[channel] = null;
  6613. }
  6614. return;
  6615. }
  6616. // Video
  6617. var alreadyActivated = false;
  6618. if (texture instanceof BABYLON.VideoTexture) {
  6619. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6620. alreadyActivated = true;
  6621. texture.update();
  6622. }
  6623. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6624. texture.delayLoad();
  6625. return;
  6626. }
  6627. if (this._activeTexturesCache[channel] === texture) {
  6628. return;
  6629. }
  6630. this._activeTexturesCache[channel] = texture;
  6631. var internalTexture = texture.getInternalTexture();
  6632. if (!alreadyActivated) {
  6633. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6634. }
  6635. if (internalTexture.isCube) {
  6636. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6637. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6638. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6639. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6640. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6641. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6642. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6643. }
  6644. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6645. }
  6646. else {
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6648. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6649. internalTexture._cachedWrapU = texture.wrapU;
  6650. switch (texture.wrapU) {
  6651. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6653. break;
  6654. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6655. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6656. break;
  6657. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6658. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6659. break;
  6660. }
  6661. }
  6662. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6663. internalTexture._cachedWrapV = texture.wrapV;
  6664. switch (texture.wrapV) {
  6665. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6666. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6667. break;
  6668. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6670. break;
  6671. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6673. break;
  6674. }
  6675. }
  6676. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6677. }
  6678. };
  6679. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6681. var value = texture.anisotropicFilteringLevel;
  6682. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6683. value = 1;
  6684. }
  6685. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6686. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6687. texture._cachedAnisotropicFilteringLevel = value;
  6688. }
  6689. };
  6690. Engine.prototype.readPixels = function (x, y, width, height) {
  6691. var data = new Uint8Array(height * width * 4);
  6692. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6693. return data;
  6694. };
  6695. Engine.prototype.releaseInternalTexture = function (texture) {
  6696. if (!texture) {
  6697. return;
  6698. }
  6699. texture.references--;
  6700. // Final reference ?
  6701. if (texture.references === 0) {
  6702. var texturesCache = this.getLoadedTexturesCache();
  6703. var index = texturesCache.indexOf(texture);
  6704. if (index > -1) {
  6705. texturesCache.splice(index, 1);
  6706. }
  6707. this._releaseTexture(texture);
  6708. }
  6709. };
  6710. // Dispose
  6711. Engine.prototype.dispose = function () {
  6712. this.hideLoadingUI();
  6713. this.stopRenderLoop();
  6714. // Release scenes
  6715. while (this.scenes.length) {
  6716. this.scenes[0].dispose();
  6717. }
  6718. // Release audio engine
  6719. Engine.audioEngine.dispose();
  6720. // Release effects
  6721. for (var name in this._compiledEffects) {
  6722. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6723. }
  6724. // Unbind
  6725. for (var i in this._vertexAttribArrays) {
  6726. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6727. continue;
  6728. }
  6729. this._gl.disableVertexAttribArray(i);
  6730. }
  6731. this._gl = null;
  6732. // Events
  6733. window.removeEventListener("blur", this._onBlur);
  6734. window.removeEventListener("focus", this._onFocus);
  6735. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6736. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6737. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6738. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6739. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6740. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6741. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6742. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6743. };
  6744. // Loading screen
  6745. Engine.prototype.displayLoadingUI = function () {
  6746. this._loadingScreen.displayLoadingUI();
  6747. };
  6748. Engine.prototype.hideLoadingUI = function () {
  6749. this._loadingScreen.hideLoadingUI();
  6750. };
  6751. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6752. get: function () {
  6753. return this._loadingScreen;
  6754. },
  6755. set: function (loadingScreen) {
  6756. this._loadingScreen = loadingScreen;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6762. set: function (text) {
  6763. this._loadingScreen.loadingUIText = text;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6769. set: function (color) {
  6770. this._loadingScreen.loadingUIBackgroundColor = color;
  6771. },
  6772. enumerable: true,
  6773. configurable: true
  6774. });
  6775. // FPS
  6776. Engine.prototype.getFps = function () {
  6777. return this.fps;
  6778. };
  6779. Engine.prototype.getDeltaTime = function () {
  6780. return this.deltaTime;
  6781. };
  6782. Engine.prototype._measureFps = function () {
  6783. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6784. var length = this.previousFramesDuration.length;
  6785. if (length >= 2) {
  6786. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6787. }
  6788. if (length >= this.fpsRange) {
  6789. if (length > this.fpsRange) {
  6790. this.previousFramesDuration.splice(0, 1);
  6791. length = this.previousFramesDuration.length;
  6792. }
  6793. var sum = 0;
  6794. for (var id = 0; id < length - 1; id++) {
  6795. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6796. }
  6797. this.fps = 1000.0 / (sum / (length - 1));
  6798. }
  6799. };
  6800. // Statics
  6801. Engine.isSupported = function () {
  6802. try {
  6803. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6804. if (navigator.isCocoonJS) {
  6805. return true;
  6806. }
  6807. var tempcanvas = document.createElement("canvas");
  6808. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6809. return gl != null && !!window.WebGLRenderingContext;
  6810. }
  6811. catch (e) {
  6812. return false;
  6813. }
  6814. };
  6815. // Const statics
  6816. Engine._ALPHA_DISABLE = 0;
  6817. Engine._ALPHA_ADD = 1;
  6818. Engine._ALPHA_COMBINE = 2;
  6819. Engine._ALPHA_SUBTRACT = 3;
  6820. Engine._ALPHA_MULTIPLY = 4;
  6821. Engine._ALPHA_MAXIMIZED = 5;
  6822. Engine._ALPHA_ONEONE = 6;
  6823. Engine._DELAYLOADSTATE_NONE = 0;
  6824. Engine._DELAYLOADSTATE_LOADED = 1;
  6825. Engine._DELAYLOADSTATE_LOADING = 2;
  6826. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6827. Engine._TEXTUREFORMAT_ALPHA = 0;
  6828. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6829. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6830. Engine._TEXTUREFORMAT_RGB = 4;
  6831. Engine._TEXTUREFORMAT_RGBA = 5;
  6832. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6833. Engine._TEXTURETYPE_FLOAT = 1;
  6834. // Updatable statics so stick with vars here
  6835. Engine.Epsilon = 0.001;
  6836. Engine.CollisionsEpsilon = 0.001;
  6837. Engine.CodeRepository = "src/";
  6838. Engine.ShadersRepository = "src/Shaders/";
  6839. return Engine;
  6840. })();
  6841. BABYLON.Engine = Engine;
  6842. })(BABYLON || (BABYLON = {}));
  6843. var BABYLON;
  6844. (function (BABYLON) {
  6845. /**
  6846. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6847. */
  6848. var Node = (function () {
  6849. /**
  6850. * @constructor
  6851. * @param {string} name - the name and id to be given to this node
  6852. * @param {BABYLON.Scene} the scene this node will be added to
  6853. */
  6854. function Node(name, scene) {
  6855. this.state = "";
  6856. this.animations = new Array();
  6857. this._childrenFlag = -1;
  6858. this._isEnabled = true;
  6859. this._isReady = true;
  6860. this._currentRenderId = -1;
  6861. this._parentRenderId = -1;
  6862. this.name = name;
  6863. this.id = name;
  6864. this._scene = scene;
  6865. this._initCache();
  6866. }
  6867. Node.prototype.getScene = function () {
  6868. return this._scene;
  6869. };
  6870. Node.prototype.getEngine = function () {
  6871. return this._scene.getEngine();
  6872. };
  6873. // override it in derived class
  6874. Node.prototype.getWorldMatrix = function () {
  6875. return BABYLON.Matrix.Identity();
  6876. };
  6877. // override it in derived class if you add new variables to the cache
  6878. // and call the parent class method
  6879. Node.prototype._initCache = function () {
  6880. this._cache = {};
  6881. this._cache.parent = undefined;
  6882. };
  6883. Node.prototype.updateCache = function (force) {
  6884. if (!force && this.isSynchronized())
  6885. return;
  6886. this._cache.parent = this.parent;
  6887. this._updateCache();
  6888. };
  6889. // override it in derived class if you add new variables to the cache
  6890. // and call the parent class method if !ignoreParentClass
  6891. Node.prototype._updateCache = function (ignoreParentClass) {
  6892. };
  6893. // override it in derived class if you add new variables to the cache
  6894. Node.prototype._isSynchronized = function () {
  6895. return true;
  6896. };
  6897. Node.prototype._markSyncedWithParent = function () {
  6898. this._parentRenderId = this.parent._currentRenderId;
  6899. };
  6900. Node.prototype.isSynchronizedWithParent = function () {
  6901. if (!this.parent) {
  6902. return true;
  6903. }
  6904. if (this._parentRenderId !== this.parent._currentRenderId) {
  6905. return false;
  6906. }
  6907. return this.parent.isSynchronized();
  6908. };
  6909. Node.prototype.isSynchronized = function (updateCache) {
  6910. var check = this.hasNewParent();
  6911. check = check || !this.isSynchronizedWithParent();
  6912. check = check || !this._isSynchronized();
  6913. if (updateCache)
  6914. this.updateCache(true);
  6915. return !check;
  6916. };
  6917. Node.prototype.hasNewParent = function (update) {
  6918. if (this._cache.parent === this.parent)
  6919. return false;
  6920. if (update)
  6921. this._cache.parent = this.parent;
  6922. return true;
  6923. };
  6924. /**
  6925. * Is this node ready to be used/rendered
  6926. * @return {boolean} is it ready
  6927. */
  6928. Node.prototype.isReady = function () {
  6929. return this._isReady;
  6930. };
  6931. /**
  6932. * Is this node enabled.
  6933. * If the node has a parent and is enabled, the parent will be inspected as well.
  6934. * @return {boolean} whether this node (and its parent) is enabled.
  6935. * @see setEnabled
  6936. */
  6937. Node.prototype.isEnabled = function () {
  6938. if (!this._isEnabled) {
  6939. return false;
  6940. }
  6941. if (this.parent) {
  6942. return this.parent.isEnabled();
  6943. }
  6944. return true;
  6945. };
  6946. /**
  6947. * Set the enabled state of this node.
  6948. * @param {boolean} value - the new enabled state
  6949. * @see isEnabled
  6950. */
  6951. Node.prototype.setEnabled = function (value) {
  6952. this._isEnabled = value;
  6953. };
  6954. /**
  6955. * Is this node a descendant of the given node.
  6956. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6957. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6958. * @see parent
  6959. */
  6960. Node.prototype.isDescendantOf = function (ancestor) {
  6961. if (this.parent) {
  6962. if (this.parent === ancestor) {
  6963. return true;
  6964. }
  6965. return this.parent.isDescendantOf(ancestor);
  6966. }
  6967. return false;
  6968. };
  6969. Node.prototype._getDescendants = function (list, results) {
  6970. for (var index = 0; index < list.length; index++) {
  6971. var item = list[index];
  6972. if (item.isDescendantOf(this)) {
  6973. results.push(item);
  6974. }
  6975. }
  6976. };
  6977. /**
  6978. * Will return all nodes that have this node as parent.
  6979. * @return {BABYLON.Node[]} all children nodes of all types.
  6980. */
  6981. Node.prototype.getDescendants = function () {
  6982. var results = [];
  6983. this._getDescendants(this._scene.meshes, results);
  6984. this._getDescendants(this._scene.lights, results);
  6985. this._getDescendants(this._scene.cameras, results);
  6986. return results;
  6987. };
  6988. Node.prototype._setReady = function (state) {
  6989. if (state === this._isReady) {
  6990. return;
  6991. }
  6992. if (!state) {
  6993. this._isReady = false;
  6994. return;
  6995. }
  6996. this._isReady = true;
  6997. if (this.onReady) {
  6998. this.onReady(this);
  6999. }
  7000. };
  7001. Node.prototype.getAnimationByName = function (name) {
  7002. for (var i = 0; i < this.animations.length; i++) {
  7003. var animation = this.animations[i];
  7004. if (animation.name === name) {
  7005. return animation;
  7006. }
  7007. }
  7008. return null;
  7009. };
  7010. return Node;
  7011. })();
  7012. BABYLON.Node = Node;
  7013. })(BABYLON || (BABYLON = {}));
  7014. var BABYLON;
  7015. (function (BABYLON) {
  7016. var FilesInput = (function () {
  7017. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7018. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7019. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7020. this._engine = p_engine;
  7021. this._canvas = p_canvas;
  7022. this._currentScene = p_scene;
  7023. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7024. this._progressCallback = p_progressCallback;
  7025. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7026. this._textureLoadingCallback = p_textureLoadingCallback;
  7027. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7028. }
  7029. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7030. var _this = this;
  7031. if (p_elementToMonitor) {
  7032. this._elementToMonitor = p_elementToMonitor;
  7033. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7034. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7035. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7036. }
  7037. };
  7038. FilesInput.prototype.renderFunction = function () {
  7039. if (this._additionnalRenderLoopLogicCallback) {
  7040. this._additionnalRenderLoopLogicCallback();
  7041. }
  7042. if (this._currentScene) {
  7043. if (this._textureLoadingCallback) {
  7044. var remaining = this._currentScene.getWaitingItemsCount();
  7045. if (remaining > 0) {
  7046. this._textureLoadingCallback(remaining);
  7047. }
  7048. }
  7049. this._currentScene.render();
  7050. }
  7051. };
  7052. FilesInput.prototype.drag = function (e) {
  7053. e.stopPropagation();
  7054. e.preventDefault();
  7055. };
  7056. FilesInput.prototype.drop = function (eventDrop) {
  7057. eventDrop.stopPropagation();
  7058. eventDrop.preventDefault();
  7059. this.loadFiles(eventDrop);
  7060. };
  7061. FilesInput.prototype.loadFiles = function (event) {
  7062. if (this._startingProcessingFilesCallback)
  7063. this._startingProcessingFilesCallback();
  7064. // Handling data transfer via drag'n'drop
  7065. if (event && event.dataTransfer && event.dataTransfer.files) {
  7066. this._filesToLoad = event.dataTransfer.files;
  7067. }
  7068. // Handling files from input files
  7069. if (event && event.target && event.target.files) {
  7070. this._filesToLoad = event.target.files;
  7071. }
  7072. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7073. for (var i = 0; i < this._filesToLoad.length; i++) {
  7074. switch (this._filesToLoad[i].type) {
  7075. case "image/jpeg":
  7076. case "image/png":
  7077. case "image/bmp":
  7078. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7079. break;
  7080. case "image/targa":
  7081. case "image/vnd.ms-dds":
  7082. case "audio/wav":
  7083. case "audio/x-wav":
  7084. case "audio/mp3":
  7085. case "audio/mpeg":
  7086. case "audio/mpeg3":
  7087. case "audio/x-mpeg-3":
  7088. case "audio/ogg":
  7089. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7090. break;
  7091. default:
  7092. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7093. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7094. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7095. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7096. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7097. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7098. this._sceneFileToLoad = this._filesToLoad[i];
  7099. }
  7100. break;
  7101. }
  7102. }
  7103. this.reload();
  7104. }
  7105. };
  7106. FilesInput.prototype.reload = function () {
  7107. var _this = this;
  7108. var that = this;
  7109. // If a ".babylon" file has been provided
  7110. if (this._sceneFileToLoad) {
  7111. if (this._currentScene) {
  7112. if (BABYLON.Tools.errorsCount > 0) {
  7113. BABYLON.Tools.ClearLogCache();
  7114. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7115. }
  7116. this._engine.stopRenderLoop();
  7117. this._currentScene.dispose();
  7118. }
  7119. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7120. that._currentScene = newScene;
  7121. // Wait for textures and shaders to be ready
  7122. that._currentScene.executeWhenReady(function () {
  7123. // Attach camera to canvas inputs
  7124. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7125. that._currentScene.createDefaultCameraOrLight();
  7126. }
  7127. that._currentScene.activeCamera.attachControl(that._canvas);
  7128. if (that._sceneLoadedCallback) {
  7129. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7130. }
  7131. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7132. });
  7133. }, function (progress) {
  7134. if (_this._progressCallback) {
  7135. _this._progressCallback(progress);
  7136. }
  7137. });
  7138. }
  7139. else {
  7140. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7141. }
  7142. };
  7143. FilesInput.FilesTextures = new Array();
  7144. FilesInput.FilesToLoad = new Array();
  7145. return FilesInput;
  7146. })();
  7147. BABYLON.FilesInput = FilesInput;
  7148. })(BABYLON || (BABYLON = {}));
  7149. var BABYLON;
  7150. (function (BABYLON) {
  7151. var IntersectionInfo = (function () {
  7152. function IntersectionInfo(bu, bv, distance) {
  7153. this.bu = bu;
  7154. this.bv = bv;
  7155. this.distance = distance;
  7156. this.faceId = 0;
  7157. this.subMeshId = 0;
  7158. }
  7159. return IntersectionInfo;
  7160. })();
  7161. BABYLON.IntersectionInfo = IntersectionInfo;
  7162. var PickingInfo = (function () {
  7163. function PickingInfo() {
  7164. this.hit = false;
  7165. this.distance = 0;
  7166. this.pickedPoint = null;
  7167. this.pickedMesh = null;
  7168. this.bu = 0;
  7169. this.bv = 0;
  7170. this.faceId = -1;
  7171. this.subMeshId = 0;
  7172. this.pickedSprite = null;
  7173. }
  7174. // Methods
  7175. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7176. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7177. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7178. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7179. return null;
  7180. }
  7181. var indices = this.pickedMesh.getIndices();
  7182. var result;
  7183. if (useVerticesNormals) {
  7184. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7185. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7186. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7187. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7188. normal0 = normal0.scale(this.bu);
  7189. normal1 = normal1.scale(this.bv);
  7190. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7191. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7192. }
  7193. else {
  7194. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7195. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7196. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7197. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7198. var p1p2 = vertex1.subtract(vertex2);
  7199. var p3p2 = vertex3.subtract(vertex2);
  7200. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7201. }
  7202. if (useWorldCoordinates) {
  7203. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7204. }
  7205. return BABYLON.Vector3.Normalize(result);
  7206. };
  7207. PickingInfo.prototype.getTextureCoordinates = function () {
  7208. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7209. return null;
  7210. }
  7211. var indices = this.pickedMesh.getIndices();
  7212. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7213. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7214. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7215. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7216. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7217. uv1 = uv1.scale(this.bu);
  7218. uv2 = uv2.scale(this.bv);
  7219. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7220. };
  7221. return PickingInfo;
  7222. })();
  7223. BABYLON.PickingInfo = PickingInfo;
  7224. })(BABYLON || (BABYLON = {}));
  7225. var BABYLON;
  7226. (function (BABYLON) {
  7227. var BoundingSphere = (function () {
  7228. function BoundingSphere(minimum, maximum) {
  7229. this.minimum = minimum;
  7230. this.maximum = maximum;
  7231. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7232. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7233. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7234. this.radius = distance * 0.5;
  7235. this.centerWorld = BABYLON.Vector3.Zero();
  7236. this._update(BABYLON.Matrix.Identity());
  7237. }
  7238. // Methods
  7239. BoundingSphere.prototype._update = function (world) {
  7240. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7241. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7242. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7243. };
  7244. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7245. for (var i = 0; i < 6; i++) {
  7246. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7247. return false;
  7248. }
  7249. return true;
  7250. };
  7251. BoundingSphere.prototype.intersectsPoint = function (point) {
  7252. var x = this.centerWorld.x - point.x;
  7253. var y = this.centerWorld.y - point.y;
  7254. var z = this.centerWorld.z - point.z;
  7255. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7256. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7257. return false;
  7258. return true;
  7259. };
  7260. // Statics
  7261. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7262. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7263. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7264. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7266. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7267. return false;
  7268. return true;
  7269. };
  7270. return BoundingSphere;
  7271. })();
  7272. BABYLON.BoundingSphere = BoundingSphere;
  7273. })(BABYLON || (BABYLON = {}));
  7274. var BABYLON;
  7275. (function (BABYLON) {
  7276. var BoundingBox = (function () {
  7277. function BoundingBox(minimum, maximum) {
  7278. this.minimum = minimum;
  7279. this.maximum = maximum;
  7280. this.vectors = new Array();
  7281. this.vectorsWorld = new Array();
  7282. // Bounding vectors
  7283. this.vectors.push(this.minimum.clone());
  7284. this.vectors.push(this.maximum.clone());
  7285. this.vectors.push(this.minimum.clone());
  7286. this.vectors[2].x = this.maximum.x;
  7287. this.vectors.push(this.minimum.clone());
  7288. this.vectors[3].y = this.maximum.y;
  7289. this.vectors.push(this.minimum.clone());
  7290. this.vectors[4].z = this.maximum.z;
  7291. this.vectors.push(this.maximum.clone());
  7292. this.vectors[5].z = this.minimum.z;
  7293. this.vectors.push(this.maximum.clone());
  7294. this.vectors[6].x = this.minimum.x;
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors[7].y = this.minimum.y;
  7297. // OBB
  7298. this.center = this.maximum.add(this.minimum).scale(0.5);
  7299. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7300. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7301. // World
  7302. for (var index = 0; index < this.vectors.length; index++) {
  7303. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7304. }
  7305. this.minimumWorld = BABYLON.Vector3.Zero();
  7306. this.maximumWorld = BABYLON.Vector3.Zero();
  7307. this._update(BABYLON.Matrix.Identity());
  7308. }
  7309. // Methods
  7310. BoundingBox.prototype.getWorldMatrix = function () {
  7311. return this._worldMatrix;
  7312. };
  7313. BoundingBox.prototype._update = function (world) {
  7314. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7315. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7316. for (var index = 0; index < this.vectors.length; index++) {
  7317. var v = this.vectorsWorld[index];
  7318. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7319. if (v.x < this.minimumWorld.x)
  7320. this.minimumWorld.x = v.x;
  7321. if (v.y < this.minimumWorld.y)
  7322. this.minimumWorld.y = v.y;
  7323. if (v.z < this.minimumWorld.z)
  7324. this.minimumWorld.z = v.z;
  7325. if (v.x > this.maximumWorld.x)
  7326. this.maximumWorld.x = v.x;
  7327. if (v.y > this.maximumWorld.y)
  7328. this.maximumWorld.y = v.y;
  7329. if (v.z > this.maximumWorld.z)
  7330. this.maximumWorld.z = v.z;
  7331. }
  7332. // OBB
  7333. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7334. this.center.scaleInPlace(0.5);
  7335. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7336. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7337. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7338. this._worldMatrix = world;
  7339. };
  7340. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7341. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7342. };
  7343. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7344. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7345. };
  7346. BoundingBox.prototype.intersectsPoint = function (point) {
  7347. var delta = -BABYLON.Engine.Epsilon;
  7348. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7349. return false;
  7350. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7351. return false;
  7352. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7353. return false;
  7354. return true;
  7355. };
  7356. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7357. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7358. };
  7359. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7360. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7361. return false;
  7362. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7363. return false;
  7364. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7365. return false;
  7366. return true;
  7367. };
  7368. // Statics
  7369. BoundingBox.Intersects = function (box0, box1) {
  7370. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7371. return false;
  7372. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7373. return false;
  7374. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7375. return false;
  7376. return true;
  7377. };
  7378. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7379. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7380. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7381. return (num <= (sphereRadius * sphereRadius));
  7382. };
  7383. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7384. for (var p = 0; p < 6; p++) {
  7385. for (var i = 0; i < 8; i++) {
  7386. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7387. return false;
  7388. }
  7389. }
  7390. }
  7391. return true;
  7392. };
  7393. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7394. for (var p = 0; p < 6; p++) {
  7395. var inCount = 8;
  7396. for (var i = 0; i < 8; i++) {
  7397. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7398. --inCount;
  7399. }
  7400. else {
  7401. break;
  7402. }
  7403. }
  7404. if (inCount === 0)
  7405. return false;
  7406. }
  7407. return true;
  7408. };
  7409. return BoundingBox;
  7410. })();
  7411. BABYLON.BoundingBox = BoundingBox;
  7412. })(BABYLON || (BABYLON = {}));
  7413. var BABYLON;
  7414. (function (BABYLON) {
  7415. var computeBoxExtents = function (axis, box) {
  7416. var p = BABYLON.Vector3.Dot(box.center, axis);
  7417. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7418. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7419. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7420. var r = r0 + r1 + r2;
  7421. return {
  7422. min: p - r,
  7423. max: p + r
  7424. };
  7425. };
  7426. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7427. var axisOverlap = function (axis, box0, box1) {
  7428. var result0 = computeBoxExtents(axis, box0);
  7429. var result1 = computeBoxExtents(axis, box1);
  7430. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7431. };
  7432. var BoundingInfo = (function () {
  7433. function BoundingInfo(minimum, maximum) {
  7434. this.minimum = minimum;
  7435. this.maximum = maximum;
  7436. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7437. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7438. }
  7439. // Methods
  7440. BoundingInfo.prototype._update = function (world) {
  7441. this.boundingBox._update(world);
  7442. this.boundingSphere._update(world);
  7443. };
  7444. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7445. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7446. return false;
  7447. return this.boundingBox.isInFrustum(frustumPlanes);
  7448. };
  7449. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7450. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7451. };
  7452. BoundingInfo.prototype._checkCollision = function (collider) {
  7453. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7454. };
  7455. BoundingInfo.prototype.intersectsPoint = function (point) {
  7456. if (!this.boundingSphere.centerWorld) {
  7457. return false;
  7458. }
  7459. if (!this.boundingSphere.intersectsPoint(point)) {
  7460. return false;
  7461. }
  7462. if (!this.boundingBox.intersectsPoint(point)) {
  7463. return false;
  7464. }
  7465. return true;
  7466. };
  7467. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7468. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7472. return false;
  7473. }
  7474. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7475. return false;
  7476. }
  7477. if (!precise) {
  7478. return true;
  7479. }
  7480. var box0 = this.boundingBox;
  7481. var box1 = boundingInfo.boundingBox;
  7482. if (!axisOverlap(box0.directions[0], box0, box1))
  7483. return false;
  7484. if (!axisOverlap(box0.directions[1], box0, box1))
  7485. return false;
  7486. if (!axisOverlap(box0.directions[2], box0, box1))
  7487. return false;
  7488. if (!axisOverlap(box1.directions[0], box0, box1))
  7489. return false;
  7490. if (!axisOverlap(box1.directions[1], box0, box1))
  7491. return false;
  7492. if (!axisOverlap(box1.directions[2], box0, box1))
  7493. return false;
  7494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7495. return false;
  7496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7497. return false;
  7498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7499. return false;
  7500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7501. return false;
  7502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7503. return false;
  7504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7511. return false;
  7512. return true;
  7513. };
  7514. return BoundingInfo;
  7515. })();
  7516. BABYLON.BoundingInfo = BoundingInfo;
  7517. })(BABYLON || (BABYLON = {}));
  7518. var BABYLON;
  7519. (function (BABYLON) {
  7520. var AbstractMesh = (function (_super) {
  7521. __extends(AbstractMesh, _super);
  7522. function AbstractMesh(name, scene) {
  7523. var _this = this;
  7524. _super.call(this, name, scene);
  7525. // Properties
  7526. this.definedFacingForward = true; // orientation for POV movement & rotation
  7527. this.position = new BABYLON.Vector3(0, 0, 0);
  7528. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7529. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7530. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7531. this.visibility = 1.0;
  7532. this.alphaIndex = Number.MAX_VALUE;
  7533. this.infiniteDistance = false;
  7534. this.isVisible = true;
  7535. this.isPickable = true;
  7536. this.showBoundingBox = false;
  7537. this.showSubMeshesBoundingBox = false;
  7538. this.onDispose = null;
  7539. this.isBlocker = false;
  7540. this.renderingGroupId = 0;
  7541. this.receiveShadows = false;
  7542. this.renderOutline = false;
  7543. this.outlineColor = BABYLON.Color3.Red();
  7544. this.outlineWidth = 0.02;
  7545. this.renderOverlay = false;
  7546. this.overlayColor = BABYLON.Color3.Red();
  7547. this.overlayAlpha = 0.5;
  7548. this.hasVertexAlpha = false;
  7549. this.useVertexColors = true;
  7550. this.applyFog = true;
  7551. this.computeBonesUsingShaders = true;
  7552. this.scalingDeterminant = 1;
  7553. this.numBoneInfluencers = 4;
  7554. this.useOctreeForRenderingSelection = true;
  7555. this.useOctreeForPicking = true;
  7556. this.useOctreeForCollisions = true;
  7557. this.layerMask = 0x0FFFFFFF;
  7558. this.alwaysSelectAsActiveMesh = false;
  7559. // Physics
  7560. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7561. // Collisions
  7562. this._checkCollisions = false;
  7563. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7564. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7565. this._collider = new BABYLON.Collider();
  7566. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7567. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7568. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7569. // Edges
  7570. this.edgesWidth = 1;
  7571. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7572. // Cache
  7573. this._localScaling = BABYLON.Matrix.Zero();
  7574. this._localRotation = BABYLON.Matrix.Zero();
  7575. this._localTranslation = BABYLON.Matrix.Zero();
  7576. this._localBillboard = BABYLON.Matrix.Zero();
  7577. this._localPivotScaling = BABYLON.Matrix.Zero();
  7578. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7579. this._localWorld = BABYLON.Matrix.Zero();
  7580. this._worldMatrix = BABYLON.Matrix.Zero();
  7581. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7582. this._absolutePosition = BABYLON.Vector3.Zero();
  7583. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7584. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7585. this._isDirty = false;
  7586. this._pivotMatrix = BABYLON.Matrix.Identity();
  7587. this._isDisposed = false;
  7588. this._renderId = 0;
  7589. this._intersectionsInProgress = new Array();
  7590. this._onAfterWorldMatrixUpdate = new Array();
  7591. this._isWorldMatrixFrozen = false;
  7592. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7593. if (collidedMesh === void 0) { collidedMesh = null; }
  7594. //TODO move this to the collision coordinator!
  7595. if (_this.getScene().workerCollisions)
  7596. newPosition.multiplyInPlace(_this._collider.radius);
  7597. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7598. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7599. _this.position.addInPlace(_this._diffPositionForCollisions);
  7600. }
  7601. if (_this.onCollide && collidedMesh) {
  7602. _this.onCollide(collidedMesh);
  7603. }
  7604. if (_this.onCollisionPositionChange) {
  7605. _this.onCollisionPositionChange(_this.position);
  7606. }
  7607. };
  7608. scene.addMesh(this);
  7609. }
  7610. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7611. get: function () {
  7612. return AbstractMesh._BILLBOARDMODE_NONE;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7618. get: function () {
  7619. return AbstractMesh._BILLBOARDMODE_X;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7625. get: function () {
  7626. return AbstractMesh._BILLBOARDMODE_Y;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7632. get: function () {
  7633. return AbstractMesh._BILLBOARDMODE_Z;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7639. get: function () {
  7640. return AbstractMesh._BILLBOARDMODE_ALL;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. // Methods
  7646. AbstractMesh.prototype.disableEdgesRendering = function () {
  7647. if (this._edgesRenderer !== undefined) {
  7648. this._edgesRenderer.dispose();
  7649. this._edgesRenderer = undefined;
  7650. }
  7651. };
  7652. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7653. if (epsilon === void 0) { epsilon = 0.95; }
  7654. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7655. this.disableEdgesRendering();
  7656. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7657. };
  7658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7659. get: function () {
  7660. return false;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. AbstractMesh.prototype.getLOD = function (camera) {
  7666. return this;
  7667. };
  7668. AbstractMesh.prototype.getTotalVertices = function () {
  7669. return 0;
  7670. };
  7671. AbstractMesh.prototype.getIndices = function () {
  7672. return null;
  7673. };
  7674. AbstractMesh.prototype.getVerticesData = function (kind) {
  7675. return null;
  7676. };
  7677. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7678. return false;
  7679. };
  7680. AbstractMesh.prototype.getBoundingInfo = function () {
  7681. if (this._masterMesh) {
  7682. return this._masterMesh.getBoundingInfo();
  7683. }
  7684. if (!this._boundingInfo) {
  7685. this._updateBoundingInfo();
  7686. }
  7687. return this._boundingInfo;
  7688. };
  7689. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7690. get: function () {
  7691. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. AbstractMesh.prototype._preActivate = function () {
  7697. };
  7698. AbstractMesh.prototype._activate = function (renderId) {
  7699. this._renderId = renderId;
  7700. };
  7701. AbstractMesh.prototype.getWorldMatrix = function () {
  7702. if (this._masterMesh) {
  7703. return this._masterMesh.getWorldMatrix();
  7704. }
  7705. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7706. this.computeWorldMatrix();
  7707. }
  7708. return this._worldMatrix;
  7709. };
  7710. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7711. get: function () {
  7712. return this._worldMatrix;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7718. get: function () {
  7719. return this._absolutePosition;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7725. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7726. this.computeWorldMatrix(true);
  7727. this._isWorldMatrixFrozen = true;
  7728. };
  7729. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7730. this._isWorldMatrixFrozen = false;
  7731. this.computeWorldMatrix(true);
  7732. };
  7733. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7734. get: function () {
  7735. return this._isWorldMatrixFrozen;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7741. axis.normalize();
  7742. if (!this.rotationQuaternion) {
  7743. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7744. this.rotation = BABYLON.Vector3.Zero();
  7745. }
  7746. var rotationQuaternion;
  7747. if (!space || space === BABYLON.Space.LOCAL) {
  7748. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7749. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7750. }
  7751. else {
  7752. if (this.parent) {
  7753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7754. invertParentWorldMatrix.invert();
  7755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7756. }
  7757. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7758. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7759. }
  7760. };
  7761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7762. var displacementVector = axis.scale(distance);
  7763. if (!space || space === BABYLON.Space.LOCAL) {
  7764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7765. this.setPositionWithLocalVector(tempV3);
  7766. }
  7767. else {
  7768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7769. }
  7770. };
  7771. AbstractMesh.prototype.getAbsolutePosition = function () {
  7772. this.computeWorldMatrix();
  7773. return this._absolutePosition;
  7774. };
  7775. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7776. if (!absolutePosition) {
  7777. return;
  7778. }
  7779. var absolutePositionX;
  7780. var absolutePositionY;
  7781. var absolutePositionZ;
  7782. if (absolutePosition.x === undefined) {
  7783. if (arguments.length < 3) {
  7784. return;
  7785. }
  7786. absolutePositionX = arguments[0];
  7787. absolutePositionY = arguments[1];
  7788. absolutePositionZ = arguments[2];
  7789. }
  7790. else {
  7791. absolutePositionX = absolutePosition.x;
  7792. absolutePositionY = absolutePosition.y;
  7793. absolutePositionZ = absolutePosition.z;
  7794. }
  7795. if (this.parent) {
  7796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7797. invertParentWorldMatrix.invert();
  7798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7800. }
  7801. else {
  7802. this.position.x = absolutePositionX;
  7803. this.position.y = absolutePositionY;
  7804. this.position.z = absolutePositionZ;
  7805. }
  7806. };
  7807. // ================================== Point of View Movement =================================
  7808. /**
  7809. * Perform relative position change from the point of view of behind the front of the mesh.
  7810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7811. * Supports definition of mesh facing forward or backward.
  7812. * @param {number} amountRight
  7813. * @param {number} amountUp
  7814. * @param {number} amountForward
  7815. */
  7816. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7817. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7818. };
  7819. /**
  7820. * Calculate relative position change from the point of view of behind the front of the mesh.
  7821. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7822. * Supports definition of mesh facing forward or backward.
  7823. * @param {number} amountRight
  7824. * @param {number} amountUp
  7825. * @param {number} amountForward
  7826. */
  7827. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7828. var rotMatrix = new BABYLON.Matrix();
  7829. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7830. rotQuaternion.toRotationMatrix(rotMatrix);
  7831. var translationDelta = BABYLON.Vector3.Zero();
  7832. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7834. return translationDelta;
  7835. };
  7836. // ================================== Point of View Rotation =================================
  7837. /**
  7838. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7839. * Supports definition of mesh facing forward or backward.
  7840. * @param {number} flipBack
  7841. * @param {number} twirlClockwise
  7842. * @param {number} tiltRight
  7843. */
  7844. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7845. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7846. };
  7847. /**
  7848. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7849. * Supports definition of mesh facing forward or backward.
  7850. * @param {number} flipBack
  7851. * @param {number} twirlClockwise
  7852. * @param {number} tiltRight
  7853. */
  7854. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7855. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7856. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7857. };
  7858. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7859. this._pivotMatrix = matrix;
  7860. this._cache.pivotMatrixUpdated = true;
  7861. };
  7862. AbstractMesh.prototype.getPivotMatrix = function () {
  7863. return this._pivotMatrix;
  7864. };
  7865. AbstractMesh.prototype._isSynchronized = function () {
  7866. if (this._isDirty) {
  7867. return false;
  7868. }
  7869. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7870. return false;
  7871. if (this._cache.pivotMatrixUpdated) {
  7872. return false;
  7873. }
  7874. if (this.infiniteDistance) {
  7875. return false;
  7876. }
  7877. if (!this._cache.position.equals(this.position))
  7878. return false;
  7879. if (this.rotationQuaternion) {
  7880. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7881. return false;
  7882. }
  7883. else {
  7884. if (!this._cache.rotation.equals(this.rotation))
  7885. return false;
  7886. }
  7887. if (!this._cache.scaling.equals(this.scaling))
  7888. return false;
  7889. return true;
  7890. };
  7891. AbstractMesh.prototype._initCache = function () {
  7892. _super.prototype._initCache.call(this);
  7893. this._cache.localMatrixUpdated = false;
  7894. this._cache.position = BABYLON.Vector3.Zero();
  7895. this._cache.scaling = BABYLON.Vector3.Zero();
  7896. this._cache.rotation = BABYLON.Vector3.Zero();
  7897. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7898. this._cache.billboardMode = -1;
  7899. };
  7900. AbstractMesh.prototype.markAsDirty = function (property) {
  7901. if (property === "rotation") {
  7902. this.rotationQuaternion = null;
  7903. }
  7904. this._currentRenderId = Number.MAX_VALUE;
  7905. this._isDirty = true;
  7906. };
  7907. AbstractMesh.prototype._updateBoundingInfo = function () {
  7908. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7909. this._boundingInfo._update(this.worldMatrixFromCache);
  7910. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7911. };
  7912. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7913. if (!this.subMeshes) {
  7914. return;
  7915. }
  7916. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7917. var subMesh = this.subMeshes[subIndex];
  7918. subMesh.updateBoundingInfo(matrix);
  7919. }
  7920. };
  7921. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7922. if (this._isWorldMatrixFrozen) {
  7923. return this._worldMatrix;
  7924. }
  7925. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7926. return this._worldMatrix;
  7927. }
  7928. this._cache.position.copyFrom(this.position);
  7929. this._cache.scaling.copyFrom(this.scaling);
  7930. this._cache.pivotMatrixUpdated = false;
  7931. this._cache.billboardMode = this.billboardMode;
  7932. this._currentRenderId = this.getScene().getRenderId();
  7933. this._isDirty = false;
  7934. // Scaling
  7935. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7936. // Rotation
  7937. if (this.rotationQuaternion) {
  7938. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7939. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7940. }
  7941. else {
  7942. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7943. this._cache.rotation.copyFrom(this.rotation);
  7944. }
  7945. // Translation
  7946. if (this.infiniteDistance && !this.parent) {
  7947. var camera = this.getScene().activeCamera;
  7948. if (camera) {
  7949. var cameraWorldMatrix = camera.getWorldMatrix();
  7950. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7951. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7952. }
  7953. }
  7954. else {
  7955. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7956. }
  7957. // Composing transformations
  7958. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7959. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7960. // Billboarding
  7961. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7962. var localPosition = this.position.clone();
  7963. var zero = this.getScene().activeCamera.globalPosition.clone();
  7964. if (this.parent && this.parent.position) {
  7965. localPosition.addInPlace(this.parent.position);
  7966. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7967. }
  7968. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7969. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7970. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7971. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7972. zero.y = localPosition.y + 0.001;
  7973. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7974. zero.z = localPosition.z + 0.001;
  7975. }
  7976. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7977. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7978. this._localBillboard.invert();
  7979. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7980. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7981. }
  7982. // Local world
  7983. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7984. // Parent
  7985. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7986. this._markSyncedWithParent();
  7987. if (this._meshToBoneReferal) {
  7988. if (!this._localMeshReferalTransform) {
  7989. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7990. }
  7991. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7992. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7993. }
  7994. else {
  7995. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7996. }
  7997. }
  7998. else {
  7999. this._worldMatrix.copyFrom(this._localWorld);
  8000. }
  8001. // Bounding info
  8002. this._updateBoundingInfo();
  8003. // Absolute position
  8004. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8005. // Callbacks
  8006. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8007. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8008. }
  8009. return this._worldMatrix;
  8010. };
  8011. /**
  8012. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8013. * @param func: callback function to add
  8014. */
  8015. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8016. this._onAfterWorldMatrixUpdate.push(func);
  8017. };
  8018. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8019. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8020. if (index > -1) {
  8021. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8022. }
  8023. };
  8024. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8025. this.computeWorldMatrix();
  8026. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8027. };
  8028. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8029. this.computeWorldMatrix();
  8030. var invLocalWorldMatrix = this._localWorld.clone();
  8031. invLocalWorldMatrix.invert();
  8032. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8033. };
  8034. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8035. this.computeWorldMatrix(true);
  8036. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8037. };
  8038. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8039. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8040. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8041. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8042. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8043. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8044. /// <returns>Mesh oriented towards targetMesh</returns>
  8045. yawCor = yawCor || 0; // default to zero if undefined
  8046. pitchCor = pitchCor || 0;
  8047. rollCor = rollCor || 0;
  8048. var dv = targetPoint.subtract(this.position);
  8049. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8050. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8051. var pitch = Math.atan2(dv.y, len);
  8052. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8053. };
  8054. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8055. this._meshToBoneReferal = affectedMesh;
  8056. this.parent = bone;
  8057. if (bone.getWorldMatrix().determinant() < 0) {
  8058. this.scalingDeterminant *= -1;
  8059. }
  8060. };
  8061. AbstractMesh.prototype.detachFromBone = function () {
  8062. if (this.parent.getWorldMatrix().determinant() < 0) {
  8063. this.scalingDeterminant *= -1;
  8064. }
  8065. this._meshToBoneReferal = null;
  8066. this.parent = null;
  8067. };
  8068. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8069. return this._boundingInfo.isInFrustum(frustumPlanes);
  8070. };
  8071. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8072. if (!camera) {
  8073. camera = this.getScene().activeCamera;
  8074. }
  8075. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8076. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8077. return false;
  8078. }
  8079. return true;
  8080. };
  8081. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8082. if (!this._boundingInfo || !mesh._boundingInfo) {
  8083. return false;
  8084. }
  8085. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8086. };
  8087. AbstractMesh.prototype.intersectsPoint = function (point) {
  8088. if (!this._boundingInfo) {
  8089. return false;
  8090. }
  8091. return this._boundingInfo.intersectsPoint(point);
  8092. };
  8093. // Physics
  8094. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8095. var physicsEngine = this.getScene().getPhysicsEngine();
  8096. if (!physicsEngine) {
  8097. return null;
  8098. }
  8099. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8100. if (impostor.impostor) {
  8101. // Old API
  8102. options = impostor;
  8103. impostor = impostor.impostor;
  8104. }
  8105. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8106. physicsEngine._unregisterMesh(this);
  8107. return null;
  8108. }
  8109. if (!options) {
  8110. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8111. }
  8112. else {
  8113. if (!options.mass && options.mass !== 0)
  8114. options.mass = 0;
  8115. if (!options.friction && options.friction !== 0)
  8116. options.friction = 0.2;
  8117. if (!options.restitution && options.restitution !== 0)
  8118. options.restitution = 0.2;
  8119. }
  8120. this._physicImpostor = impostor;
  8121. this._physicsMass = options.mass;
  8122. this._physicsFriction = options.friction;
  8123. this._physicRestitution = options.restitution;
  8124. return physicsEngine._registerMesh(this, impostor, options);
  8125. };
  8126. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8127. if (!this._physicImpostor) {
  8128. return BABYLON.PhysicsEngine.NoImpostor;
  8129. }
  8130. return this._physicImpostor;
  8131. };
  8132. AbstractMesh.prototype.getPhysicsMass = function () {
  8133. if (!this._physicsMass) {
  8134. return 0;
  8135. }
  8136. return this._physicsMass;
  8137. };
  8138. AbstractMesh.prototype.getPhysicsFriction = function () {
  8139. if (!this._physicsFriction) {
  8140. return 0;
  8141. }
  8142. return this._physicsFriction;
  8143. };
  8144. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8145. if (!this._physicRestitution) {
  8146. return 0;
  8147. }
  8148. return this._physicRestitution;
  8149. };
  8150. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8151. if (!camera) {
  8152. camera = this.getScene().activeCamera;
  8153. }
  8154. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8155. };
  8156. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8157. if (!camera) {
  8158. camera = this.getScene().activeCamera;
  8159. }
  8160. return this.absolutePosition.subtract(camera.position).length();
  8161. };
  8162. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8163. if (!this._physicImpostor) {
  8164. return;
  8165. }
  8166. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8167. };
  8168. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8169. if (!this._physicImpostor) {
  8170. return;
  8171. }
  8172. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8173. };
  8174. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8175. if (!this._physicImpostor) {
  8176. return;
  8177. }
  8178. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8179. };
  8180. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8181. // Collisions
  8182. get: function () {
  8183. return this._checkCollisions;
  8184. },
  8185. set: function (collisionEnabled) {
  8186. this._checkCollisions = collisionEnabled;
  8187. if (this.getScene().workerCollisions) {
  8188. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8189. }
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8195. var globalPosition = this.getAbsolutePosition();
  8196. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8197. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8198. this._collider.radius = this.ellipsoid;
  8199. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8200. };
  8201. // Submeshes octree
  8202. /**
  8203. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8204. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8205. */
  8206. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8207. if (maxCapacity === void 0) { maxCapacity = 64; }
  8208. if (maxDepth === void 0) { maxDepth = 2; }
  8209. if (!this._submeshesOctree) {
  8210. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8211. }
  8212. this.computeWorldMatrix(true);
  8213. // Update octree
  8214. var bbox = this.getBoundingInfo().boundingBox;
  8215. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8216. return this._submeshesOctree;
  8217. };
  8218. // Collisions
  8219. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8220. this._generatePointsArray();
  8221. // Transformation
  8222. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8223. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8224. subMesh._lastColliderWorldVertices = [];
  8225. subMesh._trianglePlanes = [];
  8226. var start = subMesh.verticesStart;
  8227. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8228. for (var i = start; i < end; i++) {
  8229. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8230. }
  8231. }
  8232. // Collide
  8233. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8234. if (collider.collisionFound) {
  8235. collider.collidedMesh = this;
  8236. }
  8237. };
  8238. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8239. var subMeshes;
  8240. var len;
  8241. // Octrees
  8242. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8243. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8244. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8245. len = intersections.length;
  8246. subMeshes = intersections.data;
  8247. }
  8248. else {
  8249. subMeshes = this.subMeshes;
  8250. len = subMeshes.length;
  8251. }
  8252. for (var index = 0; index < len; index++) {
  8253. var subMesh = subMeshes[index];
  8254. // Bounding test
  8255. if (len > 1 && !subMesh._checkCollision(collider))
  8256. continue;
  8257. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8258. }
  8259. };
  8260. AbstractMesh.prototype._checkCollision = function (collider) {
  8261. // Bounding box test
  8262. if (!this._boundingInfo._checkCollision(collider))
  8263. return;
  8264. // Transformation matrix
  8265. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8266. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8267. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8268. };
  8269. // Picking
  8270. AbstractMesh.prototype._generatePointsArray = function () {
  8271. return false;
  8272. };
  8273. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8274. var pickingInfo = new BABYLON.PickingInfo();
  8275. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8276. return pickingInfo;
  8277. }
  8278. if (!this._generatePointsArray()) {
  8279. return pickingInfo;
  8280. }
  8281. var intersectInfo = null;
  8282. // Octrees
  8283. var subMeshes;
  8284. var len;
  8285. if (this._submeshesOctree && this.useOctreeForPicking) {
  8286. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8287. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8288. len = intersections.length;
  8289. subMeshes = intersections.data;
  8290. }
  8291. else {
  8292. subMeshes = this.subMeshes;
  8293. len = subMeshes.length;
  8294. }
  8295. for (var index = 0; index < len; index++) {
  8296. var subMesh = subMeshes[index];
  8297. // Bounding test
  8298. if (len > 1 && !subMesh.canIntersects(ray))
  8299. continue;
  8300. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8301. if (currentIntersectInfo) {
  8302. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8303. intersectInfo = currentIntersectInfo;
  8304. intersectInfo.subMeshId = index;
  8305. if (fastCheck) {
  8306. break;
  8307. }
  8308. }
  8309. }
  8310. }
  8311. if (intersectInfo) {
  8312. // Get picked point
  8313. var world = this.getWorldMatrix();
  8314. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8315. var direction = ray.direction.clone();
  8316. direction = direction.scale(intersectInfo.distance);
  8317. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8318. var pickedPoint = worldOrigin.add(worldDirection);
  8319. // Return result
  8320. pickingInfo.hit = true;
  8321. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8322. pickingInfo.pickedPoint = pickedPoint;
  8323. pickingInfo.pickedMesh = this;
  8324. pickingInfo.bu = intersectInfo.bu;
  8325. pickingInfo.bv = intersectInfo.bv;
  8326. pickingInfo.faceId = intersectInfo.faceId;
  8327. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8328. return pickingInfo;
  8329. }
  8330. return pickingInfo;
  8331. };
  8332. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8333. return null;
  8334. };
  8335. AbstractMesh.prototype.releaseSubMeshes = function () {
  8336. if (this.subMeshes) {
  8337. while (this.subMeshes.length) {
  8338. this.subMeshes[0].dispose();
  8339. }
  8340. }
  8341. else {
  8342. this.subMeshes = new Array();
  8343. }
  8344. };
  8345. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8346. var index;
  8347. // Animations
  8348. this.getScene().stopAnimation(this);
  8349. // Physics
  8350. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8351. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8352. }
  8353. // Intersections in progress
  8354. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8355. var other = this._intersectionsInProgress[index];
  8356. var pos = other._intersectionsInProgress.indexOf(this);
  8357. other._intersectionsInProgress.splice(pos, 1);
  8358. }
  8359. this._intersectionsInProgress = [];
  8360. // Edges
  8361. if (this._edgesRenderer) {
  8362. this._edgesRenderer.dispose();
  8363. this._edgesRenderer = null;
  8364. }
  8365. // SubMeshes
  8366. this.releaseSubMeshes();
  8367. // Remove from scene
  8368. this.getScene().removeMesh(this);
  8369. if (!doNotRecurse) {
  8370. // Particles
  8371. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8372. if (this.getScene().particleSystems[index].emitter === this) {
  8373. this.getScene().particleSystems[index].dispose();
  8374. index--;
  8375. }
  8376. }
  8377. // Children
  8378. var objects = this.getScene().meshes.slice(0);
  8379. for (index = 0; index < objects.length; index++) {
  8380. if (objects[index].parent === this) {
  8381. objects[index].dispose();
  8382. }
  8383. }
  8384. }
  8385. else {
  8386. for (index = 0; index < this.getScene().meshes.length; index++) {
  8387. var obj = this.getScene().meshes[index];
  8388. if (obj.parent === this) {
  8389. obj.parent = null;
  8390. obj.computeWorldMatrix(true);
  8391. }
  8392. }
  8393. }
  8394. this._onAfterWorldMatrixUpdate = [];
  8395. this._isDisposed = true;
  8396. // Callback
  8397. if (this.onDispose) {
  8398. this.onDispose();
  8399. }
  8400. };
  8401. // Statics
  8402. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8403. AbstractMesh._BILLBOARDMODE_X = 1;
  8404. AbstractMesh._BILLBOARDMODE_Y = 2;
  8405. AbstractMesh._BILLBOARDMODE_Z = 4;
  8406. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8407. return AbstractMesh;
  8408. })(BABYLON.Node);
  8409. BABYLON.AbstractMesh = AbstractMesh;
  8410. })(BABYLON || (BABYLON = {}));
  8411. var BABYLON;
  8412. (function (BABYLON) {
  8413. var Light = (function (_super) {
  8414. __extends(Light, _super);
  8415. function Light(name, scene) {
  8416. _super.call(this, name, scene);
  8417. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8418. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8419. this.intensity = 1.0;
  8420. this.range = Number.MAX_VALUE;
  8421. this.includeOnlyWithLayerMask = 0;
  8422. this.includedOnlyMeshes = new Array();
  8423. this.excludedMeshes = new Array();
  8424. this.excludeWithLayerMask = 0;
  8425. this._excludedMeshesIds = new Array();
  8426. this._includedOnlyMeshesIds = new Array();
  8427. scene.addLight(this);
  8428. }
  8429. Light.prototype.getShadowGenerator = function () {
  8430. return this._shadowGenerator;
  8431. };
  8432. Light.prototype.getAbsolutePosition = function () {
  8433. return BABYLON.Vector3.Zero();
  8434. };
  8435. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8436. };
  8437. Light.prototype._getWorldMatrix = function () {
  8438. return BABYLON.Matrix.Identity();
  8439. };
  8440. Light.prototype.canAffectMesh = function (mesh) {
  8441. if (!mesh) {
  8442. return true;
  8443. }
  8444. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8445. return false;
  8446. }
  8447. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8448. return false;
  8449. }
  8450. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8451. return false;
  8452. }
  8453. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8454. return false;
  8455. }
  8456. return true;
  8457. };
  8458. Light.prototype.getWorldMatrix = function () {
  8459. this._currentRenderId = this.getScene().getRenderId();
  8460. var worldMatrix = this._getWorldMatrix();
  8461. if (this.parent && this.parent.getWorldMatrix) {
  8462. if (!this._parentedWorldMatrix) {
  8463. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8464. }
  8465. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8466. this._markSyncedWithParent();
  8467. return this._parentedWorldMatrix;
  8468. }
  8469. return worldMatrix;
  8470. };
  8471. Light.prototype.dispose = function () {
  8472. if (this._shadowGenerator) {
  8473. this._shadowGenerator.dispose();
  8474. this._shadowGenerator = null;
  8475. }
  8476. // Animations
  8477. this.getScene().stopAnimation(this);
  8478. // Remove from scene
  8479. this.getScene().removeLight(this);
  8480. };
  8481. Light.prototype.serialize = function () {
  8482. var serializationObject = {};
  8483. serializationObject.name = this.name;
  8484. serializationObject.id = this.id;
  8485. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8486. if (this.intensity) {
  8487. serializationObject.intensity = this.intensity;
  8488. }
  8489. serializationObject.range = this.range;
  8490. serializationObject.diffuse = this.diffuse.asArray();
  8491. serializationObject.specular = this.specular.asArray();
  8492. return serializationObject;
  8493. };
  8494. Light.Parse = function (parsedLight, scene) {
  8495. var light;
  8496. switch (parsedLight.type) {
  8497. case 0:
  8498. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8499. break;
  8500. case 1:
  8501. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8502. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8503. break;
  8504. case 2:
  8505. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8506. break;
  8507. case 3:
  8508. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8509. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8510. break;
  8511. }
  8512. light.id = parsedLight.id;
  8513. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8514. if (parsedLight.intensity !== undefined) {
  8515. light.intensity = parsedLight.intensity;
  8516. }
  8517. if (parsedLight.range) {
  8518. light.range = parsedLight.range;
  8519. }
  8520. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8521. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8522. if (parsedLight.excludedMeshesIds) {
  8523. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8524. }
  8525. // Parent
  8526. if (parsedLight.parentId) {
  8527. light._waitingParentId = parsedLight.parentId;
  8528. }
  8529. if (parsedLight.includedOnlyMeshesIds) {
  8530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8531. }
  8532. // Animations
  8533. if (parsedLight.animations) {
  8534. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8535. var parsedAnimation = parsedLight.animations[animationIndex];
  8536. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8537. }
  8538. }
  8539. if (parsedLight.autoAnimate) {
  8540. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8541. }
  8542. return light;
  8543. };
  8544. return Light;
  8545. })(BABYLON.Node);
  8546. BABYLON.Light = Light;
  8547. })(BABYLON || (BABYLON = {}));
  8548. var BABYLON;
  8549. (function (BABYLON) {
  8550. var PointLight = (function (_super) {
  8551. __extends(PointLight, _super);
  8552. function PointLight(name, position, scene) {
  8553. _super.call(this, name, scene);
  8554. this.position = position;
  8555. }
  8556. PointLight.prototype.getAbsolutePosition = function () {
  8557. return this.transformedPosition ? this.transformedPosition : this.position;
  8558. };
  8559. PointLight.prototype.computeTransformedPosition = function () {
  8560. if (this.parent && this.parent.getWorldMatrix) {
  8561. if (!this.transformedPosition) {
  8562. this.transformedPosition = BABYLON.Vector3.Zero();
  8563. }
  8564. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8565. return true;
  8566. }
  8567. return false;
  8568. };
  8569. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8570. if (this.parent && this.parent.getWorldMatrix) {
  8571. this.computeTransformedPosition();
  8572. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8573. return;
  8574. }
  8575. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8576. };
  8577. PointLight.prototype.needCube = function () {
  8578. return true;
  8579. };
  8580. PointLight.prototype.supportsVSM = function () {
  8581. return false;
  8582. };
  8583. PointLight.prototype.needRefreshPerFrame = function () {
  8584. return false;
  8585. };
  8586. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8587. switch (faceIndex) {
  8588. case 0:
  8589. return new BABYLON.Vector3(1, 0, 0);
  8590. case 1:
  8591. return new BABYLON.Vector3(-1, 0, 0);
  8592. case 2:
  8593. return new BABYLON.Vector3(0, -1, 0);
  8594. case 3:
  8595. return new BABYLON.Vector3(0, 1, 0);
  8596. case 4:
  8597. return new BABYLON.Vector3(0, 0, 1);
  8598. case 5:
  8599. return new BABYLON.Vector3(0, 0, -1);
  8600. }
  8601. return BABYLON.Vector3.Zero();
  8602. };
  8603. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8604. var activeCamera = this.getScene().activeCamera;
  8605. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8606. };
  8607. PointLight.prototype._getWorldMatrix = function () {
  8608. if (!this._worldMatrix) {
  8609. this._worldMatrix = BABYLON.Matrix.Identity();
  8610. }
  8611. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8612. return this._worldMatrix;
  8613. };
  8614. PointLight.prototype.serialize = function () {
  8615. var serializationObject = _super.prototype.serialize.call(this);
  8616. serializationObject.type = 0;
  8617. serializationObject.position = this.position.asArray();
  8618. return serializationObject;
  8619. };
  8620. return PointLight;
  8621. })(BABYLON.Light);
  8622. BABYLON.PointLight = PointLight;
  8623. })(BABYLON || (BABYLON = {}));
  8624. var BABYLON;
  8625. (function (BABYLON) {
  8626. var SpotLight = (function (_super) {
  8627. __extends(SpotLight, _super);
  8628. function SpotLight(name, position, direction, angle, exponent, scene) {
  8629. _super.call(this, name, scene);
  8630. this.position = position;
  8631. this.direction = direction;
  8632. this.angle = angle;
  8633. this.exponent = exponent;
  8634. }
  8635. SpotLight.prototype.getAbsolutePosition = function () {
  8636. return this.transformedPosition ? this.transformedPosition : this.position;
  8637. };
  8638. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8639. var activeCamera = this.getScene().activeCamera;
  8640. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8641. };
  8642. SpotLight.prototype.needCube = function () {
  8643. return false;
  8644. };
  8645. SpotLight.prototype.supportsVSM = function () {
  8646. return true;
  8647. };
  8648. SpotLight.prototype.needRefreshPerFrame = function () {
  8649. return false;
  8650. };
  8651. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8652. return this.direction;
  8653. };
  8654. SpotLight.prototype.setDirectionToTarget = function (target) {
  8655. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8656. return this.direction;
  8657. };
  8658. SpotLight.prototype.computeTransformedPosition = function () {
  8659. if (this.parent && this.parent.getWorldMatrix) {
  8660. if (!this.transformedPosition) {
  8661. this.transformedPosition = BABYLON.Vector3.Zero();
  8662. }
  8663. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8664. return true;
  8665. }
  8666. return false;
  8667. };
  8668. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8669. var normalizeDirection;
  8670. if (this.parent && this.parent.getWorldMatrix) {
  8671. if (!this._transformedDirection) {
  8672. this._transformedDirection = BABYLON.Vector3.Zero();
  8673. }
  8674. this.computeTransformedPosition();
  8675. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8676. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8677. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8678. }
  8679. else {
  8680. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8681. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8682. }
  8683. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8684. };
  8685. SpotLight.prototype._getWorldMatrix = function () {
  8686. if (!this._worldMatrix) {
  8687. this._worldMatrix = BABYLON.Matrix.Identity();
  8688. }
  8689. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8690. return this._worldMatrix;
  8691. };
  8692. SpotLight.prototype.serialize = function () {
  8693. var serializationObject = _super.prototype.serialize.call(this);
  8694. serializationObject.type = 2;
  8695. serializationObject.position = this.position.asArray();
  8696. serializationObject.direction = this.position.asArray();
  8697. serializationObject.angle = this.angle;
  8698. serializationObject.exponent = this.exponent;
  8699. return serializationObject;
  8700. };
  8701. return SpotLight;
  8702. })(BABYLON.Light);
  8703. BABYLON.SpotLight = SpotLight;
  8704. })(BABYLON || (BABYLON = {}));
  8705. var BABYLON;
  8706. (function (BABYLON) {
  8707. var HemisphericLight = (function (_super) {
  8708. __extends(HemisphericLight, _super);
  8709. function HemisphericLight(name, direction, scene) {
  8710. _super.call(this, name, scene);
  8711. this.direction = direction;
  8712. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8713. }
  8714. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8715. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8716. return this.direction;
  8717. };
  8718. HemisphericLight.prototype.getShadowGenerator = function () {
  8719. return null;
  8720. };
  8721. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8722. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8723. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8724. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8725. };
  8726. HemisphericLight.prototype._getWorldMatrix = function () {
  8727. if (!this._worldMatrix) {
  8728. this._worldMatrix = BABYLON.Matrix.Identity();
  8729. }
  8730. return this._worldMatrix;
  8731. };
  8732. HemisphericLight.prototype.serialize = function () {
  8733. var serializationObject = _super.prototype.serialize.call(this);
  8734. serializationObject.type = 3;
  8735. serializationObject.direction = this.direction.asArray();
  8736. serializationObject.groundColor = this.groundColor.asArray();
  8737. return serializationObject;
  8738. };
  8739. return HemisphericLight;
  8740. })(BABYLON.Light);
  8741. BABYLON.HemisphericLight = HemisphericLight;
  8742. })(BABYLON || (BABYLON = {}));
  8743. var BABYLON;
  8744. (function (BABYLON) {
  8745. var DirectionalLight = (function (_super) {
  8746. __extends(DirectionalLight, _super);
  8747. function DirectionalLight(name, direction, scene) {
  8748. _super.call(this, name, scene);
  8749. this.direction = direction;
  8750. this.shadowOrthoScale = 0.5;
  8751. this.autoUpdateExtends = true;
  8752. // Cache
  8753. this._orthoLeft = Number.MAX_VALUE;
  8754. this._orthoRight = Number.MIN_VALUE;
  8755. this._orthoTop = Number.MIN_VALUE;
  8756. this._orthoBottom = Number.MAX_VALUE;
  8757. this.position = direction.scale(-1);
  8758. }
  8759. DirectionalLight.prototype.getAbsolutePosition = function () {
  8760. return this.transformedPosition ? this.transformedPosition : this.position;
  8761. };
  8762. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8763. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8764. return this.direction;
  8765. };
  8766. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8767. var activeCamera = this.getScene().activeCamera;
  8768. // Check extends
  8769. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8770. var tempVector3 = BABYLON.Vector3.Zero();
  8771. this._orthoLeft = Number.MAX_VALUE;
  8772. this._orthoRight = Number.MIN_VALUE;
  8773. this._orthoTop = Number.MIN_VALUE;
  8774. this._orthoBottom = Number.MAX_VALUE;
  8775. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8776. var mesh = renderList[meshIndex];
  8777. if (!mesh) {
  8778. continue;
  8779. }
  8780. var boundingInfo = mesh.getBoundingInfo();
  8781. if (!boundingInfo) {
  8782. continue;
  8783. }
  8784. var boundingBox = boundingInfo.boundingBox;
  8785. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8786. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8787. if (tempVector3.x < this._orthoLeft)
  8788. this._orthoLeft = tempVector3.x;
  8789. if (tempVector3.y < this._orthoBottom)
  8790. this._orthoBottom = tempVector3.y;
  8791. if (tempVector3.x > this._orthoRight)
  8792. this._orthoRight = tempVector3.x;
  8793. if (tempVector3.y > this._orthoTop)
  8794. this._orthoTop = tempVector3.y;
  8795. }
  8796. }
  8797. }
  8798. var xOffset = this._orthoRight - this._orthoLeft;
  8799. var yOffset = this._orthoTop - this._orthoBottom;
  8800. 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);
  8801. };
  8802. DirectionalLight.prototype.supportsVSM = function () {
  8803. return true;
  8804. };
  8805. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8806. return true;
  8807. };
  8808. DirectionalLight.prototype.needCube = function () {
  8809. return false;
  8810. };
  8811. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8812. return this.direction;
  8813. };
  8814. DirectionalLight.prototype.computeTransformedPosition = function () {
  8815. if (this.parent && this.parent.getWorldMatrix) {
  8816. if (!this.transformedPosition) {
  8817. this.transformedPosition = BABYLON.Vector3.Zero();
  8818. }
  8819. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8820. return true;
  8821. }
  8822. return false;
  8823. };
  8824. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8825. if (this.parent && this.parent.getWorldMatrix) {
  8826. if (!this._transformedDirection) {
  8827. this._transformedDirection = BABYLON.Vector3.Zero();
  8828. }
  8829. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8830. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8831. return;
  8832. }
  8833. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8834. };
  8835. DirectionalLight.prototype._getWorldMatrix = function () {
  8836. if (!this._worldMatrix) {
  8837. this._worldMatrix = BABYLON.Matrix.Identity();
  8838. }
  8839. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8840. return this._worldMatrix;
  8841. };
  8842. DirectionalLight.prototype.serialize = function () {
  8843. var serializationObject = _super.prototype.serialize.call(this);
  8844. serializationObject.type = 1;
  8845. serializationObject.position = this.position.asArray();
  8846. serializationObject.direction = this.direction.asArray();
  8847. return serializationObject;
  8848. };
  8849. return DirectionalLight;
  8850. })(BABYLON.Light);
  8851. BABYLON.DirectionalLight = DirectionalLight;
  8852. })(BABYLON || (BABYLON = {}));
  8853. var BABYLON;
  8854. (function (BABYLON) {
  8855. var ShadowGenerator = (function () {
  8856. function ShadowGenerator(mapSize, light) {
  8857. var _this = this;
  8858. // Members
  8859. this._filter = ShadowGenerator.FILTER_NONE;
  8860. this.blurScale = 2;
  8861. this._blurBoxOffset = 0;
  8862. this._bias = 0.00005;
  8863. this._lightDirection = BABYLON.Vector3.Zero();
  8864. this._darkness = 0;
  8865. this._transparencyShadow = false;
  8866. this._viewMatrix = BABYLON.Matrix.Zero();
  8867. this._projectionMatrix = BABYLON.Matrix.Zero();
  8868. this._transformMatrix = BABYLON.Matrix.Zero();
  8869. this._worldViewProjection = BABYLON.Matrix.Zero();
  8870. this._currentFaceIndex = 0;
  8871. this._currentFaceIndexCache = 0;
  8872. this._light = light;
  8873. this._scene = light.getScene();
  8874. this._mapSize = mapSize;
  8875. light._shadowGenerator = this;
  8876. // Render target
  8877. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8878. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8879. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8880. this._shadowMap.anisotropicFilteringLevel = 1;
  8881. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8882. this._shadowMap.renderParticles = false;
  8883. this._shadowMap.onBeforeRender = function (faceIndex) {
  8884. _this._currentFaceIndex = faceIndex;
  8885. };
  8886. this._shadowMap.onAfterUnbind = function () {
  8887. if (!_this.useBlurVarianceShadowMap) {
  8888. return;
  8889. }
  8890. if (!_this._shadowMap2) {
  8891. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8892. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8893. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8894. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8895. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8896. _this._downSamplePostprocess.onApply = function (effect) {
  8897. effect.setTexture("textureSampler", _this._shadowMap);
  8898. };
  8899. _this.blurBoxOffset = 1;
  8900. }
  8901. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8902. };
  8903. // Custom render function
  8904. var renderSubMesh = function (subMesh) {
  8905. var mesh = subMesh.getRenderingMesh();
  8906. var scene = _this._scene;
  8907. var engine = scene.getEngine();
  8908. // Culling
  8909. engine.setState(subMesh.getMaterial().backFaceCulling);
  8910. // Managing instances
  8911. var batch = mesh._getInstancesRenderList(subMesh._id);
  8912. if (batch.mustReturn) {
  8913. return;
  8914. }
  8915. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8916. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8917. engine.enableEffect(_this._effect);
  8918. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8919. var material = subMesh.getMaterial();
  8920. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8921. // Alpha test
  8922. if (material && material.needAlphaTesting()) {
  8923. var alphaTexture = material.getAlphaTestTexture();
  8924. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8925. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8926. }
  8927. // Bones
  8928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8929. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8930. }
  8931. // Draw
  8932. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8933. }
  8934. else {
  8935. // Need to reset refresh rate of the shadowMap
  8936. _this._shadowMap.resetRefreshCounter();
  8937. }
  8938. };
  8939. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8940. var index;
  8941. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8942. renderSubMesh(opaqueSubMeshes.data[index]);
  8943. }
  8944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8945. renderSubMesh(alphaTestSubMeshes.data[index]);
  8946. }
  8947. if (_this._transparencyShadow) {
  8948. for (index = 0; index < transparentSubMeshes.length; index++) {
  8949. renderSubMesh(transparentSubMeshes.data[index]);
  8950. }
  8951. }
  8952. };
  8953. this._shadowMap.onClear = function (engine) {
  8954. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8955. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8956. }
  8957. else {
  8958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8959. }
  8960. };
  8961. }
  8962. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8963. // Static
  8964. get: function () {
  8965. return ShadowGenerator._FILTER_NONE;
  8966. },
  8967. enumerable: true,
  8968. configurable: true
  8969. });
  8970. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8971. get: function () {
  8972. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8973. },
  8974. enumerable: true,
  8975. configurable: true
  8976. });
  8977. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8978. get: function () {
  8979. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8985. get: function () {
  8986. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8987. },
  8988. enumerable: true,
  8989. configurable: true
  8990. });
  8991. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8992. get: function () {
  8993. return this._bias;
  8994. },
  8995. set: function (bias) {
  8996. this._bias = bias;
  8997. },
  8998. enumerable: true,
  8999. configurable: true
  9000. });
  9001. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9002. get: function () {
  9003. return this._blurBoxOffset;
  9004. },
  9005. set: function (value) {
  9006. var _this = this;
  9007. if (this._blurBoxOffset === value) {
  9008. return;
  9009. }
  9010. this._blurBoxOffset = value;
  9011. if (this._boxBlurPostprocess) {
  9012. this._boxBlurPostprocess.dispose();
  9013. }
  9014. 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);
  9015. this._boxBlurPostprocess.onApply = function (effect) {
  9016. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9017. };
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9023. get: function () {
  9024. return this._filter;
  9025. },
  9026. set: function (value) {
  9027. if (this._filter === value) {
  9028. return;
  9029. }
  9030. this._filter = value;
  9031. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9032. this._shadowMap.anisotropicFilteringLevel = 16;
  9033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9034. }
  9035. else {
  9036. this._shadowMap.anisotropicFilteringLevel = 1;
  9037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9038. }
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9044. get: function () {
  9045. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9046. },
  9047. set: function (value) {
  9048. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9049. },
  9050. enumerable: true,
  9051. configurable: true
  9052. });
  9053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9054. get: function () {
  9055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9056. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9057. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9058. },
  9059. set: function (value) {
  9060. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9066. get: function () {
  9067. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9068. },
  9069. set: function (value) {
  9070. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9076. var defines = [];
  9077. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9078. defines.push("#define VSM");
  9079. }
  9080. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9081. var mesh = subMesh.getMesh();
  9082. var material = subMesh.getMaterial();
  9083. // Alpha test
  9084. if (material && material.needAlphaTesting()) {
  9085. defines.push("#define ALPHATEST");
  9086. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9087. attribs.push(BABYLON.VertexBuffer.UVKind);
  9088. defines.push("#define UV1");
  9089. }
  9090. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9092. defines.push("#define UV2");
  9093. }
  9094. }
  9095. // Bones
  9096. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9097. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9098. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9099. if (mesh.numBoneInfluencers > 4) {
  9100. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9101. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9102. }
  9103. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9104. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9105. }
  9106. else {
  9107. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9108. }
  9109. // Instances
  9110. if (useInstances) {
  9111. defines.push("#define INSTANCES");
  9112. attribs.push("world0");
  9113. attribs.push("world1");
  9114. attribs.push("world2");
  9115. attribs.push("world3");
  9116. }
  9117. // Get correct effect
  9118. var join = defines.join("\n");
  9119. if (this._cachedDefines !== join) {
  9120. this._cachedDefines = join;
  9121. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9122. }
  9123. return this._effect.isReady();
  9124. };
  9125. ShadowGenerator.prototype.getShadowMap = function () {
  9126. return this._shadowMap;
  9127. };
  9128. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9129. if (this._shadowMap2) {
  9130. return this._shadowMap2;
  9131. }
  9132. return this._shadowMap;
  9133. };
  9134. ShadowGenerator.prototype.getLight = function () {
  9135. return this._light;
  9136. };
  9137. // Methods
  9138. ShadowGenerator.prototype.getTransformMatrix = function () {
  9139. var scene = this._scene;
  9140. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9141. return this._transformMatrix;
  9142. }
  9143. this._currentRenderID = scene.getRenderId();
  9144. this._currentFaceIndexCache = this._currentFaceIndex;
  9145. var lightPosition = this._light.position;
  9146. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9147. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9148. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9149. }
  9150. if (this._light.computeTransformedPosition()) {
  9151. lightPosition = this._light.transformedPosition;
  9152. }
  9153. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9154. this._cachedPosition = lightPosition.clone();
  9155. this._cachedDirection = this._lightDirection.clone();
  9156. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9157. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9158. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9159. }
  9160. return this._transformMatrix;
  9161. };
  9162. ShadowGenerator.prototype.getDarkness = function () {
  9163. return this._darkness;
  9164. };
  9165. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9166. if (darkness >= 1.0)
  9167. this._darkness = 1.0;
  9168. else if (darkness <= 0.0)
  9169. this._darkness = 0.0;
  9170. else
  9171. this._darkness = darkness;
  9172. };
  9173. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9174. this._transparencyShadow = hasShadow;
  9175. };
  9176. ShadowGenerator.prototype._packHalf = function (depth) {
  9177. var scale = depth * 255.0;
  9178. var fract = scale - Math.floor(scale);
  9179. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9180. };
  9181. ShadowGenerator.prototype.dispose = function () {
  9182. this._shadowMap.dispose();
  9183. if (this._shadowMap2) {
  9184. this._shadowMap2.dispose();
  9185. }
  9186. if (this._downSamplePostprocess) {
  9187. this._downSamplePostprocess.dispose();
  9188. }
  9189. if (this._boxBlurPostprocess) {
  9190. this._boxBlurPostprocess.dispose();
  9191. }
  9192. };
  9193. ShadowGenerator.prototype.serialize = function () {
  9194. var serializationObject = {};
  9195. serializationObject.lightId = this._light.id;
  9196. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9197. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9198. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9199. serializationObject.renderList = [];
  9200. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9201. var mesh = this.getShadowMap().renderList[meshIndex];
  9202. serializationObject.renderList.push(mesh.id);
  9203. }
  9204. return serializationObject;
  9205. };
  9206. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9207. //casting to point light, as light is missing the position attr and typescript complains.
  9208. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9209. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9210. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9211. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9212. shadowGenerator.getShadowMap().renderList.push(mesh);
  9213. }
  9214. if (parsedShadowGenerator.usePoissonSampling) {
  9215. shadowGenerator.usePoissonSampling = true;
  9216. }
  9217. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9218. shadowGenerator.useVarianceShadowMap = true;
  9219. }
  9220. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9221. shadowGenerator.useBlurVarianceShadowMap = true;
  9222. if (parsedShadowGenerator.blurScale) {
  9223. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9224. }
  9225. if (parsedShadowGenerator.blurBoxOffset) {
  9226. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9227. }
  9228. }
  9229. if (parsedShadowGenerator.bias !== undefined) {
  9230. shadowGenerator.bias = parsedShadowGenerator.bias;
  9231. }
  9232. return shadowGenerator;
  9233. };
  9234. ShadowGenerator._FILTER_NONE = 0;
  9235. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9236. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9237. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9238. return ShadowGenerator;
  9239. })();
  9240. BABYLON.ShadowGenerator = ShadowGenerator;
  9241. })(BABYLON || (BABYLON = {}));
  9242. var BABYLON;
  9243. (function (BABYLON) {
  9244. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9245. if (boxMin.x > sphereCenter.x + sphereRadius)
  9246. return false;
  9247. if (sphereCenter.x - sphereRadius > boxMax.x)
  9248. return false;
  9249. if (boxMin.y > sphereCenter.y + sphereRadius)
  9250. return false;
  9251. if (sphereCenter.y - sphereRadius > boxMax.y)
  9252. return false;
  9253. if (boxMin.z > sphereCenter.z + sphereRadius)
  9254. return false;
  9255. if (sphereCenter.z - sphereRadius > boxMax.z)
  9256. return false;
  9257. return true;
  9258. };
  9259. var getLowestRoot = function (a, b, c, maxR) {
  9260. var determinant = b * b - 4.0 * a * c;
  9261. var result = { root: 0, found: false };
  9262. if (determinant < 0)
  9263. return result;
  9264. var sqrtD = Math.sqrt(determinant);
  9265. var r1 = (-b - sqrtD) / (2.0 * a);
  9266. var r2 = (-b + sqrtD) / (2.0 * a);
  9267. if (r1 > r2) {
  9268. var temp = r2;
  9269. r2 = r1;
  9270. r1 = temp;
  9271. }
  9272. if (r1 > 0 && r1 < maxR) {
  9273. result.root = r1;
  9274. result.found = true;
  9275. return result;
  9276. }
  9277. if (r2 > 0 && r2 < maxR) {
  9278. result.root = r2;
  9279. result.found = true;
  9280. return result;
  9281. }
  9282. return result;
  9283. };
  9284. var Collider = (function () {
  9285. function Collider() {
  9286. this.radius = new BABYLON.Vector3(1, 1, 1);
  9287. this.retry = 0;
  9288. this.basePointWorld = BABYLON.Vector3.Zero();
  9289. this.velocityWorld = BABYLON.Vector3.Zero();
  9290. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9291. this._collisionPoint = BABYLON.Vector3.Zero();
  9292. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9293. this._tempVector = BABYLON.Vector3.Zero();
  9294. this._tempVector2 = BABYLON.Vector3.Zero();
  9295. this._tempVector3 = BABYLON.Vector3.Zero();
  9296. this._tempVector4 = BABYLON.Vector3.Zero();
  9297. this._edge = BABYLON.Vector3.Zero();
  9298. this._baseToVertex = BABYLON.Vector3.Zero();
  9299. this._destinationPoint = BABYLON.Vector3.Zero();
  9300. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9301. this._displacementVector = BABYLON.Vector3.Zero();
  9302. }
  9303. // Methods
  9304. Collider.prototype._initialize = function (source, dir, e) {
  9305. this.velocity = dir;
  9306. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9307. this.basePoint = source;
  9308. source.multiplyToRef(this.radius, this.basePointWorld);
  9309. dir.multiplyToRef(this.radius, this.velocityWorld);
  9310. this.velocityWorldLength = this.velocityWorld.length();
  9311. this.epsilon = e;
  9312. this.collisionFound = false;
  9313. };
  9314. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9315. pa.subtractToRef(point, this._tempVector);
  9316. pb.subtractToRef(point, this._tempVector2);
  9317. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9318. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9319. if (d < 0)
  9320. return false;
  9321. pc.subtractToRef(point, this._tempVector3);
  9322. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9323. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9324. if (d < 0)
  9325. return false;
  9326. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9327. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9328. return d >= 0;
  9329. };
  9330. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9331. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9332. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9333. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9334. return false;
  9335. }
  9336. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9337. return false;
  9338. return true;
  9339. };
  9340. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9341. var t0;
  9342. var embeddedInPlane = false;
  9343. //defensive programming, actually not needed.
  9344. if (!trianglePlaneArray) {
  9345. trianglePlaneArray = [];
  9346. }
  9347. if (!trianglePlaneArray[faceIndex]) {
  9348. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9349. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9350. }
  9351. var trianglePlane = trianglePlaneArray[faceIndex];
  9352. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9353. return;
  9354. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9355. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9356. if (normalDotVelocity == 0) {
  9357. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9358. return;
  9359. embeddedInPlane = true;
  9360. t0 = 0;
  9361. }
  9362. else {
  9363. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9364. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9365. if (t0 > t1) {
  9366. var temp = t1;
  9367. t1 = t0;
  9368. t0 = temp;
  9369. }
  9370. if (t0 > 1.0 || t1 < 0.0)
  9371. return;
  9372. if (t0 < 0)
  9373. t0 = 0;
  9374. if (t0 > 1.0)
  9375. t0 = 1.0;
  9376. }
  9377. this._collisionPoint.copyFromFloats(0, 0, 0);
  9378. var found = false;
  9379. var t = 1.0;
  9380. if (!embeddedInPlane) {
  9381. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9382. this.velocity.scaleToRef(t0, this._tempVector);
  9383. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9384. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9385. found = true;
  9386. t = t0;
  9387. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9388. }
  9389. }
  9390. if (!found) {
  9391. var velocitySquaredLength = this.velocity.lengthSquared();
  9392. var a = velocitySquaredLength;
  9393. this.basePoint.subtractToRef(p1, this._tempVector);
  9394. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9395. var c = this._tempVector.lengthSquared() - 1.0;
  9396. var lowestRoot = getLowestRoot(a, b, c, t);
  9397. if (lowestRoot.found) {
  9398. t = lowestRoot.root;
  9399. found = true;
  9400. this._collisionPoint.copyFrom(p1);
  9401. }
  9402. this.basePoint.subtractToRef(p2, this._tempVector);
  9403. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9404. c = this._tempVector.lengthSquared() - 1.0;
  9405. lowestRoot = getLowestRoot(a, b, c, t);
  9406. if (lowestRoot.found) {
  9407. t = lowestRoot.root;
  9408. found = true;
  9409. this._collisionPoint.copyFrom(p2);
  9410. }
  9411. this.basePoint.subtractToRef(p3, this._tempVector);
  9412. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9413. c = this._tempVector.lengthSquared() - 1.0;
  9414. lowestRoot = getLowestRoot(a, b, c, t);
  9415. if (lowestRoot.found) {
  9416. t = lowestRoot.root;
  9417. found = true;
  9418. this._collisionPoint.copyFrom(p3);
  9419. }
  9420. p2.subtractToRef(p1, this._edge);
  9421. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9422. var edgeSquaredLength = this._edge.lengthSquared();
  9423. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9424. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9425. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9426. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9427. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9428. lowestRoot = getLowestRoot(a, b, c, t);
  9429. if (lowestRoot.found) {
  9430. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9431. if (f >= 0.0 && f <= 1.0) {
  9432. t = lowestRoot.root;
  9433. found = true;
  9434. this._edge.scaleInPlace(f);
  9435. p1.addToRef(this._edge, this._collisionPoint);
  9436. }
  9437. }
  9438. p3.subtractToRef(p2, this._edge);
  9439. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9440. edgeSquaredLength = this._edge.lengthSquared();
  9441. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9442. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9443. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9444. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9445. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9446. lowestRoot = getLowestRoot(a, b, c, t);
  9447. if (lowestRoot.found) {
  9448. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9449. if (f >= 0.0 && f <= 1.0) {
  9450. t = lowestRoot.root;
  9451. found = true;
  9452. this._edge.scaleInPlace(f);
  9453. p2.addToRef(this._edge, this._collisionPoint);
  9454. }
  9455. }
  9456. p1.subtractToRef(p3, this._edge);
  9457. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9458. edgeSquaredLength = this._edge.lengthSquared();
  9459. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9460. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9461. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9462. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9463. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9464. lowestRoot = getLowestRoot(a, b, c, t);
  9465. if (lowestRoot.found) {
  9466. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9467. if (f >= 0.0 && f <= 1.0) {
  9468. t = lowestRoot.root;
  9469. found = true;
  9470. this._edge.scaleInPlace(f);
  9471. p3.addToRef(this._edge, this._collisionPoint);
  9472. }
  9473. }
  9474. }
  9475. if (found) {
  9476. var distToCollision = t * this.velocity.length();
  9477. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9478. if (!this.intersectionPoint) {
  9479. this.intersectionPoint = this._collisionPoint.clone();
  9480. }
  9481. else {
  9482. this.intersectionPoint.copyFrom(this._collisionPoint);
  9483. }
  9484. this.nearestDistance = distToCollision;
  9485. this.collisionFound = true;
  9486. }
  9487. }
  9488. };
  9489. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9490. for (var i = indexStart; i < indexEnd; i += 3) {
  9491. var p1 = pts[indices[i] - decal];
  9492. var p2 = pts[indices[i + 1] - decal];
  9493. var p3 = pts[indices[i + 2] - decal];
  9494. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9495. }
  9496. };
  9497. Collider.prototype._getResponse = function (pos, vel) {
  9498. pos.addToRef(vel, this._destinationPoint);
  9499. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9500. this.basePoint.addToRef(vel, pos);
  9501. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9502. this._slidePlaneNormal.normalize();
  9503. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9504. pos.addInPlace(this._displacementVector);
  9505. this.intersectionPoint.addInPlace(this._displacementVector);
  9506. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9507. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9508. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9509. };
  9510. return Collider;
  9511. })();
  9512. BABYLON.Collider = Collider;
  9513. })(BABYLON || (BABYLON = {}));
  9514. var BABYLON;
  9515. (function (BABYLON) {
  9516. //WebWorker code will be inserted to this variable.
  9517. BABYLON.CollisionWorker = "";
  9518. (function (WorkerTaskType) {
  9519. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9520. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9521. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9522. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9523. var WorkerTaskType = BABYLON.WorkerTaskType;
  9524. (function (WorkerReplyType) {
  9525. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9526. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9527. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9528. var WorkerReplyType = BABYLON.WorkerReplyType;
  9529. var CollisionCoordinatorWorker = (function () {
  9530. function CollisionCoordinatorWorker() {
  9531. var _this = this;
  9532. this._scaledPosition = BABYLON.Vector3.Zero();
  9533. this._scaledVelocity = BABYLON.Vector3.Zero();
  9534. this.onMeshUpdated = function (mesh) {
  9535. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9536. };
  9537. this.onGeometryUpdated = function (geometry) {
  9538. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9539. };
  9540. this._afterRender = function () {
  9541. if (!_this._init)
  9542. return;
  9543. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9544. return;
  9545. }
  9546. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9547. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9548. if (_this._runningUpdated > 4) {
  9549. return;
  9550. }
  9551. ++_this._runningUpdated;
  9552. var payload = {
  9553. updatedMeshes: _this._addUpdateMeshesList,
  9554. updatedGeometries: _this._addUpdateGeometriesList,
  9555. removedGeometries: _this._toRemoveGeometryArray,
  9556. removedMeshes: _this._toRemoveMeshesArray
  9557. };
  9558. var message = {
  9559. payload: payload,
  9560. taskType: WorkerTaskType.UPDATE
  9561. };
  9562. var serializable = [];
  9563. for (var id in payload.updatedGeometries) {
  9564. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9565. //prepare transferables
  9566. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9567. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9568. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9569. }
  9570. }
  9571. _this._worker.postMessage(message, serializable);
  9572. _this._addUpdateMeshesList = {};
  9573. _this._addUpdateGeometriesList = {};
  9574. _this._toRemoveGeometryArray = [];
  9575. _this._toRemoveMeshesArray = [];
  9576. };
  9577. this._onMessageFromWorker = function (e) {
  9578. var returnData = e.data;
  9579. if (returnData.error != WorkerReplyType.SUCCESS) {
  9580. //TODO what errors can be returned from the worker?
  9581. BABYLON.Tools.Warn("error returned from worker!");
  9582. return;
  9583. }
  9584. switch (returnData.taskType) {
  9585. case WorkerTaskType.INIT:
  9586. _this._init = true;
  9587. //Update the worked with ALL of the scene's current state
  9588. _this._scene.meshes.forEach(function (mesh) {
  9589. _this.onMeshAdded(mesh);
  9590. });
  9591. _this._scene.getGeometries().forEach(function (geometry) {
  9592. _this.onGeometryAdded(geometry);
  9593. });
  9594. break;
  9595. case WorkerTaskType.UPDATE:
  9596. _this._runningUpdated--;
  9597. break;
  9598. case WorkerTaskType.COLLIDE:
  9599. _this._runningCollisionTask = false;
  9600. var returnPayload = returnData.payload;
  9601. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9602. return;
  9603. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9604. //cleanup
  9605. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9606. break;
  9607. }
  9608. };
  9609. this._collisionsCallbackArray = [];
  9610. this._init = false;
  9611. this._runningUpdated = 0;
  9612. this._runningCollisionTask = false;
  9613. this._addUpdateMeshesList = {};
  9614. this._addUpdateGeometriesList = {};
  9615. this._toRemoveGeometryArray = [];
  9616. this._toRemoveMeshesArray = [];
  9617. }
  9618. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9619. if (!this._init)
  9620. return;
  9621. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9622. return;
  9623. position.divideToRef(collider.radius, this._scaledPosition);
  9624. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9625. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9626. var payload = {
  9627. collider: {
  9628. position: this._scaledPosition.asArray(),
  9629. velocity: this._scaledVelocity.asArray(),
  9630. radius: collider.radius.asArray()
  9631. },
  9632. collisionId: collisionIndex,
  9633. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9634. maximumRetry: maximumRetry
  9635. };
  9636. var message = {
  9637. payload: payload,
  9638. taskType: WorkerTaskType.COLLIDE
  9639. };
  9640. this._worker.postMessage(message);
  9641. };
  9642. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9643. this._scene = scene;
  9644. this._scene.registerAfterRender(this._afterRender);
  9645. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9646. this._worker = new Worker(workerUrl);
  9647. this._worker.onmessage = this._onMessageFromWorker;
  9648. var message = {
  9649. payload: {},
  9650. taskType: WorkerTaskType.INIT
  9651. };
  9652. this._worker.postMessage(message);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.destroy = function () {
  9655. this._scene.unregisterAfterRender(this._afterRender);
  9656. this._worker.terminate();
  9657. };
  9658. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9659. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9660. this.onMeshUpdated(mesh);
  9661. };
  9662. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9663. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9664. };
  9665. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9666. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9667. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9668. this.onGeometryUpdated(geometry);
  9669. };
  9670. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9671. this._toRemoveGeometryArray.push(geometry.id);
  9672. };
  9673. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9674. var submeshes = [];
  9675. if (mesh.subMeshes) {
  9676. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9677. return {
  9678. position: idx,
  9679. verticesStart: sm.verticesStart,
  9680. verticesCount: sm.verticesCount,
  9681. indexStart: sm.indexStart,
  9682. indexCount: sm.indexCount,
  9683. hasMaterial: !!sm.getMaterial(),
  9684. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9685. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9686. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9687. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9688. };
  9689. });
  9690. }
  9691. var geometryId = null;
  9692. if (mesh instanceof BABYLON.Mesh) {
  9693. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9694. }
  9695. else if (mesh instanceof BABYLON.InstancedMesh) {
  9696. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9697. }
  9698. return {
  9699. uniqueId: mesh.uniqueId,
  9700. id: mesh.id,
  9701. name: mesh.name,
  9702. geometryId: geometryId,
  9703. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9704. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9705. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9706. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9707. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9708. subMeshes: submeshes,
  9709. checkCollisions: mesh.checkCollisions
  9710. };
  9711. };
  9712. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9713. return {
  9714. id: geometry.id,
  9715. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9716. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9717. indices: new Int32Array(geometry.getIndices() || []),
  9718. };
  9719. };
  9720. return CollisionCoordinatorWorker;
  9721. })();
  9722. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9723. var CollisionCoordinatorLegacy = (function () {
  9724. function CollisionCoordinatorLegacy() {
  9725. this._scaledPosition = BABYLON.Vector3.Zero();
  9726. this._scaledVelocity = BABYLON.Vector3.Zero();
  9727. this._finalPosition = BABYLON.Vector3.Zero();
  9728. }
  9729. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9730. position.divideToRef(collider.radius, this._scaledPosition);
  9731. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9732. collider.collidedMesh = null;
  9733. collider.retry = 0;
  9734. collider.initialVelocity = this._scaledVelocity;
  9735. collider.initialPosition = this._scaledPosition;
  9736. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9737. this._finalPosition.multiplyInPlace(collider.radius);
  9738. //run the callback
  9739. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9740. };
  9741. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9742. this._scene = scene;
  9743. };
  9744. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9745. //Legacy need no destruction method.
  9746. };
  9747. //No update in legacy mode
  9748. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9749. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9750. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9751. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9752. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9753. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9754. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9755. if (excludedMesh === void 0) { excludedMesh = null; }
  9756. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9757. if (collider.retry >= maximumRetry) {
  9758. finalPosition.copyFrom(position);
  9759. return;
  9760. }
  9761. collider._initialize(position, velocity, closeDistance);
  9762. // Check all meshes
  9763. for (var index = 0; index < this._scene.meshes.length; index++) {
  9764. var mesh = this._scene.meshes[index];
  9765. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9766. mesh._checkCollision(collider);
  9767. }
  9768. }
  9769. if (!collider.collisionFound) {
  9770. position.addToRef(velocity, finalPosition);
  9771. return;
  9772. }
  9773. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9774. collider._getResponse(position, velocity);
  9775. }
  9776. if (velocity.length() <= closeDistance) {
  9777. finalPosition.copyFrom(position);
  9778. return;
  9779. }
  9780. collider.retry++;
  9781. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9782. };
  9783. return CollisionCoordinatorLegacy;
  9784. })();
  9785. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9786. })(BABYLON || (BABYLON = {}));
  9787. var BABYLON;
  9788. (function (BABYLON) {
  9789. var VRCameraMetrics = (function () {
  9790. function VRCameraMetrics() {
  9791. this.compensateDistortion = true;
  9792. }
  9793. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9794. get: function () {
  9795. return this.hResolution / (2 * this.vResolution);
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9801. get: function () {
  9802. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9803. },
  9804. enumerable: true,
  9805. configurable: true
  9806. });
  9807. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9808. get: function () {
  9809. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9810. var h = (4 * meters) / this.hScreenSize;
  9811. return BABYLON.Matrix.Translation(h, 0, 0);
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9817. get: function () {
  9818. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9819. var h = (4 * meters) / this.hScreenSize;
  9820. return BABYLON.Matrix.Translation(-h, 0, 0);
  9821. },
  9822. enumerable: true,
  9823. configurable: true
  9824. });
  9825. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9826. get: function () {
  9827. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9828. },
  9829. enumerable: true,
  9830. configurable: true
  9831. });
  9832. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9833. get: function () {
  9834. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. VRCameraMetrics.GetDefault = function () {
  9840. var result = new VRCameraMetrics();
  9841. result.hResolution = 1280;
  9842. result.vResolution = 800;
  9843. result.hScreenSize = 0.149759993;
  9844. result.vScreenSize = 0.0935999975;
  9845. result.vScreenCenter = 0.0467999987,
  9846. result.eyeToScreenDistance = 0.0410000011;
  9847. result.lensSeparationDistance = 0.0635000020;
  9848. result.interpupillaryDistance = 0.0640000030;
  9849. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9850. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9851. result.postProcessScaleFactor = 1.714605507808412;
  9852. result.lensCenterOffset = 0.151976421;
  9853. return result;
  9854. };
  9855. return VRCameraMetrics;
  9856. })();
  9857. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9858. var Camera = (function (_super) {
  9859. __extends(Camera, _super);
  9860. function Camera(name, position, scene) {
  9861. _super.call(this, name, scene);
  9862. this.position = position;
  9863. // Members
  9864. this.upVector = BABYLON.Vector3.Up();
  9865. this.orthoLeft = null;
  9866. this.orthoRight = null;
  9867. this.orthoBottom = null;
  9868. this.orthoTop = null;
  9869. this.fov = 0.8;
  9870. this.minZ = 1.0;
  9871. this.maxZ = 10000.0;
  9872. this.inertia = 0.9;
  9873. this.mode = Camera.PERSPECTIVE_CAMERA;
  9874. this.isIntermediate = false;
  9875. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9876. this.layerMask = 0x0FFFFFFF;
  9877. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9878. // Camera rig members
  9879. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9880. this._rigCameras = new Array();
  9881. // Cache
  9882. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9883. this._projectionMatrix = new BABYLON.Matrix();
  9884. this._postProcesses = new Array();
  9885. this._postProcessesTakenIndices = [];
  9886. this._activeMeshes = new BABYLON.SmartArray(256);
  9887. this._globalPosition = BABYLON.Vector3.Zero();
  9888. scene.addCamera(this);
  9889. if (!scene.activeCamera) {
  9890. scene.activeCamera = this;
  9891. }
  9892. }
  9893. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9894. get: function () {
  9895. return Camera._PERSPECTIVE_CAMERA;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9901. get: function () {
  9902. return Camera._ORTHOGRAPHIC_CAMERA;
  9903. },
  9904. enumerable: true,
  9905. configurable: true
  9906. });
  9907. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9908. get: function () {
  9909. return Camera._FOVMODE_VERTICAL_FIXED;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9915. get: function () {
  9916. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9922. get: function () {
  9923. return Camera._RIG_MODE_NONE;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9929. get: function () {
  9930. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9936. get: function () {
  9937. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9943. get: function () {
  9944. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9950. get: function () {
  9951. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9957. get: function () {
  9958. return Camera._RIG_MODE_VR;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. Object.defineProperty(Camera.prototype, "globalPosition", {
  9964. get: function () {
  9965. return this._globalPosition;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Camera.prototype.getActiveMeshes = function () {
  9971. return this._activeMeshes;
  9972. };
  9973. Camera.prototype.isActiveMesh = function (mesh) {
  9974. return (this._activeMeshes.indexOf(mesh) !== -1);
  9975. };
  9976. //Cache
  9977. Camera.prototype._initCache = function () {
  9978. _super.prototype._initCache.call(this);
  9979. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9980. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9981. this._cache.mode = undefined;
  9982. this._cache.minZ = undefined;
  9983. this._cache.maxZ = undefined;
  9984. this._cache.fov = undefined;
  9985. this._cache.aspectRatio = undefined;
  9986. this._cache.orthoLeft = undefined;
  9987. this._cache.orthoRight = undefined;
  9988. this._cache.orthoBottom = undefined;
  9989. this._cache.orthoTop = undefined;
  9990. this._cache.renderWidth = undefined;
  9991. this._cache.renderHeight = undefined;
  9992. };
  9993. Camera.prototype._updateCache = function (ignoreParentClass) {
  9994. if (!ignoreParentClass) {
  9995. _super.prototype._updateCache.call(this);
  9996. }
  9997. var engine = this.getEngine();
  9998. this._cache.position.copyFrom(this.position);
  9999. this._cache.upVector.copyFrom(this.upVector);
  10000. this._cache.mode = this.mode;
  10001. this._cache.minZ = this.minZ;
  10002. this._cache.maxZ = this.maxZ;
  10003. this._cache.fov = this.fov;
  10004. this._cache.aspectRatio = engine.getAspectRatio(this);
  10005. this._cache.orthoLeft = this.orthoLeft;
  10006. this._cache.orthoRight = this.orthoRight;
  10007. this._cache.orthoBottom = this.orthoBottom;
  10008. this._cache.orthoTop = this.orthoTop;
  10009. this._cache.renderWidth = engine.getRenderWidth();
  10010. this._cache.renderHeight = engine.getRenderHeight();
  10011. };
  10012. Camera.prototype._updateFromScene = function () {
  10013. this.updateCache();
  10014. this._update();
  10015. };
  10016. // Synchronized
  10017. Camera.prototype._isSynchronized = function () {
  10018. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10019. };
  10020. Camera.prototype._isSynchronizedViewMatrix = function () {
  10021. if (!_super.prototype._isSynchronized.call(this))
  10022. return false;
  10023. return this._cache.position.equals(this.position)
  10024. && this._cache.upVector.equals(this.upVector)
  10025. && this.isSynchronizedWithParent();
  10026. };
  10027. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10028. var check = this._cache.mode === this.mode
  10029. && this._cache.minZ === this.minZ
  10030. && this._cache.maxZ === this.maxZ;
  10031. if (!check) {
  10032. return false;
  10033. }
  10034. var engine = this.getEngine();
  10035. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10036. check = this._cache.fov === this.fov
  10037. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10038. }
  10039. else {
  10040. check = this._cache.orthoLeft === this.orthoLeft
  10041. && this._cache.orthoRight === this.orthoRight
  10042. && this._cache.orthoBottom === this.orthoBottom
  10043. && this._cache.orthoTop === this.orthoTop
  10044. && this._cache.renderWidth === engine.getRenderWidth()
  10045. && this._cache.renderHeight === engine.getRenderHeight();
  10046. }
  10047. return check;
  10048. };
  10049. // Controls
  10050. Camera.prototype.attachControl = function (element) {
  10051. };
  10052. Camera.prototype.detachControl = function (element) {
  10053. };
  10054. Camera.prototype._update = function () {
  10055. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10056. this._updateRigCameras();
  10057. }
  10058. this._checkInputs();
  10059. };
  10060. Camera.prototype._checkInputs = function () {
  10061. };
  10062. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10063. if (insertAt === void 0) { insertAt = null; }
  10064. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10065. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10066. return 0;
  10067. }
  10068. if (insertAt == null || insertAt < 0) {
  10069. this._postProcesses.push(postProcess);
  10070. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10071. return this._postProcesses.length - 1;
  10072. }
  10073. var add = 0;
  10074. var i;
  10075. var start;
  10076. if (this._postProcesses[insertAt]) {
  10077. start = this._postProcesses.length - 1;
  10078. for (i = start; i >= insertAt + 1; --i) {
  10079. this._postProcesses[i + 1] = this._postProcesses[i];
  10080. }
  10081. add = 1;
  10082. }
  10083. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10084. if (this._postProcessesTakenIndices[i] < insertAt) {
  10085. continue;
  10086. }
  10087. start = this._postProcessesTakenIndices.length - 1;
  10088. for (var j = start; j >= i; --j) {
  10089. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10090. }
  10091. this._postProcessesTakenIndices[i] = insertAt;
  10092. break;
  10093. }
  10094. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10095. this._postProcessesTakenIndices.push(insertAt);
  10096. }
  10097. var result = insertAt + add;
  10098. this._postProcesses[result] = postProcess;
  10099. return result;
  10100. };
  10101. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10102. if (atIndices === void 0) { atIndices = null; }
  10103. var result = [];
  10104. var i;
  10105. var index;
  10106. if (!atIndices) {
  10107. var length = this._postProcesses.length;
  10108. for (i = 0; i < length; i++) {
  10109. if (this._postProcesses[i] !== postProcess) {
  10110. continue;
  10111. }
  10112. delete this._postProcesses[i];
  10113. index = this._postProcessesTakenIndices.indexOf(i);
  10114. this._postProcessesTakenIndices.splice(index, 1);
  10115. }
  10116. }
  10117. else {
  10118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10119. for (i = 0; i < atIndices.length; i++) {
  10120. var foundPostProcess = this._postProcesses[atIndices[i]];
  10121. if (foundPostProcess !== postProcess) {
  10122. result.push(i);
  10123. continue;
  10124. }
  10125. delete this._postProcesses[atIndices[i]];
  10126. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10127. this._postProcessesTakenIndices.splice(index, 1);
  10128. }
  10129. }
  10130. return result;
  10131. };
  10132. Camera.prototype.getWorldMatrix = function () {
  10133. if (!this._worldMatrix) {
  10134. this._worldMatrix = BABYLON.Matrix.Identity();
  10135. }
  10136. var viewMatrix = this.getViewMatrix();
  10137. viewMatrix.invertToRef(this._worldMatrix);
  10138. return this._worldMatrix;
  10139. };
  10140. Camera.prototype._getViewMatrix = function () {
  10141. return BABYLON.Matrix.Identity();
  10142. };
  10143. Camera.prototype.getViewMatrix = function (force) {
  10144. this._computedViewMatrix = this._computeViewMatrix(force);
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. if (!this.parent || !this.parent.getWorldMatrix) {
  10149. this._globalPosition.copyFrom(this.position);
  10150. }
  10151. else {
  10152. if (!this._worldMatrix) {
  10153. this._worldMatrix = BABYLON.Matrix.Identity();
  10154. }
  10155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10158. this._computedViewMatrix.invert();
  10159. this._markSyncedWithParent();
  10160. }
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. return this._computedViewMatrix;
  10163. };
  10164. Camera.prototype._computeViewMatrix = function (force) {
  10165. if (!force && this._isSynchronizedViewMatrix()) {
  10166. return this._computedViewMatrix;
  10167. }
  10168. this._computedViewMatrix = this._getViewMatrix();
  10169. this._currentRenderId = this.getScene().getRenderId();
  10170. return this._computedViewMatrix;
  10171. };
  10172. Camera.prototype.getProjectionMatrix = function (force) {
  10173. if (!force && this._isSynchronizedProjectionMatrix()) {
  10174. return this._projectionMatrix;
  10175. }
  10176. var engine = this.getEngine();
  10177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10178. if (this.minZ <= 0) {
  10179. this.minZ = 0.1;
  10180. }
  10181. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10182. return this._projectionMatrix;
  10183. }
  10184. var halfWidth = engine.getRenderWidth() / 2.0;
  10185. var halfHeight = engine.getRenderHeight() / 2.0;
  10186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10187. return this._projectionMatrix;
  10188. };
  10189. Camera.prototype.dispose = function () {
  10190. // Animations
  10191. this.getScene().stopAnimation(this);
  10192. // Remove from scene
  10193. this.getScene().removeCamera(this);
  10194. while (this._rigCameras.length > 0) {
  10195. this._rigCameras.pop().dispose();
  10196. }
  10197. // Postprocesses
  10198. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10199. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10200. }
  10201. };
  10202. // ---- Camera rigs section ----
  10203. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10204. while (this._rigCameras.length > 0) {
  10205. this._rigCameras.pop().dispose();
  10206. }
  10207. this.cameraRigMode = mode;
  10208. this._cameraRigParams = {};
  10209. switch (this.cameraRigMode) {
  10210. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10212. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10213. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10214. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10215. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10216. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10217. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10218. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10219. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10220. break;
  10221. }
  10222. var postProcesses = new Array();
  10223. switch (this.cameraRigMode) {
  10224. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10225. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10226. this._rigCameras[0].isIntermediate = true;
  10227. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10228. postProcesses[1].onApply = function (effect) {
  10229. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10230. };
  10231. break;
  10232. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10233. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10234. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10235. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10236. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10237. var secondCamIndex = 1 - firstCamIndex;
  10238. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10239. this._rigCameras[firstCamIndex].isIntermediate = true;
  10240. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10241. break;
  10242. case Camera.RIG_MODE_VR:
  10243. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10244. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10245. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10246. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10247. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10248. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10249. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10250. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10251. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10252. if (metrics.compensateDistortion) {
  10253. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10254. }
  10255. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10256. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10257. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10258. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10259. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10260. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10261. if (metrics.compensateDistortion) {
  10262. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10263. }
  10264. break;
  10265. }
  10266. this._update();
  10267. };
  10268. Camera.prototype._getVRProjectionMatrix = function () {
  10269. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10270. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10271. return this._projectionMatrix;
  10272. };
  10273. Camera.prototype.setCameraRigParameter = function (name, value) {
  10274. this._cameraRigParams[name] = value;
  10275. //provisionnally:
  10276. if (name === "interaxialDistance") {
  10277. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10278. }
  10279. };
  10280. /**
  10281. * May needs to be overridden by children so sub has required properties to be copied
  10282. */
  10283. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10284. return null;
  10285. };
  10286. /**
  10287. * May needs to be overridden by children
  10288. */
  10289. Camera.prototype._updateRigCameras = function () {
  10290. for (var i = 0; i < this._rigCameras.length; i++) {
  10291. this._rigCameras[i].minZ = this.minZ;
  10292. this._rigCameras[i].maxZ = this.maxZ;
  10293. this._rigCameras[i].fov = this.fov;
  10294. }
  10295. // only update viewport when ANAGLYPH
  10296. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10297. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10298. }
  10299. };
  10300. Camera.prototype.serialize = function () {
  10301. var serializationObject = {};
  10302. serializationObject.name = this.name;
  10303. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10304. serializationObject.id = this.id;
  10305. serializationObject.position = this.position.asArray();
  10306. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10307. // Parent
  10308. if (this.parent) {
  10309. serializationObject.parentId = this.parent.id;
  10310. }
  10311. serializationObject.fov = this.fov;
  10312. serializationObject.minZ = this.minZ;
  10313. serializationObject.maxZ = this.maxZ;
  10314. serializationObject.inertia = this.inertia;
  10315. // Animations
  10316. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10317. // Layer mask
  10318. serializationObject.layerMask = this.layerMask;
  10319. return serializationObject;
  10320. };
  10321. Camera.Parse = function (parsedCamera, scene) {
  10322. var camera;
  10323. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10324. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10325. var interaxial_distance;
  10326. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10327. var alpha = parsedCamera.alpha;
  10328. var beta = parsedCamera.beta;
  10329. var radius = parsedCamera.radius;
  10330. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10331. interaxial_distance = parsedCamera.interaxial_distance;
  10332. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10333. }
  10334. else {
  10335. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10336. }
  10337. }
  10338. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10339. interaxial_distance = parsedCamera.interaxial_distance;
  10340. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10341. }
  10342. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10343. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10344. }
  10345. else if (parsedCamera.type === "FollowCamera") {
  10346. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10347. camera.heightOffset = parsedCamera.heightOffset;
  10348. camera.radius = parsedCamera.radius;
  10349. camera.rotationOffset = parsedCamera.rotationOffset;
  10350. if (lockedTargetMesh)
  10351. camera.target = lockedTargetMesh;
  10352. }
  10353. else if (parsedCamera.type === "GamepadCamera") {
  10354. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10355. }
  10356. else if (parsedCamera.type === "TouchCamera") {
  10357. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10358. }
  10359. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10360. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10361. }
  10362. else if (parsedCamera.type === "WebVRFreeCamera") {
  10363. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10364. }
  10365. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10366. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10367. }
  10368. else {
  10369. // Free Camera is the default value
  10370. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10371. }
  10372. // apply 3d rig, when found
  10373. if (parsedCamera.cameraRigMode) {
  10374. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10375. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10376. }
  10377. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10378. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10379. camera.lockedTarget = lockedTargetMesh;
  10380. }
  10381. camera.id = parsedCamera.id;
  10382. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10383. // Parent
  10384. if (parsedCamera.parentId) {
  10385. camera._waitingParentId = parsedCamera.parentId;
  10386. }
  10387. // Target
  10388. if (parsedCamera.target) {
  10389. if (camera.setTarget) {
  10390. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10391. }
  10392. else {
  10393. //For ArcRotate
  10394. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10395. }
  10396. }
  10397. else {
  10398. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10399. }
  10400. camera.fov = parsedCamera.fov;
  10401. camera.minZ = parsedCamera.minZ;
  10402. camera.maxZ = parsedCamera.maxZ;
  10403. camera.speed = parsedCamera.speed;
  10404. camera.inertia = parsedCamera.inertia;
  10405. camera.checkCollisions = parsedCamera.checkCollisions;
  10406. camera.applyGravity = parsedCamera.applyGravity;
  10407. if (parsedCamera.ellipsoid) {
  10408. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10409. }
  10410. // Animations
  10411. if (parsedCamera.animations) {
  10412. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10413. var parsedAnimation = parsedCamera.animations[animationIndex];
  10414. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10415. }
  10416. }
  10417. if (parsedCamera.autoAnimate) {
  10418. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10419. }
  10420. // Layer Mask
  10421. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10422. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10423. }
  10424. else {
  10425. camera.layerMask = 0x0FFFFFFF;
  10426. }
  10427. return camera;
  10428. };
  10429. // Statics
  10430. Camera._PERSPECTIVE_CAMERA = 0;
  10431. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10432. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10433. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10434. Camera._RIG_MODE_NONE = 0;
  10435. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10436. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10437. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10438. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10439. Camera._RIG_MODE_VR = 20;
  10440. return Camera;
  10441. })(BABYLON.Node);
  10442. BABYLON.Camera = Camera;
  10443. })(BABYLON || (BABYLON = {}));
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. var TargetCamera = (function (_super) {
  10447. __extends(TargetCamera, _super);
  10448. function TargetCamera(name, position, scene) {
  10449. _super.call(this, name, position, scene);
  10450. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10451. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10452. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10453. this.speed = 2.0;
  10454. this.noRotationConstraint = false;
  10455. this.lockedTarget = null;
  10456. this._currentTarget = BABYLON.Vector3.Zero();
  10457. this._viewMatrix = BABYLON.Matrix.Zero();
  10458. this._camMatrix = BABYLON.Matrix.Zero();
  10459. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10460. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10461. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10462. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10463. this._lookAtTemp = BABYLON.Matrix.Zero();
  10464. this._tempMatrix = BABYLON.Matrix.Zero();
  10465. }
  10466. TargetCamera.prototype.getFrontPosition = function (distance) {
  10467. var direction = this.getTarget().subtract(this.position);
  10468. direction.normalize();
  10469. direction.scaleInPlace(distance);
  10470. return this.globalPosition.add(direction);
  10471. };
  10472. TargetCamera.prototype._getLockedTargetPosition = function () {
  10473. if (!this.lockedTarget) {
  10474. return null;
  10475. }
  10476. return this.lockedTarget.position || this.lockedTarget;
  10477. };
  10478. // Cache
  10479. TargetCamera.prototype._initCache = function () {
  10480. _super.prototype._initCache.call(this);
  10481. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10482. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10483. };
  10484. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10485. if (!ignoreParentClass) {
  10486. _super.prototype._updateCache.call(this);
  10487. }
  10488. var lockedTargetPosition = this._getLockedTargetPosition();
  10489. if (!lockedTargetPosition) {
  10490. this._cache.lockedTarget = null;
  10491. }
  10492. else {
  10493. if (!this._cache.lockedTarget) {
  10494. this._cache.lockedTarget = lockedTargetPosition.clone();
  10495. }
  10496. else {
  10497. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10498. }
  10499. }
  10500. this._cache.rotation.copyFrom(this.rotation);
  10501. };
  10502. // Synchronized
  10503. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10504. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10505. return false;
  10506. }
  10507. var lockedTargetPosition = this._getLockedTargetPosition();
  10508. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10509. && this._cache.rotation.equals(this.rotation);
  10510. };
  10511. // Methods
  10512. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10513. var engine = this.getEngine();
  10514. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10515. };
  10516. // Target
  10517. TargetCamera.prototype.setTarget = function (target) {
  10518. this.upVector.normalize();
  10519. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10520. this._camMatrix.invert();
  10521. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10522. var vDir = target.subtract(this.position);
  10523. if (vDir.x >= 0.0) {
  10524. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10525. }
  10526. else {
  10527. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10528. }
  10529. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10530. if (isNaN(this.rotation.x)) {
  10531. this.rotation.x = 0;
  10532. }
  10533. if (isNaN(this.rotation.y)) {
  10534. this.rotation.y = 0;
  10535. }
  10536. if (isNaN(this.rotation.z)) {
  10537. this.rotation.z = 0;
  10538. }
  10539. };
  10540. TargetCamera.prototype.getTarget = function () {
  10541. return this._currentTarget;
  10542. };
  10543. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10544. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10545. };
  10546. TargetCamera.prototype._updatePosition = function () {
  10547. this.position.addInPlace(this.cameraDirection);
  10548. };
  10549. TargetCamera.prototype._checkInputs = function () {
  10550. var needToMove = this._decideIfNeedsToMove();
  10551. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10552. // Move
  10553. if (needToMove) {
  10554. this._updatePosition();
  10555. }
  10556. // Rotate
  10557. if (needToRotate) {
  10558. this.rotation.x += this.cameraRotation.x;
  10559. this.rotation.y += this.cameraRotation.y;
  10560. if (!this.noRotationConstraint) {
  10561. var limit = (Math.PI / 2) * 0.95;
  10562. if (this.rotation.x > limit)
  10563. this.rotation.x = limit;
  10564. if (this.rotation.x < -limit)
  10565. this.rotation.x = -limit;
  10566. }
  10567. }
  10568. // Inertia
  10569. if (needToMove) {
  10570. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10571. this.cameraDirection.x = 0;
  10572. }
  10573. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10574. this.cameraDirection.y = 0;
  10575. }
  10576. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10577. this.cameraDirection.z = 0;
  10578. }
  10579. this.cameraDirection.scaleInPlace(this.inertia);
  10580. }
  10581. if (needToRotate) {
  10582. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10583. this.cameraRotation.x = 0;
  10584. }
  10585. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10586. this.cameraRotation.y = 0;
  10587. }
  10588. this.cameraRotation.scaleInPlace(this.inertia);
  10589. }
  10590. _super.prototype._checkInputs.call(this);
  10591. };
  10592. TargetCamera.prototype._getViewMatrix = function () {
  10593. if (!this.lockedTarget) {
  10594. // Compute
  10595. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10596. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10597. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10598. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10599. this._lookAtTemp.invert();
  10600. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10601. }
  10602. else {
  10603. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10604. }
  10605. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10606. // Computing target and final matrix
  10607. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10608. }
  10609. else {
  10610. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10611. }
  10612. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10613. return this._viewMatrix;
  10614. };
  10615. TargetCamera.prototype._getVRViewMatrix = function () {
  10616. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10617. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10618. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10619. // Computing target and final matrix
  10620. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10621. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10622. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10623. return this._viewMatrix;
  10624. };
  10625. /**
  10626. * @override
  10627. * Override Camera.createRigCamera
  10628. */
  10629. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10630. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10631. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10632. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10633. rigCamera._cameraRigParams = {};
  10634. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10635. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10636. }
  10637. return rigCamera;
  10638. }
  10639. return null;
  10640. };
  10641. /**
  10642. * @override
  10643. * Override Camera._updateRigCameras
  10644. */
  10645. TargetCamera.prototype._updateRigCameras = function () {
  10646. switch (this.cameraRigMode) {
  10647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10651. case BABYLON.Camera.RIG_MODE_VR:
  10652. var camLeft = this._rigCameras[0];
  10653. var camRight = this._rigCameras[1];
  10654. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10655. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10656. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10657. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10658. camLeft.position.copyFrom(this.position);
  10659. camRight.position.copyFrom(this.position);
  10660. }
  10661. else {
  10662. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10663. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10664. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10665. camLeft.setTarget(this.getTarget());
  10666. camRight.setTarget(this.getTarget());
  10667. }
  10668. break;
  10669. }
  10670. _super.prototype._updateRigCameras.call(this);
  10671. };
  10672. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10673. if (!this._rigCamTransformMatrix) {
  10674. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10675. }
  10676. var target = this.getTarget();
  10677. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10678. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10679. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10680. };
  10681. TargetCamera.prototype.serialize = function () {
  10682. var serializationObject = _super.prototype.serialize.call(this);
  10683. serializationObject.speed = this.speed;
  10684. if (this.rotation) {
  10685. serializationObject.rotation = this.rotation.asArray();
  10686. }
  10687. if (this.lockedTarget && this.lockedTarget.id) {
  10688. serializationObject.lockedTargetId = this.lockedTarget.id;
  10689. }
  10690. return serializationObject;
  10691. };
  10692. return TargetCamera;
  10693. })(BABYLON.Camera);
  10694. BABYLON.TargetCamera = TargetCamera;
  10695. })(BABYLON || (BABYLON = {}));
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. var FreeCamera = (function (_super) {
  10699. __extends(FreeCamera, _super);
  10700. function FreeCamera(name, position, scene) {
  10701. var _this = this;
  10702. _super.call(this, name, position, scene);
  10703. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10704. this.keysUp = [38];
  10705. this.keysDown = [40];
  10706. this.keysLeft = [37];
  10707. this.keysRight = [39];
  10708. this.checkCollisions = false;
  10709. this.applyGravity = false;
  10710. this.angularSensibility = 2000.0;
  10711. this._keys = [];
  10712. this._collider = new BABYLON.Collider();
  10713. this._needMoveForGravity = false;
  10714. this._oldPosition = BABYLON.Vector3.Zero();
  10715. this._diffPosition = BABYLON.Vector3.Zero();
  10716. this._newPosition = BABYLON.Vector3.Zero();
  10717. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10718. if (collidedMesh === void 0) { collidedMesh = null; }
  10719. //TODO move this to the collision coordinator!
  10720. if (_this.getScene().workerCollisions)
  10721. newPosition.multiplyInPlace(_this._collider.radius);
  10722. var updatePosition = function (newPos) {
  10723. _this._newPosition.copyFrom(newPos);
  10724. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10725. var oldPosition = _this.position.clone();
  10726. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10727. _this.position.addInPlace(_this._diffPosition);
  10728. if (_this.onCollide && collidedMesh) {
  10729. _this.onCollide(collidedMesh);
  10730. }
  10731. }
  10732. };
  10733. updatePosition(newPosition);
  10734. };
  10735. }
  10736. // Controls
  10737. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10738. var _this = this;
  10739. var previousPosition;
  10740. var engine = this.getEngine();
  10741. if (this._attachedElement) {
  10742. return;
  10743. }
  10744. this._attachedElement = element;
  10745. if (this._onMouseDown === undefined) {
  10746. this._onMouseDown = function (evt) {
  10747. previousPosition = {
  10748. x: evt.clientX,
  10749. y: evt.clientY
  10750. };
  10751. if (!noPreventDefault) {
  10752. evt.preventDefault();
  10753. }
  10754. };
  10755. this._onMouseUp = function (evt) {
  10756. previousPosition = null;
  10757. if (!noPreventDefault) {
  10758. evt.preventDefault();
  10759. }
  10760. };
  10761. this._onMouseOut = function (evt) {
  10762. previousPosition = null;
  10763. _this._keys = [];
  10764. if (!noPreventDefault) {
  10765. evt.preventDefault();
  10766. }
  10767. };
  10768. this._onMouseMove = function (evt) {
  10769. if (!previousPosition && !engine.isPointerLock) {
  10770. return;
  10771. }
  10772. var offsetX;
  10773. var offsetY;
  10774. if (!engine.isPointerLock) {
  10775. offsetX = evt.clientX - previousPosition.x;
  10776. offsetY = evt.clientY - previousPosition.y;
  10777. }
  10778. else {
  10779. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10780. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10781. }
  10782. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10783. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10784. previousPosition = {
  10785. x: evt.clientX,
  10786. y: evt.clientY
  10787. };
  10788. if (!noPreventDefault) {
  10789. evt.preventDefault();
  10790. }
  10791. };
  10792. this._onKeyDown = function (evt) {
  10793. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10794. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10795. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10796. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10797. var index = _this._keys.indexOf(evt.keyCode);
  10798. if (index === -1) {
  10799. _this._keys.push(evt.keyCode);
  10800. }
  10801. if (!noPreventDefault) {
  10802. evt.preventDefault();
  10803. }
  10804. }
  10805. };
  10806. this._onKeyUp = function (evt) {
  10807. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10808. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10809. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10810. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10811. var index = _this._keys.indexOf(evt.keyCode);
  10812. if (index >= 0) {
  10813. _this._keys.splice(index, 1);
  10814. }
  10815. if (!noPreventDefault) {
  10816. evt.preventDefault();
  10817. }
  10818. }
  10819. };
  10820. this._onLostFocus = function () {
  10821. _this._keys = [];
  10822. };
  10823. this._reset = function () {
  10824. _this._keys = [];
  10825. previousPosition = null;
  10826. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10827. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10828. };
  10829. }
  10830. element.addEventListener("mousedown", this._onMouseDown, false);
  10831. element.addEventListener("mouseup", this._onMouseUp, false);
  10832. element.addEventListener("mouseout", this._onMouseOut, false);
  10833. element.addEventListener("mousemove", this._onMouseMove, false);
  10834. BABYLON.Tools.RegisterTopRootEvents([
  10835. { name: "keydown", handler: this._onKeyDown },
  10836. { name: "keyup", handler: this._onKeyUp },
  10837. { name: "blur", handler: this._onLostFocus }
  10838. ]);
  10839. };
  10840. FreeCamera.prototype.detachControl = function (element) {
  10841. if (this._attachedElement !== element) {
  10842. return;
  10843. }
  10844. element.removeEventListener("mousedown", this._onMouseDown);
  10845. element.removeEventListener("mouseup", this._onMouseUp);
  10846. element.removeEventListener("mouseout", this._onMouseOut);
  10847. element.removeEventListener("mousemove", this._onMouseMove);
  10848. BABYLON.Tools.UnregisterTopRootEvents([
  10849. { name: "keydown", handler: this._onKeyDown },
  10850. { name: "keyup", handler: this._onKeyUp },
  10851. { name: "blur", handler: this._onLostFocus }
  10852. ]);
  10853. this._attachedElement = null;
  10854. if (this._reset) {
  10855. this._reset();
  10856. }
  10857. };
  10858. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10859. var globalPosition;
  10860. if (this.parent) {
  10861. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10862. }
  10863. else {
  10864. globalPosition = this.position;
  10865. }
  10866. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10867. this._collider.radius = this.ellipsoid;
  10868. //no need for clone, as long as gravity is not on.
  10869. var actualVelocity = velocity;
  10870. //add gravity to the velocity to prevent the dual-collision checking
  10871. if (this.applyGravity) {
  10872. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10873. actualVelocity = velocity.add(this.getScene().gravity);
  10874. }
  10875. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10876. };
  10877. FreeCamera.prototype._checkInputs = function () {
  10878. if (!this._localDirection) {
  10879. this._localDirection = BABYLON.Vector3.Zero();
  10880. this._transformedDirection = BABYLON.Vector3.Zero();
  10881. }
  10882. // Keyboard
  10883. for (var index = 0; index < this._keys.length; index++) {
  10884. var keyCode = this._keys[index];
  10885. var speed = this._computeLocalCameraSpeed();
  10886. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10887. this._localDirection.copyFromFloats(-speed, 0, 0);
  10888. }
  10889. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10890. this._localDirection.copyFromFloats(0, 0, speed);
  10891. }
  10892. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10893. this._localDirection.copyFromFloats(speed, 0, 0);
  10894. }
  10895. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10896. this._localDirection.copyFromFloats(0, 0, -speed);
  10897. }
  10898. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10899. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10900. this.cameraDirection.addInPlace(this._transformedDirection);
  10901. }
  10902. _super.prototype._checkInputs.call(this);
  10903. };
  10904. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10905. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10906. };
  10907. FreeCamera.prototype._updatePosition = function () {
  10908. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10909. this._collideWithWorld(this.cameraDirection);
  10910. }
  10911. else {
  10912. this.position.addInPlace(this.cameraDirection);
  10913. }
  10914. };
  10915. FreeCamera.prototype.serialize = function () {
  10916. var serializationObject = _super.prototype.serialize.call(this);
  10917. serializationObject.checkCollisions = this.checkCollisions;
  10918. serializationObject.applyGravity = this.applyGravity;
  10919. serializationObject.ellipsoid = this.ellipsoid.asArray();
  10920. return serializationObject;
  10921. };
  10922. return FreeCamera;
  10923. })(BABYLON.TargetCamera);
  10924. BABYLON.FreeCamera = FreeCamera;
  10925. })(BABYLON || (BABYLON = {}));
  10926. var BABYLON;
  10927. (function (BABYLON) {
  10928. var FollowCamera = (function (_super) {
  10929. __extends(FollowCamera, _super);
  10930. function FollowCamera(name, position, scene) {
  10931. _super.call(this, name, position, scene);
  10932. this.radius = 12;
  10933. this.rotationOffset = 0;
  10934. this.heightOffset = 4;
  10935. this.cameraAcceleration = 0.05;
  10936. this.maxCameraSpeed = 20;
  10937. }
  10938. FollowCamera.prototype.getRadians = function (degrees) {
  10939. return degrees * Math.PI / 180;
  10940. };
  10941. FollowCamera.prototype.follow = function (cameraTarget) {
  10942. if (!cameraTarget)
  10943. return;
  10944. var yRotation;
  10945. if (cameraTarget.rotationQuaternion) {
  10946. var rotMatrix = new BABYLON.Matrix();
  10947. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10948. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10949. }
  10950. else {
  10951. yRotation = cameraTarget.rotation.y;
  10952. }
  10953. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10954. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10955. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10956. var dx = targetX - this.position.x;
  10957. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10958. var dz = (targetZ) - this.position.z;
  10959. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10960. var vy = dy * this.cameraAcceleration;
  10961. var vz = dz * this.cameraAcceleration * 2;
  10962. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10963. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10964. }
  10965. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10966. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10967. }
  10968. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10969. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10970. }
  10971. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10972. this.setTarget(cameraTarget.position);
  10973. };
  10974. FollowCamera.prototype._checkInputs = function () {
  10975. _super.prototype._checkInputs.call(this);
  10976. this.follow(this.target);
  10977. };
  10978. FollowCamera.prototype.serialize = function () {
  10979. var serializationObject = _super.prototype.serialize.call(this);
  10980. serializationObject.radius = this.radius;
  10981. serializationObject.heightOffset = this.heightOffset;
  10982. serializationObject.rotationOffset = this.rotationOffset;
  10983. return serializationObject;
  10984. };
  10985. return FollowCamera;
  10986. })(BABYLON.TargetCamera);
  10987. BABYLON.FollowCamera = FollowCamera;
  10988. var ArcFollowCamera = (function (_super) {
  10989. __extends(ArcFollowCamera, _super);
  10990. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10991. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10992. this.alpha = alpha;
  10993. this.beta = beta;
  10994. this.radius = radius;
  10995. this.target = target;
  10996. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10997. this.follow();
  10998. }
  10999. ArcFollowCamera.prototype.follow = function () {
  11000. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11001. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11002. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11003. this.position = this.target.position.add(this._cartesianCoordinates);
  11004. this.setTarget(this.target.position);
  11005. };
  11006. ArcFollowCamera.prototype._checkInputs = function () {
  11007. _super.prototype._checkInputs.call(this);
  11008. this.follow();
  11009. };
  11010. ArcFollowCamera.prototype.serialize = function () {
  11011. var serializationObject = _super.prototype.serialize.call(this);
  11012. serializationObject.radius = this.radius;
  11013. return serializationObject;
  11014. };
  11015. return ArcFollowCamera;
  11016. })(BABYLON.TargetCamera);
  11017. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11018. })(BABYLON || (BABYLON = {}));
  11019. var BABYLON;
  11020. (function (BABYLON) {
  11021. // We're mainly based on the logic defined into the FreeCamera code
  11022. var TouchCamera = (function (_super) {
  11023. __extends(TouchCamera, _super);
  11024. function TouchCamera(name, position, scene) {
  11025. _super.call(this, name, position, scene);
  11026. this._offsetX = null;
  11027. this._offsetY = null;
  11028. this._pointerCount = 0;
  11029. this._pointerPressed = [];
  11030. this.angularSensibility = 200000.0;
  11031. this.moveSensibility = 500.0;
  11032. }
  11033. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11034. var _this = this;
  11035. var previousPosition;
  11036. if (this._attachedCanvas) {
  11037. return;
  11038. }
  11039. this._attachedCanvas = canvas;
  11040. if (this._onPointerDown === undefined) {
  11041. this._onPointerDown = function (evt) {
  11042. if (!noPreventDefault) {
  11043. evt.preventDefault();
  11044. }
  11045. _this._pointerPressed.push(evt.pointerId);
  11046. if (_this._pointerPressed.length !== 1) {
  11047. return;
  11048. }
  11049. previousPosition = {
  11050. x: evt.clientX,
  11051. y: evt.clientY
  11052. };
  11053. };
  11054. this._onPointerUp = function (evt) {
  11055. if (!noPreventDefault) {
  11056. evt.preventDefault();
  11057. }
  11058. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11059. if (index === -1) {
  11060. return;
  11061. }
  11062. _this._pointerPressed.splice(index, 1);
  11063. if (index != 0) {
  11064. return;
  11065. }
  11066. previousPosition = null;
  11067. _this._offsetX = null;
  11068. _this._offsetY = null;
  11069. };
  11070. this._onPointerMove = function (evt) {
  11071. if (!noPreventDefault) {
  11072. evt.preventDefault();
  11073. }
  11074. if (!previousPosition) {
  11075. return;
  11076. }
  11077. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11078. if (index != 0) {
  11079. return;
  11080. }
  11081. _this._offsetX = evt.clientX - previousPosition.x;
  11082. _this._offsetY = -(evt.clientY - previousPosition.y);
  11083. };
  11084. this._onLostFocus = function () {
  11085. _this._offsetX = null;
  11086. _this._offsetY = null;
  11087. };
  11088. }
  11089. canvas.addEventListener("pointerdown", this._onPointerDown);
  11090. canvas.addEventListener("pointerup", this._onPointerUp);
  11091. canvas.addEventListener("pointerout", this._onPointerUp);
  11092. canvas.addEventListener("pointermove", this._onPointerMove);
  11093. BABYLON.Tools.RegisterTopRootEvents([
  11094. { name: "blur", handler: this._onLostFocus }
  11095. ]);
  11096. };
  11097. TouchCamera.prototype.detachControl = function (canvas) {
  11098. if (this._attachedCanvas !== canvas) {
  11099. return;
  11100. }
  11101. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11102. canvas.removeEventListener("pointerup", this._onPointerUp);
  11103. canvas.removeEventListener("pointerout", this._onPointerUp);
  11104. canvas.removeEventListener("pointermove", this._onPointerMove);
  11105. BABYLON.Tools.UnregisterTopRootEvents([
  11106. { name: "blur", handler: this._onLostFocus }
  11107. ]);
  11108. this._attachedCanvas = null;
  11109. };
  11110. TouchCamera.prototype._checkInputs = function () {
  11111. if (this._offsetX) {
  11112. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11113. if (this._pointerPressed.length > 1) {
  11114. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11115. }
  11116. else {
  11117. var speed = this._computeLocalCameraSpeed();
  11118. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11119. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11120. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11121. }
  11122. }
  11123. _super.prototype._checkInputs.call(this);
  11124. };
  11125. return TouchCamera;
  11126. })(BABYLON.FreeCamera);
  11127. BABYLON.TouchCamera = TouchCamera;
  11128. })(BABYLON || (BABYLON = {}));
  11129. var BABYLON;
  11130. (function (BABYLON) {
  11131. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11132. var ArcRotateCamera = (function (_super) {
  11133. __extends(ArcRotateCamera, _super);
  11134. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11135. var _this = this;
  11136. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11137. this.alpha = alpha;
  11138. this.beta = beta;
  11139. this.radius = radius;
  11140. this.target = target;
  11141. this.inertialAlphaOffset = 0;
  11142. this.inertialBetaOffset = 0;
  11143. this.inertialRadiusOffset = 0;
  11144. this.lowerAlphaLimit = null;
  11145. this.upperAlphaLimit = null;
  11146. this.lowerBetaLimit = 0.01;
  11147. this.upperBetaLimit = Math.PI;
  11148. this.lowerRadiusLimit = null;
  11149. this.upperRadiusLimit = null;
  11150. this.angularSensibilityX = 1000.0;
  11151. this.angularSensibilityY = 1000.0;
  11152. this.wheelPrecision = 3.0;
  11153. this.pinchPrecision = 2.0;
  11154. this.panningSensibility = 50.0;
  11155. this.inertialPanningX = 0;
  11156. this.inertialPanningY = 0;
  11157. this.keysUp = [38];
  11158. this.keysDown = [40];
  11159. this.keysLeft = [37];
  11160. this.keysRight = [39];
  11161. this.zoomOnFactor = 1;
  11162. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11163. this.pinchInwards = true;
  11164. this.allowUpsideDown = true;
  11165. this._keys = [];
  11166. this._viewMatrix = new BABYLON.Matrix();
  11167. this._isRightClick = false;
  11168. this._isCtrlPushed = false;
  11169. this.checkCollisions = false;
  11170. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11171. this._collider = new BABYLON.Collider();
  11172. this._previousPosition = BABYLON.Vector3.Zero();
  11173. this._collisionVelocity = BABYLON.Vector3.Zero();
  11174. this._newPosition = BABYLON.Vector3.Zero();
  11175. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11176. if (collidedMesh === void 0) { collidedMesh = null; }
  11177. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11178. newPosition.multiplyInPlace(_this._collider.radius);
  11179. }
  11180. if (!collidedMesh) {
  11181. _this._previousPosition.copyFrom(_this.position);
  11182. }
  11183. else {
  11184. _this.setPosition(newPosition);
  11185. if (_this.onCollide) {
  11186. _this.onCollide(collidedMesh);
  11187. }
  11188. }
  11189. // Recompute because of constraints
  11190. var cosa = Math.cos(_this.alpha);
  11191. var sina = Math.sin(_this.alpha);
  11192. var cosb = Math.cos(_this.beta);
  11193. var sinb = Math.sin(_this.beta);
  11194. var target = _this._getTargetPosition();
  11195. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11196. _this.position.copyFrom(_this._newPosition);
  11197. var up = _this.upVector;
  11198. if (_this.allowUpsideDown && _this.beta < 0) {
  11199. up = up.clone();
  11200. up = up.negate();
  11201. }
  11202. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11203. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11204. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11205. _this._collisionTriggered = false;
  11206. };
  11207. if (!this.target) {
  11208. this.target = BABYLON.Vector3.Zero();
  11209. }
  11210. this.getViewMatrix();
  11211. }
  11212. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11213. //deprecated angularSensibility support
  11214. get: function () {
  11215. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11216. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11217. },
  11218. //deprecated angularSensibility support
  11219. set: function (value) {
  11220. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11221. this.angularSensibilityX = value;
  11222. this.angularSensibilityY = value;
  11223. },
  11224. enumerable: true,
  11225. configurable: true
  11226. });
  11227. ArcRotateCamera.prototype._getTargetPosition = function () {
  11228. return this.target.position || this.target;
  11229. };
  11230. // Cache
  11231. ArcRotateCamera.prototype._initCache = function () {
  11232. _super.prototype._initCache.call(this);
  11233. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11234. this._cache.alpha = undefined;
  11235. this._cache.beta = undefined;
  11236. this._cache.radius = undefined;
  11237. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11238. };
  11239. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11240. if (!ignoreParentClass) {
  11241. _super.prototype._updateCache.call(this);
  11242. }
  11243. this._cache.target.copyFrom(this._getTargetPosition());
  11244. this._cache.alpha = this.alpha;
  11245. this._cache.beta = this.beta;
  11246. this._cache.radius = this.radius;
  11247. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11248. };
  11249. // Synchronized
  11250. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11251. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11252. return false;
  11253. return this._cache.target.equals(this._getTargetPosition())
  11254. && this._cache.alpha === this.alpha
  11255. && this._cache.beta === this.beta
  11256. && this._cache.radius === this.radius
  11257. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11258. };
  11259. // Methods
  11260. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11261. var _this = this;
  11262. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11263. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11264. var previousPinchDistance = 0;
  11265. var pointers = new BABYLON.SmartCollection();
  11266. if (this._attachedElement) {
  11267. return;
  11268. }
  11269. this._attachedElement = element;
  11270. var engine = this.getEngine();
  11271. if (this._onPointerDown === undefined) {
  11272. this._onPointerDown = function (evt) {
  11273. // Manage panning with right click
  11274. _this._isRightClick = evt.button === 2;
  11275. // manage pointers
  11276. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11277. cacheSoloPointer = pointers.item(evt.pointerId);
  11278. if (!noPreventDefault) {
  11279. evt.preventDefault();
  11280. }
  11281. };
  11282. this._onPointerUp = function (evt) {
  11283. cacheSoloPointer = null;
  11284. previousPinchDistance = 0;
  11285. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11286. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11287. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11288. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11289. pointers.empty();
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onContextMenu = function (evt) {
  11295. evt.preventDefault();
  11296. };
  11297. this._onPointerMove = function (evt) {
  11298. if (!noPreventDefault) {
  11299. evt.preventDefault();
  11300. }
  11301. switch (pointers.count) {
  11302. case 1:
  11303. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11304. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11305. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11306. }
  11307. else {
  11308. var offsetX = evt.clientX - cacheSoloPointer.x;
  11309. var offsetY = evt.clientY - cacheSoloPointer.y;
  11310. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11311. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11312. }
  11313. cacheSoloPointer.x = evt.clientX;
  11314. cacheSoloPointer.y = evt.clientY;
  11315. break;
  11316. case 2:
  11317. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11318. pointers.item(evt.pointerId).x = evt.clientX;
  11319. pointers.item(evt.pointerId).y = evt.clientY;
  11320. var direction = _this.pinchInwards ? 1 : -1;
  11321. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11322. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11323. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11324. if (previousPinchDistance === 0) {
  11325. previousPinchDistance = pinchSquaredDistance;
  11326. return;
  11327. }
  11328. if (pinchSquaredDistance !== previousPinchDistance) {
  11329. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11330. previousPinchDistance = pinchSquaredDistance;
  11331. }
  11332. break;
  11333. default:
  11334. if (pointers.item(evt.pointerId)) {
  11335. pointers.item(evt.pointerId).x = evt.clientX;
  11336. pointers.item(evt.pointerId).y = evt.clientY;
  11337. }
  11338. }
  11339. };
  11340. this._onMouseMove = function (evt) {
  11341. if (!engine.isPointerLock) {
  11342. return;
  11343. }
  11344. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11345. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11346. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11347. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11348. if (!noPreventDefault) {
  11349. evt.preventDefault();
  11350. }
  11351. };
  11352. this._wheel = function (event) {
  11353. var delta = 0;
  11354. if (event.wheelDelta) {
  11355. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11356. }
  11357. else if (event.detail) {
  11358. delta = -event.detail / _this.wheelPrecision;
  11359. }
  11360. if (delta)
  11361. _this.inertialRadiusOffset += delta;
  11362. if (event.preventDefault) {
  11363. if (!noPreventDefault) {
  11364. event.preventDefault();
  11365. }
  11366. }
  11367. };
  11368. this._onKeyDown = function (evt) {
  11369. _this._isCtrlPushed = evt.ctrlKey;
  11370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11373. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11374. var index = _this._keys.indexOf(evt.keyCode);
  11375. if (index === -1) {
  11376. _this._keys.push(evt.keyCode);
  11377. }
  11378. if (evt.preventDefault) {
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. }
  11383. }
  11384. };
  11385. this._onKeyUp = function (evt) {
  11386. _this._isCtrlPushed = evt.ctrlKey;
  11387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11390. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11391. var index = _this._keys.indexOf(evt.keyCode);
  11392. if (index >= 0) {
  11393. _this._keys.splice(index, 1);
  11394. }
  11395. if (evt.preventDefault) {
  11396. if (!noPreventDefault) {
  11397. evt.preventDefault();
  11398. }
  11399. }
  11400. }
  11401. };
  11402. this._onLostFocus = function () {
  11403. _this._keys = [];
  11404. pointers.empty();
  11405. previousPinchDistance = 0;
  11406. cacheSoloPointer = null;
  11407. };
  11408. this._onGestureStart = function (e) {
  11409. if (window.MSGesture === undefined) {
  11410. return;
  11411. }
  11412. if (!_this._MSGestureHandler) {
  11413. _this._MSGestureHandler = new MSGesture();
  11414. _this._MSGestureHandler.target = element;
  11415. }
  11416. _this._MSGestureHandler.addPointer(e.pointerId);
  11417. };
  11418. this._onGesture = function (e) {
  11419. _this.radius *= e.scale;
  11420. if (e.preventDefault) {
  11421. if (!noPreventDefault) {
  11422. e.stopPropagation();
  11423. e.preventDefault();
  11424. }
  11425. }
  11426. };
  11427. this._reset = function () {
  11428. _this._keys = [];
  11429. _this.inertialAlphaOffset = 0;
  11430. _this.inertialBetaOffset = 0;
  11431. _this.inertialRadiusOffset = 0;
  11432. pointers.empty();
  11433. previousPinchDistance = 0;
  11434. cacheSoloPointer = null;
  11435. };
  11436. }
  11437. if (!useCtrlForPanning) {
  11438. element.addEventListener("contextmenu", this._onContextMenu, false);
  11439. }
  11440. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11441. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11442. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11443. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11444. element.addEventListener("mousemove", this._onMouseMove, false);
  11445. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11446. element.addEventListener("MSGestureChange", this._onGesture, false);
  11447. element.addEventListener('mousewheel', this._wheel, false);
  11448. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11449. BABYLON.Tools.RegisterTopRootEvents([
  11450. { name: "keydown", handler: this._onKeyDown },
  11451. { name: "keyup", handler: this._onKeyUp },
  11452. { name: "blur", handler: this._onLostFocus }
  11453. ]);
  11454. };
  11455. ArcRotateCamera.prototype.detachControl = function (element) {
  11456. if (this._attachedElement !== element) {
  11457. return;
  11458. }
  11459. element.removeEventListener("contextmenu", this._onContextMenu);
  11460. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11461. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11462. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11463. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11464. element.removeEventListener("mousemove", this._onMouseMove);
  11465. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11466. element.removeEventListener("MSGestureChange", this._onGesture);
  11467. element.removeEventListener('mousewheel', this._wheel);
  11468. element.removeEventListener('DOMMouseScroll', this._wheel);
  11469. BABYLON.Tools.UnregisterTopRootEvents([
  11470. { name: "keydown", handler: this._onKeyDown },
  11471. { name: "keyup", handler: this._onKeyUp },
  11472. { name: "blur", handler: this._onLostFocus }
  11473. ]);
  11474. this._MSGestureHandler = null;
  11475. this._attachedElement = null;
  11476. if (this._reset) {
  11477. this._reset();
  11478. }
  11479. };
  11480. ArcRotateCamera.prototype._checkInputs = function () {
  11481. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11482. if (this._collisionTriggered) {
  11483. return;
  11484. }
  11485. // Keyboard
  11486. for (var index = 0; index < this._keys.length; index++) {
  11487. var keyCode = this._keys[index];
  11488. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11489. this.inertialAlphaOffset -= 0.01;
  11490. }
  11491. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11492. this.inertialBetaOffset -= 0.01;
  11493. }
  11494. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11495. this.inertialAlphaOffset += 0.01;
  11496. }
  11497. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11498. this.inertialBetaOffset += 0.01;
  11499. }
  11500. }
  11501. // Inertia
  11502. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11503. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11504. this.beta += this.inertialBetaOffset;
  11505. this.radius -= this.inertialRadiusOffset;
  11506. this.inertialAlphaOffset *= this.inertia;
  11507. this.inertialBetaOffset *= this.inertia;
  11508. this.inertialRadiusOffset *= this.inertia;
  11509. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11510. this.inertialAlphaOffset = 0;
  11511. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11512. this.inertialBetaOffset = 0;
  11513. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11514. this.inertialRadiusOffset = 0;
  11515. }
  11516. // Panning inertia
  11517. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11518. if (!this._localDirection) {
  11519. this._localDirection = BABYLON.Vector3.Zero();
  11520. this._transformedDirection = BABYLON.Vector3.Zero();
  11521. }
  11522. this.inertialPanningX *= this.inertia;
  11523. this.inertialPanningY *= this.inertia;
  11524. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11525. this.inertialPanningX = 0;
  11526. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11527. this.inertialPanningY = 0;
  11528. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11529. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11530. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11531. this.target.addInPlace(this._transformedDirection);
  11532. }
  11533. // Limits
  11534. this._checkLimits();
  11535. _super.prototype._checkInputs.call(this);
  11536. };
  11537. ArcRotateCamera.prototype._checkLimits = function () {
  11538. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11539. if (this.allowUpsideDown && this.beta > Math.PI) {
  11540. this.beta = this.beta - (2 * Math.PI);
  11541. }
  11542. }
  11543. else {
  11544. if (this.beta < this.lowerBetaLimit) {
  11545. this.beta = this.lowerBetaLimit;
  11546. }
  11547. }
  11548. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11549. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11550. this.beta = this.beta + (2 * Math.PI);
  11551. }
  11552. }
  11553. else {
  11554. if (this.beta > this.upperBetaLimit) {
  11555. this.beta = this.upperBetaLimit;
  11556. }
  11557. }
  11558. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11559. this.alpha = this.lowerAlphaLimit;
  11560. }
  11561. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11562. this.alpha = this.upperAlphaLimit;
  11563. }
  11564. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11565. this.radius = this.lowerRadiusLimit;
  11566. }
  11567. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11568. this.radius = this.upperRadiusLimit;
  11569. }
  11570. };
  11571. ArcRotateCamera.prototype.setPosition = function (position) {
  11572. if (this.position.equals(position)) {
  11573. return;
  11574. }
  11575. var radiusv3 = position.subtract(this._getTargetPosition());
  11576. this.radius = radiusv3.length();
  11577. // Alpha
  11578. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11579. if (radiusv3.z < 0) {
  11580. this.alpha = 2 * Math.PI - this.alpha;
  11581. }
  11582. // Beta
  11583. this.beta = Math.acos(radiusv3.y / this.radius);
  11584. this._checkLimits();
  11585. };
  11586. ArcRotateCamera.prototype.setTarget = function (target) {
  11587. this.target = target;
  11588. };
  11589. ArcRotateCamera.prototype._getViewMatrix = function () {
  11590. // Compute
  11591. var cosa = Math.cos(this.alpha);
  11592. var sina = Math.sin(this.alpha);
  11593. var cosb = Math.cos(this.beta);
  11594. var sinb = Math.sin(this.beta);
  11595. var target = this._getTargetPosition();
  11596. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11597. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11598. this._collider.radius = this.collisionRadius;
  11599. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11600. this._collisionTriggered = true;
  11601. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11602. }
  11603. else {
  11604. this.position.copyFrom(this._newPosition);
  11605. var up = this.upVector;
  11606. if (this.allowUpsideDown && this.beta < 0) {
  11607. up = up.clone();
  11608. up = up.negate();
  11609. }
  11610. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11611. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11612. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11613. }
  11614. return this._viewMatrix;
  11615. };
  11616. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11617. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11618. meshes = meshes || this.getScene().meshes;
  11619. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11620. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11621. this.radius = distance * this.zoomOnFactor;
  11622. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11623. };
  11624. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11625. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11626. var meshesOrMinMaxVector;
  11627. var distance;
  11628. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11629. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11630. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11631. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11632. }
  11633. else {
  11634. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11635. distance = meshesOrMinMaxVectorAndDistance.distance;
  11636. }
  11637. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11638. if (!doNotUpdateMaxZ) {
  11639. this.maxZ = distance * 2;
  11640. }
  11641. };
  11642. /**
  11643. * @override
  11644. * Override Camera.createRigCamera
  11645. */
  11646. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11647. switch (this.cameraRigMode) {
  11648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11652. case BABYLON.Camera.RIG_MODE_VR:
  11653. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11654. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11655. }
  11656. return null;
  11657. };
  11658. /**
  11659. * @override
  11660. * Override Camera._updateRigCameras
  11661. */
  11662. ArcRotateCamera.prototype._updateRigCameras = function () {
  11663. switch (this.cameraRigMode) {
  11664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11668. case BABYLON.Camera.RIG_MODE_VR:
  11669. var camLeft = this._rigCameras[0];
  11670. var camRight = this._rigCameras[1];
  11671. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11672. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11673. camLeft.beta = camRight.beta = this.beta;
  11674. camLeft.radius = camRight.radius = this.radius;
  11675. break;
  11676. }
  11677. _super.prototype._updateRigCameras.call(this);
  11678. };
  11679. ArcRotateCamera.prototype.serialize = function () {
  11680. var serializationObject = _super.prototype.serialize.call(this);
  11681. if (this.target instanceof BABYLON.Vector3) {
  11682. serializationObject.target = this.target.asArray();
  11683. }
  11684. if (this.target && this.target.id) {
  11685. serializationObject.lockedTargetId = this.target.id;
  11686. }
  11687. serializationObject.checkCollisions = this.checkCollisions;
  11688. serializationObject.alpha = this.alpha;
  11689. serializationObject.beta = this.beta;
  11690. serializationObject.radius = this.radius;
  11691. return serializationObject;
  11692. };
  11693. return ArcRotateCamera;
  11694. })(BABYLON.TargetCamera);
  11695. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11696. })(BABYLON || (BABYLON = {}));
  11697. var BABYLON;
  11698. (function (BABYLON) {
  11699. var RenderingManager = (function () {
  11700. function RenderingManager(scene) {
  11701. this._renderingGroups = new Array();
  11702. this._scene = scene;
  11703. }
  11704. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11705. if (this._scene._activeParticleSystems.length === 0) {
  11706. return;
  11707. }
  11708. // Particles
  11709. var activeCamera = this._scene.activeCamera;
  11710. var beforeParticlesDate = BABYLON.Tools.Now;
  11711. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11712. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11713. if (particleSystem.renderingGroupId !== index) {
  11714. continue;
  11715. }
  11716. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11717. continue;
  11718. }
  11719. this._clearDepthBuffer();
  11720. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11721. this._scene._activeParticles += particleSystem.render();
  11722. }
  11723. }
  11724. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11725. };
  11726. RenderingManager.prototype._renderSprites = function (index) {
  11727. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11728. return;
  11729. }
  11730. // Sprites
  11731. var activeCamera = this._scene.activeCamera;
  11732. var beforeSpritessDate = BABYLON.Tools.Now;
  11733. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11734. var spriteManager = this._scene.spriteManagers[id];
  11735. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11736. this._clearDepthBuffer();
  11737. spriteManager.render();
  11738. }
  11739. }
  11740. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11741. };
  11742. RenderingManager.prototype._clearDepthBuffer = function () {
  11743. if (this._depthBufferAlreadyCleaned) {
  11744. return;
  11745. }
  11746. this._scene.getEngine().clear(0, false, true);
  11747. this._depthBufferAlreadyCleaned = true;
  11748. };
  11749. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11750. if (this._currentRenderSprites) {
  11751. this._renderSprites(this._currentIndex);
  11752. }
  11753. if (this._currentRenderParticles) {
  11754. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11755. }
  11756. };
  11757. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11758. this._currentActiveMeshes = activeMeshes;
  11759. this._currentRenderParticles = renderParticles;
  11760. this._currentRenderSprites = renderSprites;
  11761. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11762. this._depthBufferAlreadyCleaned = false;
  11763. var renderingGroup = this._renderingGroups[index];
  11764. var needToStepBack = false;
  11765. this._currentIndex = index;
  11766. if (renderingGroup) {
  11767. this._clearDepthBuffer();
  11768. if (!renderingGroup.onBeforeTransparentRendering) {
  11769. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11770. }
  11771. if (!renderingGroup.render(customRenderFunction)) {
  11772. this._renderingGroups.splice(index, 1);
  11773. needToStepBack = true;
  11774. this._renderSpritesAndParticles();
  11775. }
  11776. }
  11777. else {
  11778. this._renderSpritesAndParticles();
  11779. }
  11780. if (needToStepBack) {
  11781. index--;
  11782. }
  11783. }
  11784. };
  11785. RenderingManager.prototype.reset = function () {
  11786. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11787. if (renderingGroup) {
  11788. renderingGroup.prepare();
  11789. }
  11790. });
  11791. };
  11792. RenderingManager.prototype.dispatch = function (subMesh) {
  11793. var mesh = subMesh.getMesh();
  11794. var renderingGroupId = mesh.renderingGroupId || 0;
  11795. if (!this._renderingGroups[renderingGroupId]) {
  11796. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11797. }
  11798. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11799. };
  11800. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11801. return RenderingManager;
  11802. })();
  11803. BABYLON.RenderingManager = RenderingManager;
  11804. })(BABYLON || (BABYLON = {}));
  11805. var BABYLON;
  11806. (function (BABYLON) {
  11807. var RenderingGroup = (function () {
  11808. function RenderingGroup(index, scene) {
  11809. this.index = index;
  11810. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11811. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11812. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11813. this._scene = scene;
  11814. }
  11815. RenderingGroup.prototype.render = function (customRenderFunction) {
  11816. if (customRenderFunction) {
  11817. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11818. return true;
  11819. }
  11820. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11821. if (this.onBeforeTransparentRendering) {
  11822. this.onBeforeTransparentRendering();
  11823. }
  11824. return false;
  11825. }
  11826. var engine = this._scene.getEngine();
  11827. // Opaque
  11828. var subIndex;
  11829. var submesh;
  11830. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11831. submesh = this._opaqueSubMeshes.data[subIndex];
  11832. submesh.render(false);
  11833. }
  11834. // Alpha test
  11835. engine.setAlphaTesting(true);
  11836. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11837. submesh = this._alphaTestSubMeshes.data[subIndex];
  11838. submesh.render(false);
  11839. }
  11840. engine.setAlphaTesting(false);
  11841. if (this.onBeforeTransparentRendering) {
  11842. this.onBeforeTransparentRendering();
  11843. }
  11844. // Transparent
  11845. if (this._transparentSubMeshes.length) {
  11846. // Sorting
  11847. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11848. submesh = this._transparentSubMeshes.data[subIndex];
  11849. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11850. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11851. }
  11852. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11853. sortedArray.sort(function (a, b) {
  11854. // Alpha index first
  11855. if (a._alphaIndex > b._alphaIndex) {
  11856. return 1;
  11857. }
  11858. if (a._alphaIndex < b._alphaIndex) {
  11859. return -1;
  11860. }
  11861. // Then distance to camera
  11862. if (a._distanceToCamera < b._distanceToCamera) {
  11863. return 1;
  11864. }
  11865. if (a._distanceToCamera > b._distanceToCamera) {
  11866. return -1;
  11867. }
  11868. return 0;
  11869. });
  11870. // Rendering
  11871. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11872. submesh = sortedArray[subIndex];
  11873. submesh.render(true);
  11874. }
  11875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11876. }
  11877. return true;
  11878. };
  11879. RenderingGroup.prototype.prepare = function () {
  11880. this._opaqueSubMeshes.reset();
  11881. this._transparentSubMeshes.reset();
  11882. this._alphaTestSubMeshes.reset();
  11883. };
  11884. RenderingGroup.prototype.dispatch = function (subMesh) {
  11885. var material = subMesh.getMaterial();
  11886. var mesh = subMesh.getMesh();
  11887. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11888. this._transparentSubMeshes.push(subMesh);
  11889. }
  11890. else if (material.needAlphaTesting()) {
  11891. this._alphaTestSubMeshes.push(subMesh);
  11892. }
  11893. else {
  11894. this._opaqueSubMeshes.push(subMesh); // Opaque
  11895. }
  11896. };
  11897. return RenderingGroup;
  11898. })();
  11899. BABYLON.RenderingGroup = RenderingGroup;
  11900. })(BABYLON || (BABYLON = {}));
  11901. var BABYLON;
  11902. (function (BABYLON) {
  11903. /**
  11904. * Represents a scene to be rendered by the engine.
  11905. * @see http://doc.babylonjs.com/page.php?p=21911
  11906. */
  11907. var Scene = (function () {
  11908. /**
  11909. * @constructor
  11910. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11911. */
  11912. function Scene(engine) {
  11913. // Members
  11914. this.autoClear = true;
  11915. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11916. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11917. this.forceWireframe = false;
  11918. this.forcePointsCloud = false;
  11919. this.forceShowBoundingBoxes = false;
  11920. this.animationsEnabled = true;
  11921. this.constantlyUpdateMeshUnderPointer = false;
  11922. 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
  11923. // Fog
  11924. /**
  11925. * is fog enabled on this scene.
  11926. * @type {boolean}
  11927. */
  11928. this.fogEnabled = true;
  11929. this.fogMode = Scene.FOGMODE_NONE;
  11930. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11931. this.fogDensity = 0.1;
  11932. this.fogStart = 0;
  11933. this.fogEnd = 1000.0;
  11934. // Lights
  11935. /**
  11936. * is shadow enabled on this scene.
  11937. * @type {boolean}
  11938. */
  11939. this.shadowsEnabled = true;
  11940. /**
  11941. * is light enabled on this scene.
  11942. * @type {boolean}
  11943. */
  11944. this.lightsEnabled = true;
  11945. /**
  11946. * All of the lights added to this scene.
  11947. * @see BABYLON.Light
  11948. * @type {BABYLON.Light[]}
  11949. */
  11950. this.lights = new Array();
  11951. // Cameras
  11952. /**
  11953. * All of the cameras added to this scene.
  11954. * @see BABYLON.Camera
  11955. * @type {BABYLON.Camera[]}
  11956. */
  11957. this.cameras = new Array();
  11958. this.activeCameras = new Array();
  11959. // Meshes
  11960. /**
  11961. * All of the (abstract) meshes added to this scene.
  11962. * @see BABYLON.AbstractMesh
  11963. * @type {BABYLON.AbstractMesh[]}
  11964. */
  11965. this.meshes = new Array();
  11966. // Geometries
  11967. this._geometries = new Array();
  11968. this.materials = new Array();
  11969. this.multiMaterials = new Array();
  11970. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11971. // Textures
  11972. this.texturesEnabled = true;
  11973. this.textures = new Array();
  11974. // Particles
  11975. this.particlesEnabled = true;
  11976. this.particleSystems = new Array();
  11977. // Sprites
  11978. this.spritesEnabled = true;
  11979. this.spriteManagers = new Array();
  11980. // Layers
  11981. this.layers = new Array();
  11982. // Skeletons
  11983. this.skeletonsEnabled = true;
  11984. this.skeletons = new Array();
  11985. // Lens flares
  11986. this.lensFlaresEnabled = true;
  11987. this.lensFlareSystems = new Array();
  11988. // Collisions
  11989. this.collisionsEnabled = true;
  11990. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11991. // Postprocesses
  11992. this.postProcessesEnabled = true;
  11993. // Customs render targets
  11994. this.renderTargetsEnabled = true;
  11995. this.dumpNextRenderTargets = false;
  11996. this.customRenderTargets = new Array();
  11997. // Imported meshes
  11998. this.importedMeshesFiles = new Array();
  11999. // Probes
  12000. this.probesEnabled = true;
  12001. this.reflectionProbes = new Array();
  12002. this._actionManagers = new Array();
  12003. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12004. // Procedural textures
  12005. this.proceduralTexturesEnabled = true;
  12006. this._proceduralTextures = new Array();
  12007. this.soundTracks = new Array();
  12008. this._audioEnabled = true;
  12009. this._headphone = false;
  12010. this._totalVertices = 0;
  12011. this._activeIndices = 0;
  12012. this._activeParticles = 0;
  12013. this._lastFrameDuration = 0;
  12014. this._evaluateActiveMeshesDuration = 0;
  12015. this._renderTargetsDuration = 0;
  12016. this._particlesDuration = 0;
  12017. this._renderDuration = 0;
  12018. this._spritesDuration = 0;
  12019. this._animationRatio = 0;
  12020. this._renderId = 0;
  12021. this._executeWhenReadyTimeoutId = -1;
  12022. this._toBeDisposed = new BABYLON.SmartArray(256);
  12023. this._onReadyCallbacks = new Array();
  12024. this._pendingData = []; //ANY
  12025. this._onBeforeRenderCallbacks = new Array();
  12026. this._onAfterRenderCallbacks = new Array();
  12027. this._activeMeshes = new BABYLON.SmartArray(256);
  12028. this._processedMaterials = new BABYLON.SmartArray(256);
  12029. this._renderTargets = new BABYLON.SmartArray(256);
  12030. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12031. this._activeSkeletons = new BABYLON.SmartArray(32);
  12032. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12033. this._activeBones = 0;
  12034. this._activeAnimatables = new Array();
  12035. this._transformMatrix = BABYLON.Matrix.Zero();
  12036. this._edgesRenderers = new BABYLON.SmartArray(16);
  12037. this._uniqueIdCounter = 0;
  12038. this._engine = engine;
  12039. engine.scenes.push(this);
  12040. this._renderingManager = new BABYLON.RenderingManager(this);
  12041. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12042. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12043. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12044. if (BABYLON.OutlineRenderer) {
  12045. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12046. }
  12047. this.attachControl();
  12048. this._debugLayer = new BABYLON.DebugLayer(this);
  12049. if (BABYLON.SoundTrack) {
  12050. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12051. }
  12052. //simplification queue
  12053. if (BABYLON.SimplificationQueue) {
  12054. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12055. }
  12056. //collision coordinator initialization. For now legacy per default.
  12057. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12058. }
  12059. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12060. get: function () {
  12061. return Scene._FOGMODE_NONE;
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12067. get: function () {
  12068. return Scene._FOGMODE_EXP;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12074. get: function () {
  12075. return Scene._FOGMODE_EXP2;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12081. get: function () {
  12082. return Scene._FOGMODE_LINEAR;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(Scene.prototype, "debugLayer", {
  12088. // Properties
  12089. get: function () {
  12090. return this._debugLayer;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12096. get: function () {
  12097. return this._workerCollisions;
  12098. },
  12099. set: function (enabled) {
  12100. enabled = (enabled && !!Worker);
  12101. this._workerCollisions = enabled;
  12102. if (this.collisionCoordinator) {
  12103. this.collisionCoordinator.destroy();
  12104. }
  12105. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12106. this.collisionCoordinator.init(this);
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12112. get: function () {
  12113. return this._selectionOctree;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12119. /**
  12120. * The mesh that is currently under the pointer.
  12121. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12122. */
  12123. get: function () {
  12124. return this._meshUnderPointer;
  12125. },
  12126. enumerable: true,
  12127. configurable: true
  12128. });
  12129. Object.defineProperty(Scene.prototype, "pointerX", {
  12130. /**
  12131. * Current on-screen X position of the pointer
  12132. * @return {number} X position of the pointer
  12133. */
  12134. get: function () {
  12135. return this._pointerX;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Scene.prototype, "pointerY", {
  12141. /**
  12142. * Current on-screen Y position of the pointer
  12143. * @return {number} Y position of the pointer
  12144. */
  12145. get: function () {
  12146. return this._pointerY;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Scene.prototype.getCachedMaterial = function () {
  12152. return this._cachedMaterial;
  12153. };
  12154. Scene.prototype.getBoundingBoxRenderer = function () {
  12155. return this._boundingBoxRenderer;
  12156. };
  12157. Scene.prototype.getOutlineRenderer = function () {
  12158. return this._outlineRenderer;
  12159. };
  12160. Scene.prototype.getEngine = function () {
  12161. return this._engine;
  12162. };
  12163. Scene.prototype.getTotalVertices = function () {
  12164. return this._totalVertices;
  12165. };
  12166. Scene.prototype.getActiveIndices = function () {
  12167. return this._activeIndices;
  12168. };
  12169. Scene.prototype.getActiveParticles = function () {
  12170. return this._activeParticles;
  12171. };
  12172. Scene.prototype.getActiveBones = function () {
  12173. return this._activeBones;
  12174. };
  12175. // Stats
  12176. Scene.prototype.getLastFrameDuration = function () {
  12177. return this._lastFrameDuration;
  12178. };
  12179. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12180. return this._evaluateActiveMeshesDuration;
  12181. };
  12182. Scene.prototype.getActiveMeshes = function () {
  12183. return this._activeMeshes;
  12184. };
  12185. Scene.prototype.getRenderTargetsDuration = function () {
  12186. return this._renderTargetsDuration;
  12187. };
  12188. Scene.prototype.getRenderDuration = function () {
  12189. return this._renderDuration;
  12190. };
  12191. Scene.prototype.getParticlesDuration = function () {
  12192. return this._particlesDuration;
  12193. };
  12194. Scene.prototype.getSpritesDuration = function () {
  12195. return this._spritesDuration;
  12196. };
  12197. Scene.prototype.getAnimationRatio = function () {
  12198. return this._animationRatio;
  12199. };
  12200. Scene.prototype.getRenderId = function () {
  12201. return this._renderId;
  12202. };
  12203. Scene.prototype.incrementRenderId = function () {
  12204. this._renderId++;
  12205. };
  12206. Scene.prototype._updatePointerPosition = function (evt) {
  12207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12208. this._pointerX = evt.clientX - canvasRect.left;
  12209. this._pointerY = evt.clientY - canvasRect.top;
  12210. if (this.cameraToUseForPointers) {
  12211. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12212. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12213. }
  12214. };
  12215. // Pointers handling
  12216. Scene.prototype.attachControl = function () {
  12217. var _this = this;
  12218. var spritePredicate = function (sprite) {
  12219. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12220. };
  12221. this._onPointerMove = function (evt) {
  12222. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12223. return;
  12224. }
  12225. var canvas = _this._engine.getRenderingCanvas();
  12226. _this._updatePointerPosition(evt);
  12227. // Meshes
  12228. 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);
  12229. if (pickResult.hit && pickResult.pickedMesh) {
  12230. _this._meshUnderPointer = pickResult.pickedMesh;
  12231. _this.setPointerOverMesh(pickResult.pickedMesh);
  12232. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12233. canvas.style.cursor = "pointer";
  12234. }
  12235. else {
  12236. canvas.style.cursor = "";
  12237. }
  12238. }
  12239. else {
  12240. // Sprites
  12241. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12242. if (pickResult.hit && pickResult.pickedSprite) {
  12243. canvas.style.cursor = "pointer";
  12244. }
  12245. else {
  12246. // Restore pointer
  12247. _this.setPointerOverMesh(null);
  12248. canvas.style.cursor = "";
  12249. _this._meshUnderPointer = null;
  12250. }
  12251. }
  12252. if (_this.onPointerMove) {
  12253. _this.onPointerMove(evt, pickResult);
  12254. }
  12255. };
  12256. this._onPointerDown = function (evt) {
  12257. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12258. return;
  12259. }
  12260. _this._updatePointerPosition(evt);
  12261. var predicate = null;
  12262. // Meshes
  12263. if (!_this.onPointerDown) {
  12264. predicate = function (mesh) {
  12265. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12266. };
  12267. }
  12268. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12269. if (pickResult.hit && pickResult.pickedMesh) {
  12270. if (pickResult.pickedMesh.actionManager) {
  12271. switch (evt.button) {
  12272. case 0:
  12273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12274. break;
  12275. case 1:
  12276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12277. break;
  12278. case 2:
  12279. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12280. break;
  12281. }
  12282. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12283. }
  12284. }
  12285. if (_this.onPointerDown) {
  12286. _this.onPointerDown(evt, pickResult);
  12287. }
  12288. // Sprites
  12289. if (_this.spriteManagers.length > 0) {
  12290. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12291. if (pickResult.hit && pickResult.pickedSprite) {
  12292. if (pickResult.pickedSprite.actionManager) {
  12293. switch (evt.button) {
  12294. case 0:
  12295. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12296. break;
  12297. case 1:
  12298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12299. break;
  12300. case 2:
  12301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12302. break;
  12303. }
  12304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12305. }
  12306. }
  12307. }
  12308. };
  12309. this._onPointerUp = function (evt) {
  12310. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12311. return;
  12312. }
  12313. var predicate = null;
  12314. _this._updatePointerPosition(evt);
  12315. if (!_this.onPointerUp) {
  12316. predicate = function (mesh) {
  12317. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12318. };
  12319. }
  12320. // Meshes
  12321. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12322. if (pickResult.hit && pickResult.pickedMesh) {
  12323. if (pickResult.pickedMesh.actionManager) {
  12324. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12325. }
  12326. }
  12327. if (_this.onPointerUp) {
  12328. _this.onPointerUp(evt, pickResult);
  12329. }
  12330. // Sprites
  12331. if (_this.spriteManagers.length > 0) {
  12332. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12333. if (pickResult.hit && pickResult.pickedSprite) {
  12334. if (pickResult.pickedSprite.actionManager) {
  12335. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12336. }
  12337. }
  12338. }
  12339. };
  12340. this._onKeyDown = function (evt) {
  12341. if (_this.actionManager) {
  12342. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12343. }
  12344. };
  12345. this._onKeyUp = function (evt) {
  12346. if (_this.actionManager) {
  12347. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12348. }
  12349. };
  12350. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12351. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12352. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12353. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12354. // Wheel
  12355. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12356. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12357. BABYLON.Tools.RegisterTopRootEvents([
  12358. { name: "keydown", handler: this._onKeyDown },
  12359. { name: "keyup", handler: this._onKeyUp }
  12360. ]);
  12361. };
  12362. Scene.prototype.detachControl = function () {
  12363. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12364. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12365. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12366. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12367. // Wheel
  12368. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12369. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12370. BABYLON.Tools.UnregisterTopRootEvents([
  12371. { name: "keydown", handler: this._onKeyDown },
  12372. { name: "keyup", handler: this._onKeyUp }
  12373. ]);
  12374. };
  12375. // Ready
  12376. Scene.prototype.isReady = function () {
  12377. if (this._pendingData.length > 0) {
  12378. return false;
  12379. }
  12380. var index;
  12381. for (index = 0; index < this._geometries.length; index++) {
  12382. var geometry = this._geometries[index];
  12383. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12384. return false;
  12385. }
  12386. }
  12387. for (index = 0; index < this.meshes.length; index++) {
  12388. var mesh = this.meshes[index];
  12389. if (!mesh.isReady()) {
  12390. return false;
  12391. }
  12392. var mat = mesh.material;
  12393. if (mat) {
  12394. if (!mat.isReady(mesh)) {
  12395. return false;
  12396. }
  12397. }
  12398. }
  12399. return true;
  12400. };
  12401. Scene.prototype.resetCachedMaterial = function () {
  12402. this._cachedMaterial = null;
  12403. };
  12404. Scene.prototype.registerBeforeRender = function (func) {
  12405. this._onBeforeRenderCallbacks.push(func);
  12406. };
  12407. Scene.prototype.unregisterBeforeRender = function (func) {
  12408. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12409. if (index > -1) {
  12410. this._onBeforeRenderCallbacks.splice(index, 1);
  12411. }
  12412. };
  12413. Scene.prototype.registerAfterRender = function (func) {
  12414. this._onAfterRenderCallbacks.push(func);
  12415. };
  12416. Scene.prototype.unregisterAfterRender = function (func) {
  12417. var index = this._onAfterRenderCallbacks.indexOf(func);
  12418. if (index > -1) {
  12419. this._onAfterRenderCallbacks.splice(index, 1);
  12420. }
  12421. };
  12422. Scene.prototype._addPendingData = function (data) {
  12423. this._pendingData.push(data);
  12424. };
  12425. Scene.prototype._removePendingData = function (data) {
  12426. var index = this._pendingData.indexOf(data);
  12427. if (index !== -1) {
  12428. this._pendingData.splice(index, 1);
  12429. }
  12430. };
  12431. Scene.prototype.getWaitingItemsCount = function () {
  12432. return this._pendingData.length;
  12433. };
  12434. /**
  12435. * Registers a function to be executed when the scene is ready.
  12436. * @param {Function} func - the function to be executed.
  12437. */
  12438. Scene.prototype.executeWhenReady = function (func) {
  12439. var _this = this;
  12440. this._onReadyCallbacks.push(func);
  12441. if (this._executeWhenReadyTimeoutId !== -1) {
  12442. return;
  12443. }
  12444. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12445. _this._checkIsReady();
  12446. }, 150);
  12447. };
  12448. Scene.prototype._checkIsReady = function () {
  12449. var _this = this;
  12450. if (this.isReady()) {
  12451. this._onReadyCallbacks.forEach(function (func) {
  12452. func();
  12453. });
  12454. this._onReadyCallbacks = [];
  12455. this._executeWhenReadyTimeoutId = -1;
  12456. return;
  12457. }
  12458. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12459. _this._checkIsReady();
  12460. }, 150);
  12461. };
  12462. // Animations
  12463. /**
  12464. * Will start the animation sequence of a given target
  12465. * @param target - the target
  12466. * @param {number} from - from which frame should animation start
  12467. * @param {number} to - till which frame should animation run.
  12468. * @param {boolean} [loop] - should the animation loop
  12469. * @param {number} [speedRatio] - the speed in which to run the animation
  12470. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12471. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12472. * @return {BABYLON.Animatable} the animatable object created for this animation
  12473. * @see BABYLON.Animatable
  12474. * @see http://doc.babylonjs.com/page.php?p=22081
  12475. */
  12476. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12477. if (speedRatio === void 0) { speedRatio = 1.0; }
  12478. this.stopAnimation(target);
  12479. if (!animatable) {
  12480. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12481. }
  12482. // Local animations
  12483. if (target.animations) {
  12484. animatable.appendAnimations(target, target.animations);
  12485. }
  12486. // Children animations
  12487. if (target.getAnimatables) {
  12488. var animatables = target.getAnimatables();
  12489. for (var index = 0; index < animatables.length; index++) {
  12490. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12491. }
  12492. }
  12493. return animatable;
  12494. };
  12495. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12496. if (speedRatio === undefined) {
  12497. speedRatio = 1.0;
  12498. }
  12499. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12500. return animatable;
  12501. };
  12502. Scene.prototype.getAnimatableByTarget = function (target) {
  12503. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12504. if (this._activeAnimatables[index].target === target) {
  12505. return this._activeAnimatables[index];
  12506. }
  12507. }
  12508. return null;
  12509. };
  12510. /**
  12511. * Will stop the animation of the given target
  12512. * @param target - the target
  12513. * @see beginAnimation
  12514. */
  12515. Scene.prototype.stopAnimation = function (target) {
  12516. var animatable = this.getAnimatableByTarget(target);
  12517. if (animatable) {
  12518. animatable.stop();
  12519. }
  12520. };
  12521. Scene.prototype._animate = function () {
  12522. if (!this.animationsEnabled) {
  12523. return;
  12524. }
  12525. if (!this._animationStartDate) {
  12526. this._animationStartDate = BABYLON.Tools.Now;
  12527. }
  12528. // Getting time
  12529. var now = BABYLON.Tools.Now;
  12530. var delay = now - this._animationStartDate;
  12531. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12532. this._activeAnimatables[index]._animate(delay);
  12533. }
  12534. };
  12535. // Matrix
  12536. Scene.prototype.getViewMatrix = function () {
  12537. return this._viewMatrix;
  12538. };
  12539. Scene.prototype.getProjectionMatrix = function () {
  12540. return this._projectionMatrix;
  12541. };
  12542. Scene.prototype.getTransformMatrix = function () {
  12543. return this._transformMatrix;
  12544. };
  12545. Scene.prototype.setTransformMatrix = function (view, projection) {
  12546. this._viewMatrix = view;
  12547. this._projectionMatrix = projection;
  12548. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12549. };
  12550. // Methods
  12551. Scene.prototype.addMesh = function (newMesh) {
  12552. newMesh.uniqueId = this._uniqueIdCounter++;
  12553. var position = this.meshes.push(newMesh);
  12554. //notify the collision coordinator
  12555. this.collisionCoordinator.onMeshAdded(newMesh);
  12556. if (this.onNewMeshAdded) {
  12557. this.onNewMeshAdded(newMesh, position, this);
  12558. }
  12559. };
  12560. Scene.prototype.removeMesh = function (toRemove) {
  12561. var index = this.meshes.indexOf(toRemove);
  12562. if (index !== -1) {
  12563. // Remove from the scene if mesh found
  12564. this.meshes.splice(index, 1);
  12565. }
  12566. //notify the collision coordinator
  12567. this.collisionCoordinator.onMeshRemoved(toRemove);
  12568. if (this.onMeshRemoved) {
  12569. this.onMeshRemoved(toRemove);
  12570. }
  12571. return index;
  12572. };
  12573. Scene.prototype.removeSkeleton = function (toRemove) {
  12574. var index = this.skeletons.indexOf(toRemove);
  12575. if (index !== -1) {
  12576. // Remove from the scene if mesh found
  12577. this.skeletons.splice(index, 1);
  12578. }
  12579. return index;
  12580. };
  12581. Scene.prototype.removeLight = function (toRemove) {
  12582. var index = this.lights.indexOf(toRemove);
  12583. if (index !== -1) {
  12584. // Remove from the scene if mesh found
  12585. this.lights.splice(index, 1);
  12586. }
  12587. if (this.onLightRemoved) {
  12588. this.onLightRemoved(toRemove);
  12589. }
  12590. return index;
  12591. };
  12592. Scene.prototype.removeCamera = function (toRemove) {
  12593. var index = this.cameras.indexOf(toRemove);
  12594. if (index !== -1) {
  12595. // Remove from the scene if mesh found
  12596. this.cameras.splice(index, 1);
  12597. }
  12598. // Remove from activeCameras
  12599. var index2 = this.activeCameras.indexOf(toRemove);
  12600. if (index2 !== -1) {
  12601. // Remove from the scene if mesh found
  12602. this.activeCameras.splice(index2, 1);
  12603. }
  12604. // Reset the activeCamera
  12605. if (this.activeCamera === toRemove) {
  12606. if (this.cameras.length > 0) {
  12607. this.activeCamera = this.cameras[0];
  12608. }
  12609. else {
  12610. this.activeCamera = null;
  12611. }
  12612. }
  12613. if (this.onCameraRemoved) {
  12614. this.onCameraRemoved(toRemove);
  12615. }
  12616. return index;
  12617. };
  12618. Scene.prototype.addLight = function (newLight) {
  12619. newLight.uniqueId = this._uniqueIdCounter++;
  12620. var position = this.lights.push(newLight);
  12621. if (this.onNewLightAdded) {
  12622. this.onNewLightAdded(newLight, position, this);
  12623. }
  12624. };
  12625. Scene.prototype.addCamera = function (newCamera) {
  12626. newCamera.uniqueId = this._uniqueIdCounter++;
  12627. var position = this.cameras.push(newCamera);
  12628. if (this.onNewCameraAdded) {
  12629. this.onNewCameraAdded(newCamera, position, this);
  12630. }
  12631. };
  12632. /**
  12633. * sets the active camera of the scene using its ID
  12634. * @param {string} id - the camera's ID
  12635. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12636. * @see activeCamera
  12637. */
  12638. Scene.prototype.setActiveCameraByID = function (id) {
  12639. var camera = this.getCameraByID(id);
  12640. if (camera) {
  12641. this.activeCamera = camera;
  12642. return camera;
  12643. }
  12644. return null;
  12645. };
  12646. /**
  12647. * sets the active camera of the scene using its name
  12648. * @param {string} name - the camera's name
  12649. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12650. * @see activeCamera
  12651. */
  12652. Scene.prototype.setActiveCameraByName = function (name) {
  12653. var camera = this.getCameraByName(name);
  12654. if (camera) {
  12655. this.activeCamera = camera;
  12656. return camera;
  12657. }
  12658. return null;
  12659. };
  12660. /**
  12661. * get a material using its id
  12662. * @param {string} the material's ID
  12663. * @return {BABYLON.Material|null} the material or null if none found.
  12664. */
  12665. Scene.prototype.getMaterialByID = function (id) {
  12666. for (var index = 0; index < this.materials.length; index++) {
  12667. if (this.materials[index].id === id) {
  12668. return this.materials[index];
  12669. }
  12670. }
  12671. return null;
  12672. };
  12673. /**
  12674. * get a material using its name
  12675. * @param {string} the material's name
  12676. * @return {BABYLON.Material|null} the material or null if none found.
  12677. */
  12678. Scene.prototype.getMaterialByName = function (name) {
  12679. for (var index = 0; index < this.materials.length; index++) {
  12680. if (this.materials[index].name === name) {
  12681. return this.materials[index];
  12682. }
  12683. }
  12684. return null;
  12685. };
  12686. Scene.prototype.getLensFlareSystemByName = function (name) {
  12687. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12688. if (this.lensFlareSystems[index].name === name) {
  12689. return this.lensFlareSystems[index];
  12690. }
  12691. }
  12692. return null;
  12693. };
  12694. Scene.prototype.getCameraByID = function (id) {
  12695. for (var index = 0; index < this.cameras.length; index++) {
  12696. if (this.cameras[index].id === id) {
  12697. return this.cameras[index];
  12698. }
  12699. }
  12700. return null;
  12701. };
  12702. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12703. for (var index = 0; index < this.cameras.length; index++) {
  12704. if (this.cameras[index].uniqueId === uniqueId) {
  12705. return this.cameras[index];
  12706. }
  12707. }
  12708. return null;
  12709. };
  12710. /**
  12711. * get a camera using its name
  12712. * @param {string} the camera's name
  12713. * @return {BABYLON.Camera|null} the camera or null if none found.
  12714. */
  12715. Scene.prototype.getCameraByName = function (name) {
  12716. for (var index = 0; index < this.cameras.length; index++) {
  12717. if (this.cameras[index].name === name) {
  12718. return this.cameras[index];
  12719. }
  12720. }
  12721. return null;
  12722. };
  12723. /**
  12724. * get a bone using its id
  12725. * @param {string} the bone's id
  12726. * @return {BABYLON.Bone|null} the bone or null if not found
  12727. */
  12728. Scene.prototype.getBoneByID = function (id) {
  12729. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12730. var skeleton = this.skeletons[skeletonIndex];
  12731. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12732. if (skeleton.bones[boneIndex].id === id) {
  12733. return skeleton.bones[boneIndex];
  12734. }
  12735. }
  12736. }
  12737. return null;
  12738. };
  12739. /**
  12740. * get a bone using its id
  12741. * @param {string} the bone's name
  12742. * @return {BABYLON.Bone|null} the bone or null if not found
  12743. */
  12744. Scene.prototype.getBoneByName = function (name) {
  12745. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12746. var skeleton = this.skeletons[skeletonIndex];
  12747. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12748. if (skeleton.bones[boneIndex].name === name) {
  12749. return skeleton.bones[boneIndex];
  12750. }
  12751. }
  12752. }
  12753. return null;
  12754. };
  12755. /**
  12756. * get a light node using its name
  12757. * @param {string} the light's name
  12758. * @return {BABYLON.Light|null} the light or null if none found.
  12759. */
  12760. Scene.prototype.getLightByName = function (name) {
  12761. for (var index = 0; index < this.lights.length; index++) {
  12762. if (this.lights[index].name === name) {
  12763. return this.lights[index];
  12764. }
  12765. }
  12766. return null;
  12767. };
  12768. /**
  12769. * get a light node using its ID
  12770. * @param {string} the light's id
  12771. * @return {BABYLON.Light|null} the light or null if none found.
  12772. */
  12773. Scene.prototype.getLightByID = function (id) {
  12774. for (var index = 0; index < this.lights.length; index++) {
  12775. if (this.lights[index].id === id) {
  12776. return this.lights[index];
  12777. }
  12778. }
  12779. return null;
  12780. };
  12781. /**
  12782. * get a light node using its scene-generated unique ID
  12783. * @param {number} the light's unique id
  12784. * @return {BABYLON.Light|null} the light or null if none found.
  12785. */
  12786. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12787. for (var index = 0; index < this.lights.length; index++) {
  12788. if (this.lights[index].uniqueId === uniqueId) {
  12789. return this.lights[index];
  12790. }
  12791. }
  12792. return null;
  12793. };
  12794. /**
  12795. * get a geometry using its ID
  12796. * @param {string} the geometry's id
  12797. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12798. */
  12799. Scene.prototype.getGeometryByID = function (id) {
  12800. for (var index = 0; index < this._geometries.length; index++) {
  12801. if (this._geometries[index].id === id) {
  12802. return this._geometries[index];
  12803. }
  12804. }
  12805. return null;
  12806. };
  12807. /**
  12808. * add a new geometry to this scene.
  12809. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12810. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12811. * @return {boolean} was the geometry added or not
  12812. */
  12813. Scene.prototype.pushGeometry = function (geometry, force) {
  12814. if (!force && this.getGeometryByID(geometry.id)) {
  12815. return false;
  12816. }
  12817. this._geometries.push(geometry);
  12818. //notify the collision coordinator
  12819. this.collisionCoordinator.onGeometryAdded(geometry);
  12820. if (this.onGeometryAdded) {
  12821. this.onGeometryAdded(geometry);
  12822. }
  12823. return true;
  12824. };
  12825. /**
  12826. * Removes an existing geometry
  12827. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12828. * @return {boolean} was the geometry removed or not
  12829. */
  12830. Scene.prototype.removeGeometry = function (geometry) {
  12831. var index = this._geometries.indexOf(geometry);
  12832. if (index > -1) {
  12833. this._geometries.splice(index, 1);
  12834. //notify the collision coordinator
  12835. this.collisionCoordinator.onGeometryDeleted(geometry);
  12836. if (this.onGeometryRemoved) {
  12837. this.onGeometryRemoved(geometry);
  12838. }
  12839. return true;
  12840. }
  12841. return false;
  12842. };
  12843. Scene.prototype.getGeometries = function () {
  12844. return this._geometries;
  12845. };
  12846. /**
  12847. * Get the first added mesh found of a given ID
  12848. * @param {string} id - the id to search for
  12849. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12850. */
  12851. Scene.prototype.getMeshByID = function (id) {
  12852. for (var index = 0; index < this.meshes.length; index++) {
  12853. if (this.meshes[index].id === id) {
  12854. return this.meshes[index];
  12855. }
  12856. }
  12857. return null;
  12858. };
  12859. /**
  12860. * Get a mesh with its auto-generated unique id
  12861. * @param {number} uniqueId - the unique id to search for
  12862. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12863. */
  12864. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12865. for (var index = 0; index < this.meshes.length; index++) {
  12866. if (this.meshes[index].uniqueId === uniqueId) {
  12867. return this.meshes[index];
  12868. }
  12869. }
  12870. return null;
  12871. };
  12872. /**
  12873. * Get a the last added mesh found of a given ID
  12874. * @param {string} id - the id to search for
  12875. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12876. */
  12877. Scene.prototype.getLastMeshByID = function (id) {
  12878. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12879. if (this.meshes[index].id === id) {
  12880. return this.meshes[index];
  12881. }
  12882. }
  12883. return null;
  12884. };
  12885. /**
  12886. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12887. * @param {string} id - the id to search for
  12888. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12889. */
  12890. Scene.prototype.getLastEntryByID = function (id) {
  12891. var index;
  12892. for (index = this.meshes.length - 1; index >= 0; index--) {
  12893. if (this.meshes[index].id === id) {
  12894. return this.meshes[index];
  12895. }
  12896. }
  12897. for (index = this.cameras.length - 1; index >= 0; index--) {
  12898. if (this.cameras[index].id === id) {
  12899. return this.cameras[index];
  12900. }
  12901. }
  12902. for (index = this.lights.length - 1; index >= 0; index--) {
  12903. if (this.lights[index].id === id) {
  12904. return this.lights[index];
  12905. }
  12906. }
  12907. return null;
  12908. };
  12909. Scene.prototype.getNodeByID = function (id) {
  12910. var mesh = this.getMeshByID(id);
  12911. if (mesh) {
  12912. return mesh;
  12913. }
  12914. var light = this.getLightByID(id);
  12915. if (light) {
  12916. return light;
  12917. }
  12918. var camera = this.getCameraByID(id);
  12919. if (camera) {
  12920. return camera;
  12921. }
  12922. var bone = this.getBoneByID(id);
  12923. return bone;
  12924. };
  12925. Scene.prototype.getNodeByName = function (name) {
  12926. var mesh = this.getMeshByName(name);
  12927. if (mesh) {
  12928. return mesh;
  12929. }
  12930. var light = this.getLightByName(name);
  12931. if (light) {
  12932. return light;
  12933. }
  12934. var camera = this.getCameraByName(name);
  12935. if (camera) {
  12936. return camera;
  12937. }
  12938. var bone = this.getBoneByName(name);
  12939. return bone;
  12940. };
  12941. Scene.prototype.getMeshByName = function (name) {
  12942. for (var index = 0; index < this.meshes.length; index++) {
  12943. if (this.meshes[index].name === name) {
  12944. return this.meshes[index];
  12945. }
  12946. }
  12947. return null;
  12948. };
  12949. Scene.prototype.getSoundByName = function (name) {
  12950. var index;
  12951. if (BABYLON.AudioEngine) {
  12952. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12953. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12954. return this.mainSoundTrack.soundCollection[index];
  12955. }
  12956. }
  12957. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12958. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12959. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12960. return this.soundTracks[sdIndex].soundCollection[index];
  12961. }
  12962. }
  12963. }
  12964. }
  12965. return null;
  12966. };
  12967. Scene.prototype.getLastSkeletonByID = function (id) {
  12968. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12969. if (this.skeletons[index].id === id) {
  12970. return this.skeletons[index];
  12971. }
  12972. }
  12973. return null;
  12974. };
  12975. Scene.prototype.getSkeletonById = function (id) {
  12976. for (var index = 0; index < this.skeletons.length; index++) {
  12977. if (this.skeletons[index].id === id) {
  12978. return this.skeletons[index];
  12979. }
  12980. }
  12981. return null;
  12982. };
  12983. Scene.prototype.getSkeletonByName = function (name) {
  12984. for (var index = 0; index < this.skeletons.length; index++) {
  12985. if (this.skeletons[index].name === name) {
  12986. return this.skeletons[index];
  12987. }
  12988. }
  12989. return null;
  12990. };
  12991. Scene.prototype.isActiveMesh = function (mesh) {
  12992. return (this._activeMeshes.indexOf(mesh) !== -1);
  12993. };
  12994. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12995. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12996. var material = subMesh.getMaterial();
  12997. if (mesh.showSubMeshesBoundingBox) {
  12998. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12999. }
  13000. if (material) {
  13001. // Render targets
  13002. if (material.getRenderTargetTextures) {
  13003. if (this._processedMaterials.indexOf(material) === -1) {
  13004. this._processedMaterials.push(material);
  13005. this._renderTargets.concat(material.getRenderTargetTextures());
  13006. }
  13007. }
  13008. // Dispatch
  13009. this._activeIndices += subMesh.indexCount;
  13010. this._renderingManager.dispatch(subMesh);
  13011. }
  13012. }
  13013. };
  13014. Scene.prototype._evaluateActiveMeshes = function () {
  13015. this.activeCamera._activeMeshes.reset();
  13016. this._activeMeshes.reset();
  13017. this._renderingManager.reset();
  13018. this._processedMaterials.reset();
  13019. this._activeParticleSystems.reset();
  13020. this._activeSkeletons.reset();
  13021. this._softwareSkinnedMeshes.reset();
  13022. this._boundingBoxRenderer.reset();
  13023. this._edgesRenderers.reset();
  13024. if (!this._frustumPlanes) {
  13025. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13026. }
  13027. else {
  13028. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13029. }
  13030. // Meshes
  13031. var meshes;
  13032. var len;
  13033. if (this._selectionOctree) {
  13034. var selection = this._selectionOctree.select(this._frustumPlanes);
  13035. meshes = selection.data;
  13036. len = selection.length;
  13037. }
  13038. else {
  13039. len = this.meshes.length;
  13040. meshes = this.meshes;
  13041. }
  13042. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13043. var mesh = meshes[meshIndex];
  13044. if (mesh.isBlocked) {
  13045. continue;
  13046. }
  13047. this._totalVertices += mesh.getTotalVertices();
  13048. if (!mesh.isReady() || !mesh.isEnabled()) {
  13049. continue;
  13050. }
  13051. mesh.computeWorldMatrix();
  13052. // Intersections
  13053. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13054. this._meshesForIntersections.pushNoDuplicate(mesh);
  13055. }
  13056. // Switch to current LOD
  13057. var meshLOD = mesh.getLOD(this.activeCamera);
  13058. if (!meshLOD) {
  13059. continue;
  13060. }
  13061. mesh._preActivate();
  13062. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13063. this._activeMeshes.push(mesh);
  13064. this.activeCamera._activeMeshes.push(mesh);
  13065. mesh._activate(this._renderId);
  13066. this._activeMesh(meshLOD);
  13067. }
  13068. }
  13069. // Particle systems
  13070. var beforeParticlesDate = BABYLON.Tools.Now;
  13071. if (this.particlesEnabled) {
  13072. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13073. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13074. var particleSystem = this.particleSystems[particleIndex];
  13075. if (!particleSystem.isStarted()) {
  13076. continue;
  13077. }
  13078. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13079. this._activeParticleSystems.push(particleSystem);
  13080. particleSystem.animate();
  13081. }
  13082. }
  13083. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13084. }
  13085. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13086. };
  13087. Scene.prototype._activeMesh = function (mesh) {
  13088. if (mesh.skeleton && this.skeletonsEnabled) {
  13089. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13090. if (!mesh.computeBonesUsingShaders) {
  13091. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13092. }
  13093. }
  13094. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13095. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13096. }
  13097. if (mesh._edgesRenderer) {
  13098. this._edgesRenderers.push(mesh._edgesRenderer);
  13099. }
  13100. if (mesh && mesh.subMeshes) {
  13101. // Submeshes Octrees
  13102. var len;
  13103. var subMeshes;
  13104. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13105. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13106. len = intersections.length;
  13107. subMeshes = intersections.data;
  13108. }
  13109. else {
  13110. subMeshes = mesh.subMeshes;
  13111. len = subMeshes.length;
  13112. }
  13113. for (var subIndex = 0; subIndex < len; subIndex++) {
  13114. var subMesh = subMeshes[subIndex];
  13115. this._evaluateSubMesh(subMesh, mesh);
  13116. }
  13117. }
  13118. };
  13119. Scene.prototype.updateTransformMatrix = function (force) {
  13120. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13121. };
  13122. Scene.prototype._renderForCamera = function (camera) {
  13123. var engine = this._engine;
  13124. this.activeCamera = camera;
  13125. if (!this.activeCamera)
  13126. throw new Error("Active camera not set");
  13127. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13128. // Viewport
  13129. engine.setViewport(this.activeCamera.viewport);
  13130. // Camera
  13131. this.resetCachedMaterial();
  13132. this._renderId++;
  13133. this.updateTransformMatrix();
  13134. if (this.beforeCameraRender) {
  13135. this.beforeCameraRender(this.activeCamera);
  13136. }
  13137. // Meshes
  13138. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13139. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13140. this._evaluateActiveMeshes();
  13141. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13142. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13143. // Skeletons
  13144. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13145. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13146. skeleton.prepare();
  13147. }
  13148. // Software skinning
  13149. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13150. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13151. mesh.applySkeleton(mesh.skeleton);
  13152. }
  13153. // Render targets
  13154. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13155. if (this.renderTargetsEnabled) {
  13156. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13157. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13158. var renderTarget = this._renderTargets.data[renderIndex];
  13159. if (renderTarget._shouldRender()) {
  13160. this._renderId++;
  13161. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13162. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13163. }
  13164. }
  13165. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13166. this._renderId++;
  13167. }
  13168. if (this._renderTargets.length > 0) {
  13169. engine.restoreDefaultFramebuffer();
  13170. }
  13171. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13172. // Prepare Frame
  13173. this.postProcessManager._prepareFrame();
  13174. var beforeRenderDate = BABYLON.Tools.Now;
  13175. // Backgrounds
  13176. var layerIndex;
  13177. var layer;
  13178. if (this.layers.length) {
  13179. engine.setDepthBuffer(false);
  13180. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13181. layer = this.layers[layerIndex];
  13182. if (layer.isBackground) {
  13183. layer.render();
  13184. }
  13185. }
  13186. engine.setDepthBuffer(true);
  13187. }
  13188. // Render
  13189. BABYLON.Tools.StartPerformanceCounter("Main render");
  13190. this._renderingManager.render(null, null, true, true);
  13191. BABYLON.Tools.EndPerformanceCounter("Main render");
  13192. // Bounding boxes
  13193. this._boundingBoxRenderer.render();
  13194. // Edges
  13195. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13196. this._edgesRenderers.data[edgesRendererIndex].render();
  13197. }
  13198. // Lens flares
  13199. if (this.lensFlaresEnabled) {
  13200. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13201. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13202. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13203. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13204. lensFlareSystem.render();
  13205. }
  13206. }
  13207. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13208. }
  13209. // Foregrounds
  13210. if (this.layers.length) {
  13211. engine.setDepthBuffer(false);
  13212. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13213. layer = this.layers[layerIndex];
  13214. if (!layer.isBackground) {
  13215. layer.render();
  13216. }
  13217. }
  13218. engine.setDepthBuffer(true);
  13219. }
  13220. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13221. // Finalize frame
  13222. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13223. // Update camera
  13224. this.activeCamera._updateFromScene();
  13225. // Reset some special arrays
  13226. this._renderTargets.reset();
  13227. if (this.afterCameraRender) {
  13228. this.afterCameraRender(this.activeCamera);
  13229. }
  13230. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13231. };
  13232. Scene.prototype._processSubCameras = function (camera) {
  13233. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13234. this._renderForCamera(camera);
  13235. return;
  13236. }
  13237. // rig cameras
  13238. for (var index = 0; index < camera._rigCameras.length; index++) {
  13239. this._renderForCamera(camera._rigCameras[index]);
  13240. }
  13241. this.activeCamera = camera;
  13242. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13243. // Update camera
  13244. this.activeCamera._updateFromScene();
  13245. };
  13246. Scene.prototype._checkIntersections = function () {
  13247. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13248. var sourceMesh = this._meshesForIntersections.data[index];
  13249. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13250. var action = sourceMesh.actionManager.actions[actionIndex];
  13251. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13252. var parameters = action.getTriggerParameter();
  13253. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13254. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13255. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13256. if (areIntersecting && currentIntersectionInProgress === -1) {
  13257. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13258. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13259. sourceMesh._intersectionsInProgress.push(otherMesh);
  13260. }
  13261. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13262. sourceMesh._intersectionsInProgress.push(otherMesh);
  13263. }
  13264. }
  13265. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13266. //They intersected, and now they don't.
  13267. //is this trigger an exit trigger? execute an event.
  13268. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13269. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13270. }
  13271. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13272. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13273. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13274. }
  13275. }
  13276. }
  13277. }
  13278. }
  13279. };
  13280. Scene.prototype.render = function () {
  13281. var startDate = BABYLON.Tools.Now;
  13282. this._particlesDuration = 0;
  13283. this._spritesDuration = 0;
  13284. this._activeParticles = 0;
  13285. this._renderDuration = 0;
  13286. this._renderTargetsDuration = 0;
  13287. this._evaluateActiveMeshesDuration = 0;
  13288. this._totalVertices = 0;
  13289. this._activeIndices = 0;
  13290. this._activeBones = 0;
  13291. this.getEngine().resetDrawCalls();
  13292. this._meshesForIntersections.reset();
  13293. this.resetCachedMaterial();
  13294. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13295. // Actions
  13296. if (this.actionManager) {
  13297. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13298. }
  13299. //Simplification Queue
  13300. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13301. this.simplificationQueue.executeNext();
  13302. }
  13303. // Animations
  13304. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13305. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13306. this._animate();
  13307. // Physics
  13308. if (this._physicsEngine) {
  13309. BABYLON.Tools.StartPerformanceCounter("Physics");
  13310. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13311. BABYLON.Tools.EndPerformanceCounter("Physics");
  13312. }
  13313. // Before render
  13314. if (this.beforeRender) {
  13315. this.beforeRender();
  13316. }
  13317. var callbackIndex;
  13318. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13319. this._onBeforeRenderCallbacks[callbackIndex]();
  13320. }
  13321. // Customs render targets
  13322. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13323. var engine = this.getEngine();
  13324. var currentActiveCamera = this.activeCamera;
  13325. if (this.renderTargetsEnabled) {
  13326. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13327. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13328. var renderTarget = this.customRenderTargets[customIndex];
  13329. if (renderTarget._shouldRender()) {
  13330. this._renderId++;
  13331. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13332. if (!this.activeCamera)
  13333. throw new Error("Active camera not set");
  13334. // Viewport
  13335. engine.setViewport(this.activeCamera.viewport);
  13336. // Camera
  13337. this.updateTransformMatrix();
  13338. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13339. }
  13340. }
  13341. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13342. this._renderId++;
  13343. }
  13344. if (this.customRenderTargets.length > 0) {
  13345. engine.restoreDefaultFramebuffer();
  13346. }
  13347. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13348. this.activeCamera = currentActiveCamera;
  13349. // Procedural textures
  13350. if (this.proceduralTexturesEnabled) {
  13351. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13352. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13353. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13354. if (proceduralTexture._shouldRender()) {
  13355. proceduralTexture.render();
  13356. }
  13357. }
  13358. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13359. }
  13360. // Clear
  13361. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13362. // Shadows
  13363. if (this.shadowsEnabled) {
  13364. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13365. var light = this.lights[lightIndex];
  13366. var shadowGenerator = light.getShadowGenerator();
  13367. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13368. this._renderTargets.push(shadowGenerator.getShadowMap());
  13369. }
  13370. }
  13371. }
  13372. // Depth renderer
  13373. if (this._depthRenderer) {
  13374. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13375. }
  13376. // RenderPipeline
  13377. this.postProcessRenderPipelineManager.update();
  13378. // Multi-cameras?
  13379. if (this.activeCameras.length > 0) {
  13380. var currentRenderId = this._renderId;
  13381. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13382. this._renderId = currentRenderId;
  13383. this._processSubCameras(this.activeCameras[cameraIndex]);
  13384. }
  13385. }
  13386. else {
  13387. if (!this.activeCamera) {
  13388. throw new Error("No camera defined");
  13389. }
  13390. this._processSubCameras(this.activeCamera);
  13391. }
  13392. // Intersection checks
  13393. this._checkIntersections();
  13394. // Update the audio listener attached to the camera
  13395. if (BABYLON.AudioEngine) {
  13396. this._updateAudioParameters();
  13397. }
  13398. // After render
  13399. if (this.afterRender) {
  13400. this.afterRender();
  13401. }
  13402. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13403. this._onAfterRenderCallbacks[callbackIndex]();
  13404. }
  13405. // Cleaning
  13406. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13407. this._toBeDisposed.data[index].dispose();
  13408. this._toBeDisposed[index] = null;
  13409. }
  13410. this._toBeDisposed.reset();
  13411. if (this.dumpNextRenderTargets) {
  13412. this.dumpNextRenderTargets = false;
  13413. }
  13414. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13415. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13416. };
  13417. Scene.prototype._updateAudioParameters = function () {
  13418. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13419. return;
  13420. }
  13421. var listeningCamera;
  13422. var audioEngine = BABYLON.Engine.audioEngine;
  13423. if (this.activeCameras.length > 0) {
  13424. listeningCamera = this.activeCameras[0];
  13425. }
  13426. else {
  13427. listeningCamera = this.activeCamera;
  13428. }
  13429. if (listeningCamera && audioEngine.canUseWebAudio) {
  13430. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13431. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13432. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13433. cameraDirection.normalize();
  13434. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13435. var i;
  13436. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13437. var sound = this.mainSoundTrack.soundCollection[i];
  13438. if (sound.useCustomAttenuation) {
  13439. sound.updateDistanceFromListener();
  13440. }
  13441. }
  13442. for (i = 0; i < this.soundTracks.length; i++) {
  13443. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13444. sound = this.soundTracks[i].soundCollection[j];
  13445. if (sound.useCustomAttenuation) {
  13446. sound.updateDistanceFromListener();
  13447. }
  13448. }
  13449. }
  13450. }
  13451. };
  13452. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13453. // Audio
  13454. get: function () {
  13455. return this._audioEnabled;
  13456. },
  13457. set: function (value) {
  13458. this._audioEnabled = value;
  13459. if (BABYLON.AudioEngine) {
  13460. if (this._audioEnabled) {
  13461. this._enableAudio();
  13462. }
  13463. else {
  13464. this._disableAudio();
  13465. }
  13466. }
  13467. },
  13468. enumerable: true,
  13469. configurable: true
  13470. });
  13471. Scene.prototype._disableAudio = function () {
  13472. var i;
  13473. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13474. this.mainSoundTrack.soundCollection[i].pause();
  13475. }
  13476. for (i = 0; i < this.soundTracks.length; i++) {
  13477. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13478. this.soundTracks[i].soundCollection[j].pause();
  13479. }
  13480. }
  13481. };
  13482. Scene.prototype._enableAudio = function () {
  13483. var i;
  13484. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13485. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13486. this.mainSoundTrack.soundCollection[i].play();
  13487. }
  13488. }
  13489. for (i = 0; i < this.soundTracks.length; i++) {
  13490. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13491. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13492. this.soundTracks[i].soundCollection[j].play();
  13493. }
  13494. }
  13495. }
  13496. };
  13497. Object.defineProperty(Scene.prototype, "headphone", {
  13498. get: function () {
  13499. return this._headphone;
  13500. },
  13501. set: function (value) {
  13502. this._headphone = value;
  13503. if (BABYLON.AudioEngine) {
  13504. if (this._headphone) {
  13505. this._switchAudioModeForHeadphones();
  13506. }
  13507. else {
  13508. this._switchAudioModeForNormalSpeakers();
  13509. }
  13510. }
  13511. },
  13512. enumerable: true,
  13513. configurable: true
  13514. });
  13515. Scene.prototype._switchAudioModeForHeadphones = function () {
  13516. this.mainSoundTrack.switchPanningModelToHRTF();
  13517. for (var i = 0; i < this.soundTracks.length; i++) {
  13518. this.soundTracks[i].switchPanningModelToHRTF();
  13519. }
  13520. };
  13521. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13522. this.mainSoundTrack.switchPanningModelToEqualPower();
  13523. for (var i = 0; i < this.soundTracks.length; i++) {
  13524. this.soundTracks[i].switchPanningModelToEqualPower();
  13525. }
  13526. };
  13527. Scene.prototype.enableDepthRenderer = function () {
  13528. if (this._depthRenderer) {
  13529. return this._depthRenderer;
  13530. }
  13531. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13532. return this._depthRenderer;
  13533. };
  13534. Scene.prototype.disableDepthRenderer = function () {
  13535. if (!this._depthRenderer) {
  13536. return;
  13537. }
  13538. this._depthRenderer.dispose();
  13539. this._depthRenderer = null;
  13540. };
  13541. Scene.prototype.dispose = function () {
  13542. this.beforeRender = null;
  13543. this.afterRender = null;
  13544. this.skeletons = [];
  13545. this._boundingBoxRenderer.dispose();
  13546. if (this._depthRenderer) {
  13547. this._depthRenderer.dispose();
  13548. }
  13549. // Debug layer
  13550. this.debugLayer.hide();
  13551. // Events
  13552. if (this.onDispose) {
  13553. this.onDispose();
  13554. }
  13555. this._onBeforeRenderCallbacks = [];
  13556. this._onAfterRenderCallbacks = [];
  13557. this.detachControl();
  13558. // Release sounds & sounds tracks
  13559. if (BABYLON.AudioEngine) {
  13560. this.disposeSounds();
  13561. }
  13562. // Detach cameras
  13563. var canvas = this._engine.getRenderingCanvas();
  13564. var index;
  13565. for (index = 0; index < this.cameras.length; index++) {
  13566. this.cameras[index].detachControl(canvas);
  13567. }
  13568. // Release lights
  13569. while (this.lights.length) {
  13570. this.lights[0].dispose();
  13571. }
  13572. // Release meshes
  13573. while (this.meshes.length) {
  13574. this.meshes[0].dispose(true);
  13575. }
  13576. // Release cameras
  13577. while (this.cameras.length) {
  13578. this.cameras[0].dispose();
  13579. }
  13580. // Release materials
  13581. while (this.materials.length) {
  13582. this.materials[0].dispose();
  13583. }
  13584. // Release particles
  13585. while (this.particleSystems.length) {
  13586. this.particleSystems[0].dispose();
  13587. }
  13588. // Release sprites
  13589. while (this.spriteManagers.length) {
  13590. this.spriteManagers[0].dispose();
  13591. }
  13592. // Release layers
  13593. while (this.layers.length) {
  13594. this.layers[0].dispose();
  13595. }
  13596. // Release textures
  13597. while (this.textures.length) {
  13598. this.textures[0].dispose();
  13599. }
  13600. // Post-processes
  13601. this.postProcessManager.dispose();
  13602. // Physics
  13603. if (this._physicsEngine) {
  13604. this.disablePhysicsEngine();
  13605. }
  13606. // Remove from engine
  13607. index = this._engine.scenes.indexOf(this);
  13608. if (index > -1) {
  13609. this._engine.scenes.splice(index, 1);
  13610. }
  13611. this._engine.wipeCaches();
  13612. };
  13613. // Release sounds & sounds tracks
  13614. Scene.prototype.disposeSounds = function () {
  13615. this.mainSoundTrack.dispose();
  13616. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13617. this.soundTracks[scIndex].dispose();
  13618. }
  13619. };
  13620. // Octrees
  13621. Scene.prototype.getWorldExtends = function () {
  13622. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13623. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13624. for (var index = 0; index < this.meshes.length; index++) {
  13625. var mesh = this.meshes[index];
  13626. mesh.computeWorldMatrix(true);
  13627. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13628. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13629. BABYLON.Tools.CheckExtends(minBox, min, max);
  13630. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13631. }
  13632. return {
  13633. min: min,
  13634. max: max
  13635. };
  13636. };
  13637. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13638. if (maxCapacity === void 0) { maxCapacity = 64; }
  13639. if (maxDepth === void 0) { maxDepth = 2; }
  13640. if (!this._selectionOctree) {
  13641. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13642. }
  13643. var worldExtends = this.getWorldExtends();
  13644. // Update octree
  13645. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13646. return this._selectionOctree;
  13647. };
  13648. // Picking
  13649. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13650. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13651. var engine = this._engine;
  13652. if (!camera) {
  13653. if (!this.activeCamera)
  13654. throw new Error("Active camera not set");
  13655. camera = this.activeCamera;
  13656. }
  13657. var cameraViewport = camera.viewport;
  13658. var viewport = cameraViewport.toGlobal(engine);
  13659. // Moving coordinates to local viewport world
  13660. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13661. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13662. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13663. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13664. };
  13665. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13666. var engine = this._engine;
  13667. if (!camera) {
  13668. if (!this.activeCamera)
  13669. throw new Error("Active camera not set");
  13670. camera = this.activeCamera;
  13671. }
  13672. var cameraViewport = camera.viewport;
  13673. var viewport = cameraViewport.toGlobal(engine);
  13674. var identity = BABYLON.Matrix.Identity();
  13675. // Moving coordinates to local viewport world
  13676. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13677. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13678. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13679. };
  13680. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13681. var pickingInfo = null;
  13682. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13683. var mesh = this.meshes[meshIndex];
  13684. if (predicate) {
  13685. if (!predicate(mesh)) {
  13686. continue;
  13687. }
  13688. }
  13689. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13690. continue;
  13691. }
  13692. var world = mesh.getWorldMatrix();
  13693. var ray = rayFunction(world);
  13694. var result = mesh.intersects(ray, fastCheck);
  13695. if (!result || !result.hit)
  13696. continue;
  13697. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13698. continue;
  13699. pickingInfo = result;
  13700. if (fastCheck) {
  13701. break;
  13702. }
  13703. }
  13704. return pickingInfo || new BABYLON.PickingInfo();
  13705. };
  13706. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13707. var pickingInfo = null;
  13708. camera = camera || this.activeCamera;
  13709. if (this.spriteManagers.length > 0) {
  13710. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13711. var spriteManager = this.spriteManagers[spriteIndex];
  13712. if (!spriteManager.isPickable) {
  13713. continue;
  13714. }
  13715. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13716. if (!result || !result.hit)
  13717. continue;
  13718. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13719. continue;
  13720. pickingInfo = result;
  13721. if (fastCheck) {
  13722. break;
  13723. }
  13724. }
  13725. }
  13726. return pickingInfo || new BABYLON.PickingInfo();
  13727. };
  13728. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13729. var _this = this;
  13730. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13731. /// <param name="x">X position on screen</param>
  13732. /// <param name="y">Y position on screen</param>
  13733. /// <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>
  13734. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13735. /// <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>
  13736. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13737. };
  13738. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13739. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13740. /// <param name="x">X position on screen</param>
  13741. /// <param name="y">Y position on screen</param>
  13742. /// <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>
  13743. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13744. /// <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>
  13745. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13746. };
  13747. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13748. var _this = this;
  13749. return this._internalPick(function (world) {
  13750. if (!_this._pickWithRayInverseMatrix) {
  13751. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13752. }
  13753. world.invertToRef(_this._pickWithRayInverseMatrix);
  13754. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13755. }, predicate, fastCheck);
  13756. };
  13757. Scene.prototype.setPointerOverMesh = function (mesh) {
  13758. if (this._pointerOverMesh === mesh) {
  13759. return;
  13760. }
  13761. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13762. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13763. }
  13764. this._pointerOverMesh = mesh;
  13765. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13766. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13767. }
  13768. };
  13769. Scene.prototype.getPointerOverMesh = function () {
  13770. return this._pointerOverMesh;
  13771. };
  13772. // Physics
  13773. Scene.prototype.getPhysicsEngine = function () {
  13774. return this._physicsEngine;
  13775. };
  13776. /**
  13777. * Enables physics to the current scene
  13778. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13779. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13780. * @return {boolean} was the physics engine initialized
  13781. */
  13782. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13783. if (this._physicsEngine) {
  13784. return true;
  13785. }
  13786. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13787. if (!this._physicsEngine.isSupported()) {
  13788. this._physicsEngine = null;
  13789. return false;
  13790. }
  13791. this._physicsEngine._initialize(gravity);
  13792. return true;
  13793. };
  13794. Scene.prototype.disablePhysicsEngine = function () {
  13795. if (!this._physicsEngine) {
  13796. return;
  13797. }
  13798. this._physicsEngine.dispose();
  13799. this._physicsEngine = undefined;
  13800. };
  13801. Scene.prototype.isPhysicsEnabled = function () {
  13802. return this._physicsEngine !== undefined;
  13803. };
  13804. /**
  13805. * Sets the gravity of the physics engine (and NOT of the scene)
  13806. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13807. */
  13808. Scene.prototype.setGravity = function (gravity) {
  13809. if (!this._physicsEngine) {
  13810. return;
  13811. }
  13812. this._physicsEngine._setGravity(gravity);
  13813. };
  13814. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13815. if (parts.parts) {
  13816. options = parts;
  13817. parts = parts.parts;
  13818. }
  13819. if (!this._physicsEngine) {
  13820. return null;
  13821. }
  13822. for (var index = 0; index < parts.length; index++) {
  13823. var mesh = parts[index].mesh;
  13824. mesh._physicImpostor = parts[index].impostor;
  13825. mesh._physicsMass = options.mass / parts.length;
  13826. mesh._physicsFriction = options.friction;
  13827. mesh._physicRestitution = options.restitution;
  13828. }
  13829. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13830. };
  13831. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13832. for (var index = 0; index < compound.parts.length; index++) {
  13833. var mesh = compound.parts[index].mesh;
  13834. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13835. this._physicsEngine._unregisterMesh(mesh);
  13836. }
  13837. };
  13838. // Misc.
  13839. Scene.prototype.createDefaultCameraOrLight = function () {
  13840. // Light
  13841. if (this.lights.length === 0) {
  13842. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13843. }
  13844. // Camera
  13845. if (!this.activeCamera) {
  13846. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13847. // Compute position
  13848. var worldExtends = this.getWorldExtends();
  13849. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13850. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13851. camera.setTarget(worldCenter);
  13852. this.activeCamera = camera;
  13853. }
  13854. };
  13855. // Tags
  13856. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13857. if (tagsQuery === undefined) {
  13858. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13859. return list;
  13860. }
  13861. var listByTags = [];
  13862. forEach = forEach || (function (item) { return; });
  13863. for (var i in list) {
  13864. var item = list[i];
  13865. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13866. listByTags.push(item);
  13867. forEach(item);
  13868. }
  13869. }
  13870. return listByTags;
  13871. };
  13872. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13873. return this._getByTags(this.meshes, tagsQuery, forEach);
  13874. };
  13875. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13876. return this._getByTags(this.cameras, tagsQuery, forEach);
  13877. };
  13878. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13879. return this._getByTags(this.lights, tagsQuery, forEach);
  13880. };
  13881. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13882. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13883. };
  13884. // Statics
  13885. Scene._FOGMODE_NONE = 0;
  13886. Scene._FOGMODE_EXP = 1;
  13887. Scene._FOGMODE_EXP2 = 2;
  13888. Scene._FOGMODE_LINEAR = 3;
  13889. Scene.MinDeltaTime = 1.0;
  13890. Scene.MaxDeltaTime = 1000.0;
  13891. return Scene;
  13892. })();
  13893. BABYLON.Scene = Scene;
  13894. })(BABYLON || (BABYLON = {}));
  13895. var BABYLON;
  13896. (function (BABYLON) {
  13897. var VertexBuffer = (function () {
  13898. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13899. if (engine instanceof BABYLON.Mesh) {
  13900. this._engine = engine.getScene().getEngine();
  13901. }
  13902. else {
  13903. this._engine = engine;
  13904. }
  13905. this._updatable = updatable;
  13906. this._data = data;
  13907. if (!postponeInternalCreation) {
  13908. this.create();
  13909. }
  13910. this._kind = kind;
  13911. if (stride) {
  13912. this._strideSize = stride;
  13913. return;
  13914. }
  13915. // Deduce stride from kind
  13916. switch (kind) {
  13917. case VertexBuffer.PositionKind:
  13918. this._strideSize = 3;
  13919. break;
  13920. case VertexBuffer.NormalKind:
  13921. this._strideSize = 3;
  13922. break;
  13923. case VertexBuffer.UVKind:
  13924. case VertexBuffer.UV2Kind:
  13925. case VertexBuffer.UV3Kind:
  13926. case VertexBuffer.UV4Kind:
  13927. case VertexBuffer.UV5Kind:
  13928. case VertexBuffer.UV6Kind:
  13929. this._strideSize = 2;
  13930. break;
  13931. case VertexBuffer.ColorKind:
  13932. this._strideSize = 4;
  13933. break;
  13934. case VertexBuffer.MatricesIndicesKind:
  13935. case VertexBuffer.MatricesIndicesExtraKind:
  13936. this._strideSize = 4;
  13937. break;
  13938. case VertexBuffer.MatricesWeightsKind:
  13939. case VertexBuffer.MatricesWeightsExtraKind:
  13940. this._strideSize = 4;
  13941. break;
  13942. }
  13943. }
  13944. // Properties
  13945. VertexBuffer.prototype.isUpdatable = function () {
  13946. return this._updatable;
  13947. };
  13948. VertexBuffer.prototype.getData = function () {
  13949. return this._data;
  13950. };
  13951. VertexBuffer.prototype.getBuffer = function () {
  13952. return this._buffer;
  13953. };
  13954. VertexBuffer.prototype.getStrideSize = function () {
  13955. return this._strideSize;
  13956. };
  13957. // Methods
  13958. VertexBuffer.prototype.create = function (data) {
  13959. if (!data && this._buffer) {
  13960. return; // nothing to do
  13961. }
  13962. data = data || this._data;
  13963. if (!this._buffer) {
  13964. if (this._updatable) {
  13965. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13966. }
  13967. else {
  13968. this._buffer = this._engine.createVertexBuffer(data);
  13969. }
  13970. }
  13971. if (this._updatable) {
  13972. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13973. this._data = data;
  13974. }
  13975. };
  13976. VertexBuffer.prototype.update = function (data) {
  13977. this.create(data);
  13978. };
  13979. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13980. if (!this._buffer) {
  13981. return;
  13982. }
  13983. if (this._updatable) {
  13984. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13985. this._data = null;
  13986. }
  13987. };
  13988. VertexBuffer.prototype.dispose = function () {
  13989. if (!this._buffer) {
  13990. return;
  13991. }
  13992. if (this._engine._releaseBuffer(this._buffer)) {
  13993. this._buffer = null;
  13994. }
  13995. };
  13996. Object.defineProperty(VertexBuffer, "PositionKind", {
  13997. get: function () {
  13998. return VertexBuffer._PositionKind;
  13999. },
  14000. enumerable: true,
  14001. configurable: true
  14002. });
  14003. Object.defineProperty(VertexBuffer, "NormalKind", {
  14004. get: function () {
  14005. return VertexBuffer._NormalKind;
  14006. },
  14007. enumerable: true,
  14008. configurable: true
  14009. });
  14010. Object.defineProperty(VertexBuffer, "UVKind", {
  14011. get: function () {
  14012. return VertexBuffer._UVKind;
  14013. },
  14014. enumerable: true,
  14015. configurable: true
  14016. });
  14017. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14018. get: function () {
  14019. return VertexBuffer._UV2Kind;
  14020. },
  14021. enumerable: true,
  14022. configurable: true
  14023. });
  14024. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14025. get: function () {
  14026. return VertexBuffer._UV3Kind;
  14027. },
  14028. enumerable: true,
  14029. configurable: true
  14030. });
  14031. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14032. get: function () {
  14033. return VertexBuffer._UV4Kind;
  14034. },
  14035. enumerable: true,
  14036. configurable: true
  14037. });
  14038. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14039. get: function () {
  14040. return VertexBuffer._UV5Kind;
  14041. },
  14042. enumerable: true,
  14043. configurable: true
  14044. });
  14045. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14046. get: function () {
  14047. return VertexBuffer._UV6Kind;
  14048. },
  14049. enumerable: true,
  14050. configurable: true
  14051. });
  14052. Object.defineProperty(VertexBuffer, "ColorKind", {
  14053. get: function () {
  14054. return VertexBuffer._ColorKind;
  14055. },
  14056. enumerable: true,
  14057. configurable: true
  14058. });
  14059. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14060. get: function () {
  14061. return VertexBuffer._MatricesIndicesKind;
  14062. },
  14063. enumerable: true,
  14064. configurable: true
  14065. });
  14066. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14067. get: function () {
  14068. return VertexBuffer._MatricesWeightsKind;
  14069. },
  14070. enumerable: true,
  14071. configurable: true
  14072. });
  14073. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14074. get: function () {
  14075. return VertexBuffer._MatricesIndicesExtraKind;
  14076. },
  14077. enumerable: true,
  14078. configurable: true
  14079. });
  14080. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14081. get: function () {
  14082. return VertexBuffer._MatricesWeightsExtraKind;
  14083. },
  14084. enumerable: true,
  14085. configurable: true
  14086. });
  14087. // Enums
  14088. VertexBuffer._PositionKind = "position";
  14089. VertexBuffer._NormalKind = "normal";
  14090. VertexBuffer._UVKind = "uv";
  14091. VertexBuffer._UV2Kind = "uv2";
  14092. VertexBuffer._UV3Kind = "uv3";
  14093. VertexBuffer._UV4Kind = "uv4";
  14094. VertexBuffer._UV5Kind = "uv5";
  14095. VertexBuffer._UV6Kind = "uv6";
  14096. VertexBuffer._ColorKind = "color";
  14097. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14098. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14099. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14100. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14101. return VertexBuffer;
  14102. })();
  14103. BABYLON.VertexBuffer = VertexBuffer;
  14104. })(BABYLON || (BABYLON = {}));
  14105. var BABYLON;
  14106. (function (BABYLON) {
  14107. /**
  14108. * Creates an instance based on a source mesh.
  14109. */
  14110. var InstancedMesh = (function (_super) {
  14111. __extends(InstancedMesh, _super);
  14112. function InstancedMesh(name, source) {
  14113. _super.call(this, name, source.getScene());
  14114. source.instances.push(this);
  14115. this._sourceMesh = source;
  14116. this.position.copyFrom(source.position);
  14117. this.rotation.copyFrom(source.rotation);
  14118. this.scaling.copyFrom(source.scaling);
  14119. if (source.rotationQuaternion) {
  14120. this.rotationQuaternion = source.rotationQuaternion.clone();
  14121. }
  14122. this.infiniteDistance = source.infiniteDistance;
  14123. this.setPivotMatrix(source.getPivotMatrix());
  14124. this.refreshBoundingInfo();
  14125. this._syncSubMeshes();
  14126. }
  14127. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14128. // Methods
  14129. get: function () {
  14130. return this._sourceMesh.receiveShadows;
  14131. },
  14132. enumerable: true,
  14133. configurable: true
  14134. });
  14135. Object.defineProperty(InstancedMesh.prototype, "material", {
  14136. get: function () {
  14137. return this._sourceMesh.material;
  14138. },
  14139. enumerable: true,
  14140. configurable: true
  14141. });
  14142. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14143. get: function () {
  14144. return this._sourceMesh.visibility;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14150. get: function () {
  14151. return this._sourceMesh.skeleton;
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14157. get: function () {
  14158. return this._sourceMesh.renderingGroupId;
  14159. },
  14160. enumerable: true,
  14161. configurable: true
  14162. });
  14163. InstancedMesh.prototype.getTotalVertices = function () {
  14164. return this._sourceMesh.getTotalVertices();
  14165. };
  14166. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14167. get: function () {
  14168. return this._sourceMesh;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14174. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14175. };
  14176. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14177. return this._sourceMesh.isVerticesDataPresent(kind);
  14178. };
  14179. InstancedMesh.prototype.getIndices = function () {
  14180. return this._sourceMesh.getIndices();
  14181. };
  14182. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14183. get: function () {
  14184. return this._sourceMesh._positions;
  14185. },
  14186. enumerable: true,
  14187. configurable: true
  14188. });
  14189. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14190. var meshBB = this._sourceMesh.getBoundingInfo();
  14191. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14192. this._updateBoundingInfo();
  14193. };
  14194. InstancedMesh.prototype._preActivate = function () {
  14195. if (this._currentLOD) {
  14196. this._currentLOD._preActivate();
  14197. }
  14198. };
  14199. InstancedMesh.prototype._activate = function (renderId) {
  14200. if (this._currentLOD) {
  14201. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14202. }
  14203. };
  14204. InstancedMesh.prototype.getLOD = function (camera) {
  14205. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14206. if (this._currentLOD === this.sourceMesh) {
  14207. return this;
  14208. }
  14209. return this._currentLOD;
  14210. };
  14211. InstancedMesh.prototype._syncSubMeshes = function () {
  14212. this.releaseSubMeshes();
  14213. if (this._sourceMesh.subMeshes) {
  14214. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14215. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14216. }
  14217. }
  14218. };
  14219. InstancedMesh.prototype._generatePointsArray = function () {
  14220. return this._sourceMesh._generatePointsArray();
  14221. };
  14222. // Clone
  14223. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14224. var result = this._sourceMesh.createInstance(name);
  14225. // Deep copy
  14226. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14227. // Bounding info
  14228. this.refreshBoundingInfo();
  14229. // Parent
  14230. if (newParent) {
  14231. result.parent = newParent;
  14232. }
  14233. if (!doNotCloneChildren) {
  14234. // Children
  14235. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14236. var mesh = this.getScene().meshes[index];
  14237. if (mesh.parent === this) {
  14238. mesh.clone(mesh.name, result);
  14239. }
  14240. }
  14241. }
  14242. result.computeWorldMatrix(true);
  14243. return result;
  14244. };
  14245. // Dispoe
  14246. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14247. // Remove from mesh
  14248. var index = this._sourceMesh.instances.indexOf(this);
  14249. this._sourceMesh.instances.splice(index, 1);
  14250. _super.prototype.dispose.call(this, doNotRecurse);
  14251. };
  14252. return InstancedMesh;
  14253. })(BABYLON.AbstractMesh);
  14254. BABYLON.InstancedMesh = InstancedMesh;
  14255. })(BABYLON || (BABYLON = {}));
  14256. var BABYLON;
  14257. (function (BABYLON) {
  14258. var _InstancesBatch = (function () {
  14259. function _InstancesBatch() {
  14260. this.mustReturn = false;
  14261. this.visibleInstances = new Array();
  14262. this.renderSelf = new Array();
  14263. }
  14264. return _InstancesBatch;
  14265. })();
  14266. BABYLON._InstancesBatch = _InstancesBatch;
  14267. var Mesh = (function (_super) {
  14268. __extends(Mesh, _super);
  14269. /**
  14270. * @constructor
  14271. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14272. * @param {Scene} scene - The scene to add this mesh to.
  14273. * @param {Node} parent - The parent of this mesh, if it has one
  14274. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14275. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14276. * When false, achieved by calling a clone(), also passing False.
  14277. * This will make creation of children, recursive.
  14278. */
  14279. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14280. if (parent === void 0) { parent = null; }
  14281. _super.call(this, name, scene);
  14282. // Members
  14283. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14284. this.instances = new Array();
  14285. this._LODLevels = new Array();
  14286. this._onBeforeRenderCallbacks = new Array();
  14287. this._onAfterRenderCallbacks = new Array();
  14288. this._visibleInstances = {};
  14289. this._renderIdForInstances = new Array();
  14290. this._batchCache = new _InstancesBatch();
  14291. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14292. this._sideOrientation = Mesh._DEFAULTSIDE;
  14293. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14294. if (source) {
  14295. // Geometry
  14296. if (source._geometry) {
  14297. source._geometry.applyToMesh(this);
  14298. }
  14299. // Deep copy
  14300. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14301. this.id = name + "." + source.id;
  14302. // Material
  14303. this.material = source.material;
  14304. var index;
  14305. if (!doNotCloneChildren) {
  14306. // Children
  14307. for (index = 0; index < scene.meshes.length; index++) {
  14308. var mesh = scene.meshes[index];
  14309. if (mesh.parent === source) {
  14310. // doNotCloneChildren is always going to be False
  14311. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14312. }
  14313. }
  14314. }
  14315. // Particles
  14316. for (index = 0; index < scene.particleSystems.length; index++) {
  14317. var system = scene.particleSystems[index];
  14318. if (system.emitter === source) {
  14319. system.clone(system.name, this);
  14320. }
  14321. }
  14322. this.computeWorldMatrix(true);
  14323. }
  14324. // Parent
  14325. if (parent !== null) {
  14326. this.parent = parent;
  14327. }
  14328. }
  14329. Object.defineProperty(Mesh, "FRONTSIDE", {
  14330. get: function () {
  14331. return Mesh._FRONTSIDE;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(Mesh, "BACKSIDE", {
  14337. get: function () {
  14338. return Mesh._BACKSIDE;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14344. get: function () {
  14345. return Mesh._DOUBLESIDE;
  14346. },
  14347. enumerable: true,
  14348. configurable: true
  14349. });
  14350. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14351. get: function () {
  14352. return Mesh._DEFAULTSIDE;
  14353. },
  14354. enumerable: true,
  14355. configurable: true
  14356. });
  14357. Object.defineProperty(Mesh, "NO_CAP", {
  14358. get: function () {
  14359. return Mesh._NO_CAP;
  14360. },
  14361. enumerable: true,
  14362. configurable: true
  14363. });
  14364. Object.defineProperty(Mesh, "CAP_START", {
  14365. get: function () {
  14366. return Mesh._CAP_START;
  14367. },
  14368. enumerable: true,
  14369. configurable: true
  14370. });
  14371. Object.defineProperty(Mesh, "CAP_END", {
  14372. get: function () {
  14373. return Mesh._CAP_END;
  14374. },
  14375. enumerable: true,
  14376. configurable: true
  14377. });
  14378. Object.defineProperty(Mesh, "CAP_ALL", {
  14379. get: function () {
  14380. return Mesh._CAP_ALL;
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14386. // Methods
  14387. get: function () {
  14388. return this._LODLevels.length > 0;
  14389. },
  14390. enumerable: true,
  14391. configurable: true
  14392. });
  14393. Mesh.prototype._sortLODLevels = function () {
  14394. this._LODLevels.sort(function (a, b) {
  14395. if (a.distance < b.distance) {
  14396. return 1;
  14397. }
  14398. if (a.distance > b.distance) {
  14399. return -1;
  14400. }
  14401. return 0;
  14402. });
  14403. };
  14404. /**
  14405. * Add a mesh as LOD level triggered at the given distance.
  14406. * @param {number} distance - the distance from the center of the object to show this level
  14407. * @param {Mesh} mesh - the mesh to be added as LOD level
  14408. * @return {Mesh} this mesh (for chaining)
  14409. */
  14410. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14411. if (mesh && mesh._masterMesh) {
  14412. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14413. return this;
  14414. }
  14415. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14416. this._LODLevels.push(level);
  14417. if (mesh) {
  14418. mesh._masterMesh = this;
  14419. }
  14420. this._sortLODLevels();
  14421. return this;
  14422. };
  14423. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14424. for (var index = 0; index < this._LODLevels.length; index++) {
  14425. var level = this._LODLevels[index];
  14426. if (level.distance === distance) {
  14427. return level.mesh;
  14428. }
  14429. }
  14430. return null;
  14431. };
  14432. /**
  14433. * Remove a mesh from the LOD array
  14434. * @param {Mesh} mesh - the mesh to be removed.
  14435. * @return {Mesh} this mesh (for chaining)
  14436. */
  14437. Mesh.prototype.removeLODLevel = function (mesh) {
  14438. for (var index = 0; index < this._LODLevels.length; index++) {
  14439. if (this._LODLevels[index].mesh === mesh) {
  14440. this._LODLevels.splice(index, 1);
  14441. if (mesh) {
  14442. mesh._masterMesh = null;
  14443. }
  14444. }
  14445. }
  14446. this._sortLODLevels();
  14447. return this;
  14448. };
  14449. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14450. if (!this._LODLevels || this._LODLevels.length === 0) {
  14451. return this;
  14452. }
  14453. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14454. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14455. if (this.onLODLevelSelection) {
  14456. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14457. }
  14458. return this;
  14459. }
  14460. for (var index = 0; index < this._LODLevels.length; index++) {
  14461. var level = this._LODLevels[index];
  14462. if (level.distance < distanceToCamera) {
  14463. if (level.mesh) {
  14464. level.mesh._preActivate();
  14465. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14466. }
  14467. if (this.onLODLevelSelection) {
  14468. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14469. }
  14470. return level.mesh;
  14471. }
  14472. }
  14473. if (this.onLODLevelSelection) {
  14474. this.onLODLevelSelection(distanceToCamera, this, this);
  14475. }
  14476. return this;
  14477. };
  14478. Object.defineProperty(Mesh.prototype, "geometry", {
  14479. get: function () {
  14480. return this._geometry;
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. Mesh.prototype.getTotalVertices = function () {
  14486. if (!this._geometry) {
  14487. return 0;
  14488. }
  14489. return this._geometry.getTotalVertices();
  14490. };
  14491. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14492. if (!this._geometry) {
  14493. return null;
  14494. }
  14495. return this._geometry.getVerticesData(kind, copyWhenShared);
  14496. };
  14497. Mesh.prototype.getVertexBuffer = function (kind) {
  14498. if (!this._geometry) {
  14499. return undefined;
  14500. }
  14501. return this._geometry.getVertexBuffer(kind);
  14502. };
  14503. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14504. if (!this._geometry) {
  14505. if (this._delayInfo) {
  14506. return this._delayInfo.indexOf(kind) !== -1;
  14507. }
  14508. return false;
  14509. }
  14510. return this._geometry.isVerticesDataPresent(kind);
  14511. };
  14512. Mesh.prototype.getVerticesDataKinds = function () {
  14513. if (!this._geometry) {
  14514. var result = [];
  14515. if (this._delayInfo) {
  14516. for (var kind in this._delayInfo) {
  14517. result.push(kind);
  14518. }
  14519. }
  14520. return result;
  14521. }
  14522. return this._geometry.getVerticesDataKinds();
  14523. };
  14524. Mesh.prototype.getTotalIndices = function () {
  14525. if (!this._geometry) {
  14526. return 0;
  14527. }
  14528. return this._geometry.getTotalIndices();
  14529. };
  14530. Mesh.prototype.getIndices = function (copyWhenShared) {
  14531. if (!this._geometry) {
  14532. return [];
  14533. }
  14534. return this._geometry.getIndices(copyWhenShared);
  14535. };
  14536. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14537. get: function () {
  14538. return this._masterMesh !== null && this._masterMesh !== undefined;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Mesh.prototype.isReady = function () {
  14544. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14545. return false;
  14546. }
  14547. return _super.prototype.isReady.call(this);
  14548. };
  14549. Mesh.prototype.isDisposed = function () {
  14550. return this._isDisposed;
  14551. };
  14552. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14553. get: function () {
  14554. return this._sideOrientation;
  14555. },
  14556. set: function (sideO) {
  14557. this._sideOrientation = sideO;
  14558. },
  14559. enumerable: true,
  14560. configurable: true
  14561. });
  14562. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14563. get: function () {
  14564. return this._areNormalsFrozen;
  14565. },
  14566. enumerable: true,
  14567. configurable: true
  14568. });
  14569. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14570. Mesh.prototype.freezeNormals = function () {
  14571. this._areNormalsFrozen = true;
  14572. };
  14573. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14574. Mesh.prototype.unfreezeNormals = function () {
  14575. this._areNormalsFrozen = false;
  14576. };
  14577. // Methods
  14578. Mesh.prototype._preActivate = function () {
  14579. var sceneRenderId = this.getScene().getRenderId();
  14580. if (this._preActivateId === sceneRenderId) {
  14581. return;
  14582. }
  14583. this._preActivateId = sceneRenderId;
  14584. this._visibleInstances = null;
  14585. };
  14586. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14587. if (!this._visibleInstances) {
  14588. this._visibleInstances = {};
  14589. this._visibleInstances.defaultRenderId = renderId;
  14590. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14591. }
  14592. if (!this._visibleInstances[renderId]) {
  14593. this._visibleInstances[renderId] = new Array();
  14594. }
  14595. this._visibleInstances[renderId].push(instance);
  14596. };
  14597. Mesh.prototype.refreshBoundingInfo = function () {
  14598. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14599. if (data) {
  14600. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14601. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14602. }
  14603. if (this.subMeshes) {
  14604. for (var index = 0; index < this.subMeshes.length; index++) {
  14605. this.subMeshes[index].refreshBoundingInfo();
  14606. }
  14607. }
  14608. this._updateBoundingInfo();
  14609. };
  14610. Mesh.prototype._createGlobalSubMesh = function () {
  14611. var totalVertices = this.getTotalVertices();
  14612. if (!totalVertices || !this.getIndices()) {
  14613. return null;
  14614. }
  14615. this.releaseSubMeshes();
  14616. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14617. };
  14618. Mesh.prototype.subdivide = function (count) {
  14619. if (count < 1) {
  14620. return;
  14621. }
  14622. var totalIndices = this.getTotalIndices();
  14623. var subdivisionSize = (totalIndices / count) | 0;
  14624. var offset = 0;
  14625. // Ensure that subdivisionSize is a multiple of 3
  14626. while (subdivisionSize % 3 !== 0) {
  14627. subdivisionSize++;
  14628. }
  14629. this.releaseSubMeshes();
  14630. for (var index = 0; index < count; index++) {
  14631. if (offset >= totalIndices) {
  14632. break;
  14633. }
  14634. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14635. offset += subdivisionSize;
  14636. }
  14637. this.synchronizeInstances();
  14638. };
  14639. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14640. if (!this._geometry) {
  14641. var vertexData = new BABYLON.VertexData();
  14642. vertexData.set(data, kind);
  14643. var scene = this.getScene();
  14644. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14645. }
  14646. else {
  14647. this._geometry.setVerticesData(kind, data, updatable, stride);
  14648. }
  14649. };
  14650. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14651. if (!this._geometry) {
  14652. return;
  14653. }
  14654. if (!makeItUnique) {
  14655. this._geometry.updateVerticesData(kind, data, updateExtends);
  14656. }
  14657. else {
  14658. this.makeGeometryUnique();
  14659. this.updateVerticesData(kind, data, updateExtends, false);
  14660. }
  14661. };
  14662. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14663. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14664. if (!this._geometry) {
  14665. return;
  14666. }
  14667. if (!makeItUnique) {
  14668. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14669. }
  14670. else {
  14671. this.makeGeometryUnique();
  14672. this.updateVerticesDataDirectly(kind, data, offset, false);
  14673. }
  14674. };
  14675. // Mesh positions update function :
  14676. // updates the mesh positions according to the positionFunction returned values.
  14677. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14678. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14679. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14680. if (computeNormals === void 0) { computeNormals = true; }
  14681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14682. positionFunction(positions);
  14683. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14684. if (computeNormals) {
  14685. var indices = this.getIndices();
  14686. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14687. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14688. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14689. }
  14690. };
  14691. Mesh.prototype.makeGeometryUnique = function () {
  14692. if (!this._geometry) {
  14693. return;
  14694. }
  14695. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14696. geometry.applyToMesh(this);
  14697. };
  14698. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14699. if (!this._geometry) {
  14700. var vertexData = new BABYLON.VertexData();
  14701. vertexData.indices = indices;
  14702. var scene = this.getScene();
  14703. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14704. }
  14705. else {
  14706. this._geometry.setIndices(indices, totalVertices);
  14707. }
  14708. };
  14709. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14710. var engine = this.getScene().getEngine();
  14711. // Wireframe
  14712. var indexToBind;
  14713. switch (fillMode) {
  14714. case BABYLON.Material.PointFillMode:
  14715. indexToBind = null;
  14716. break;
  14717. case BABYLON.Material.WireFrameFillMode:
  14718. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14719. break;
  14720. default:
  14721. case BABYLON.Material.TriangleFillMode:
  14722. indexToBind = this._geometry.getIndexBuffer();
  14723. break;
  14724. }
  14725. // VBOs
  14726. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14727. };
  14728. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14729. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14730. return;
  14731. }
  14732. var engine = this.getScene().getEngine();
  14733. // Draw order
  14734. switch (fillMode) {
  14735. case BABYLON.Material.PointFillMode:
  14736. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14737. break;
  14738. case BABYLON.Material.WireFrameFillMode:
  14739. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14740. break;
  14741. default:
  14742. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14743. }
  14744. };
  14745. Mesh.prototype.registerBeforeRender = function (func) {
  14746. this._onBeforeRenderCallbacks.push(func);
  14747. };
  14748. Mesh.prototype.unregisterBeforeRender = function (func) {
  14749. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14750. if (index > -1) {
  14751. this._onBeforeRenderCallbacks.splice(index, 1);
  14752. }
  14753. };
  14754. Mesh.prototype.registerAfterRender = function (func) {
  14755. this._onAfterRenderCallbacks.push(func);
  14756. };
  14757. Mesh.prototype.unregisterAfterRender = function (func) {
  14758. var index = this._onAfterRenderCallbacks.indexOf(func);
  14759. if (index > -1) {
  14760. this._onAfterRenderCallbacks.splice(index, 1);
  14761. }
  14762. };
  14763. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14764. var scene = this.getScene();
  14765. this._batchCache.mustReturn = false;
  14766. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14767. this._batchCache.visibleInstances[subMeshId] = null;
  14768. if (this._visibleInstances) {
  14769. var currentRenderId = scene.getRenderId();
  14770. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14771. var selfRenderId = this._renderId;
  14772. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14773. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14774. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14775. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14776. }
  14777. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14778. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14779. this._batchCache.mustReturn = true;
  14780. return this._batchCache;
  14781. }
  14782. if (currentRenderId !== selfRenderId) {
  14783. this._batchCache.renderSelf[subMeshId] = false;
  14784. }
  14785. }
  14786. this._renderIdForInstances[subMeshId] = currentRenderId;
  14787. }
  14788. return this._batchCache;
  14789. };
  14790. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14791. var visibleInstances = batch.visibleInstances[subMesh._id];
  14792. var matricesCount = visibleInstances.length + 1;
  14793. var bufferSize = matricesCount * 16 * 4;
  14794. while (this._instancesBufferSize < bufferSize) {
  14795. this._instancesBufferSize *= 2;
  14796. }
  14797. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14798. if (this._worldMatricesInstancesBuffer) {
  14799. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14800. }
  14801. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14802. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14803. }
  14804. var offset = 0;
  14805. var instancesCount = 0;
  14806. var world = this.getWorldMatrix();
  14807. if (batch.renderSelf[subMesh._id]) {
  14808. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14809. offset += 16;
  14810. instancesCount++;
  14811. }
  14812. if (visibleInstances) {
  14813. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14814. var instance = visibleInstances[instanceIndex];
  14815. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14816. offset += 16;
  14817. instancesCount++;
  14818. }
  14819. }
  14820. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14821. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14822. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14823. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14824. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14825. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14826. this._draw(subMesh, fillMode, instancesCount);
  14827. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14828. };
  14829. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14830. var scene = this.getScene();
  14831. var engine = scene.getEngine();
  14832. if (hardwareInstancedRendering) {
  14833. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14834. }
  14835. else {
  14836. if (batch.renderSelf[subMesh._id]) {
  14837. // Draw
  14838. if (onBeforeDraw) {
  14839. onBeforeDraw(false, this.getWorldMatrix());
  14840. }
  14841. this._draw(subMesh, fillMode);
  14842. }
  14843. if (batch.visibleInstances[subMesh._id]) {
  14844. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14845. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14846. // World
  14847. var world = instance.getWorldMatrix();
  14848. if (onBeforeDraw) {
  14849. onBeforeDraw(true, world);
  14850. }
  14851. // Draw
  14852. this._draw(subMesh, fillMode);
  14853. }
  14854. }
  14855. }
  14856. };
  14857. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14858. var scene = this.getScene();
  14859. // Managing instances
  14860. var batch = this._getInstancesRenderList(subMesh._id);
  14861. if (batch.mustReturn) {
  14862. return;
  14863. }
  14864. // Checking geometry state
  14865. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14866. return;
  14867. }
  14868. var callbackIndex;
  14869. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14870. this._onBeforeRenderCallbacks[callbackIndex](this);
  14871. }
  14872. var engine = scene.getEngine();
  14873. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14874. // Material
  14875. var effectiveMaterial = subMesh.getMaterial();
  14876. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14877. return;
  14878. }
  14879. // Outline - step 1
  14880. var savedDepthWrite = engine.getDepthWrite();
  14881. if (this.renderOutline) {
  14882. engine.setDepthWrite(false);
  14883. scene.getOutlineRenderer().render(subMesh, batch);
  14884. engine.setDepthWrite(savedDepthWrite);
  14885. }
  14886. effectiveMaterial._preBind();
  14887. var effect = effectiveMaterial.getEffect();
  14888. // Bind
  14889. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14890. this._bind(subMesh, effect, fillMode);
  14891. var world = this.getWorldMatrix();
  14892. effectiveMaterial.bind(world, this);
  14893. // Alpha mode
  14894. if (enableAlphaMode) {
  14895. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14896. }
  14897. // Draw
  14898. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14899. if (isInstance) {
  14900. effectiveMaterial.bindOnlyWorldMatrix(world);
  14901. }
  14902. });
  14903. // Unbind
  14904. effectiveMaterial.unbind();
  14905. // Outline - step 2
  14906. if (this.renderOutline && savedDepthWrite) {
  14907. engine.setDepthWrite(true);
  14908. engine.setColorWrite(false);
  14909. scene.getOutlineRenderer().render(subMesh, batch);
  14910. engine.setColorWrite(true);
  14911. }
  14912. // Overlay
  14913. if (this.renderOverlay) {
  14914. var currentMode = engine.getAlphaMode();
  14915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14916. scene.getOutlineRenderer().render(subMesh, batch, true);
  14917. engine.setAlphaMode(currentMode);
  14918. }
  14919. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14920. this._onAfterRenderCallbacks[callbackIndex](this);
  14921. }
  14922. };
  14923. Mesh.prototype.getEmittedParticleSystems = function () {
  14924. var results = new Array();
  14925. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14926. var particleSystem = this.getScene().particleSystems[index];
  14927. if (particleSystem.emitter === this) {
  14928. results.push(particleSystem);
  14929. }
  14930. }
  14931. return results;
  14932. };
  14933. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14934. var results = new Array();
  14935. var descendants = this.getDescendants();
  14936. descendants.push(this);
  14937. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14938. var particleSystem = this.getScene().particleSystems[index];
  14939. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14940. results.push(particleSystem);
  14941. }
  14942. }
  14943. return results;
  14944. };
  14945. Mesh.prototype.getChildren = function () {
  14946. var results = [];
  14947. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14948. var mesh = this.getScene().meshes[index];
  14949. if (mesh.parent === this) {
  14950. results.push(mesh);
  14951. }
  14952. }
  14953. return results;
  14954. };
  14955. Mesh.prototype._checkDelayState = function () {
  14956. var _this = this;
  14957. var that = this;
  14958. var scene = this.getScene();
  14959. if (this._geometry) {
  14960. this._geometry.load(scene);
  14961. }
  14962. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14963. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14964. scene._addPendingData(that);
  14965. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14966. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14967. if (data instanceof ArrayBuffer) {
  14968. _this._delayLoadingFunction(data, _this);
  14969. }
  14970. else {
  14971. _this._delayLoadingFunction(JSON.parse(data), _this);
  14972. }
  14973. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14974. scene._removePendingData(_this);
  14975. }, function () { }, scene.database, getBinaryData);
  14976. }
  14977. };
  14978. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14979. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14980. return false;
  14981. }
  14982. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14983. return false;
  14984. }
  14985. this._checkDelayState();
  14986. return true;
  14987. };
  14988. Mesh.prototype.setMaterialByID = function (id) {
  14989. var materials = this.getScene().materials;
  14990. var index;
  14991. for (index = 0; index < materials.length; index++) {
  14992. if (materials[index].id === id) {
  14993. this.material = materials[index];
  14994. return;
  14995. }
  14996. }
  14997. // Multi
  14998. var multiMaterials = this.getScene().multiMaterials;
  14999. for (index = 0; index < multiMaterials.length; index++) {
  15000. if (multiMaterials[index].id === id) {
  15001. this.material = multiMaterials[index];
  15002. return;
  15003. }
  15004. }
  15005. };
  15006. Mesh.prototype.getAnimatables = function () {
  15007. var results = [];
  15008. if (this.material) {
  15009. results.push(this.material);
  15010. }
  15011. if (this.skeleton) {
  15012. results.push(this.skeleton);
  15013. }
  15014. return results;
  15015. };
  15016. // Geometry
  15017. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15018. // Position
  15019. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15020. return;
  15021. }
  15022. this._resetPointsArrayCache();
  15023. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15024. var temp = [];
  15025. var index;
  15026. for (index = 0; index < data.length; index += 3) {
  15027. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15028. }
  15029. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15030. // Normals
  15031. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15032. return;
  15033. }
  15034. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15035. temp = [];
  15036. for (index = 0; index < data.length; index += 3) {
  15037. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15038. }
  15039. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15040. // flip faces?
  15041. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15042. this.flipFaces();
  15043. }
  15044. };
  15045. // Will apply current transform to mesh and reset world matrix
  15046. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15047. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15048. this.scaling.copyFromFloats(1, 1, 1);
  15049. this.position.copyFromFloats(0, 0, 0);
  15050. this.rotation.copyFromFloats(0, 0, 0);
  15051. //only if quaternion is already set
  15052. if (this.rotationQuaternion) {
  15053. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15054. }
  15055. this._worldMatrix = BABYLON.Matrix.Identity();
  15056. };
  15057. // Cache
  15058. Mesh.prototype._resetPointsArrayCache = function () {
  15059. this._positions = null;
  15060. };
  15061. Mesh.prototype._generatePointsArray = function () {
  15062. if (this._positions)
  15063. return true;
  15064. this._positions = [];
  15065. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15066. if (!data) {
  15067. return false;
  15068. }
  15069. for (var index = 0; index < data.length; index += 3) {
  15070. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15071. }
  15072. return true;
  15073. };
  15074. // Clone
  15075. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15076. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15077. };
  15078. // Dispose
  15079. Mesh.prototype.dispose = function (doNotRecurse) {
  15080. if (this._geometry) {
  15081. this._geometry.releaseForMesh(this, true);
  15082. }
  15083. // Instances
  15084. if (this._worldMatricesInstancesBuffer) {
  15085. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15086. this._worldMatricesInstancesBuffer = null;
  15087. }
  15088. while (this.instances.length) {
  15089. this.instances[0].dispose();
  15090. }
  15091. _super.prototype.dispose.call(this, doNotRecurse);
  15092. };
  15093. // Geometric tools
  15094. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15095. var _this = this;
  15096. var scene = this.getScene();
  15097. var onload = function (img) {
  15098. // Getting height map data
  15099. var canvas = document.createElement("canvas");
  15100. var context = canvas.getContext("2d");
  15101. var heightMapWidth = img.width;
  15102. var heightMapHeight = img.height;
  15103. canvas.width = heightMapWidth;
  15104. canvas.height = heightMapHeight;
  15105. context.drawImage(img, 0, 0);
  15106. // Create VertexData from map data
  15107. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15108. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15109. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15110. //execute success callback, if set
  15111. if (onSuccess) {
  15112. onSuccess(_this);
  15113. }
  15114. };
  15115. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15116. };
  15117. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15119. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15120. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15121. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15122. return;
  15123. }
  15124. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15125. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15126. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15127. var position = BABYLON.Vector3.Zero();
  15128. var normal = BABYLON.Vector3.Zero();
  15129. var uv = BABYLON.Vector2.Zero();
  15130. for (var index = 0; index < positions.length; index += 3) {
  15131. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15132. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15133. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15134. // Compute height
  15135. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15136. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15137. var pos = (u + v * heightMapWidth) * 4;
  15138. var r = buffer[pos] / 255.0;
  15139. var g = buffer[pos + 1] / 255.0;
  15140. var b = buffer[pos + 2] / 255.0;
  15141. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15142. normal.normalize();
  15143. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15144. position = position.add(normal);
  15145. position.toArray(positions, index);
  15146. }
  15147. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15148. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15149. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15150. };
  15151. Mesh.prototype.convertToFlatShadedMesh = function () {
  15152. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15153. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15154. var kinds = this.getVerticesDataKinds();
  15155. var vbs = [];
  15156. var data = [];
  15157. var newdata = [];
  15158. var updatableNormals = false;
  15159. var kindIndex;
  15160. var kind;
  15161. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15162. kind = kinds[kindIndex];
  15163. var vertexBuffer = this.getVertexBuffer(kind);
  15164. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15165. updatableNormals = vertexBuffer.isUpdatable();
  15166. kinds.splice(kindIndex, 1);
  15167. kindIndex--;
  15168. continue;
  15169. }
  15170. vbs[kind] = vertexBuffer;
  15171. data[kind] = vbs[kind].getData();
  15172. newdata[kind] = [];
  15173. }
  15174. // Save previous submeshes
  15175. var previousSubmeshes = this.subMeshes.slice(0);
  15176. var indices = this.getIndices();
  15177. var totalIndices = this.getTotalIndices();
  15178. // Generating unique vertices per face
  15179. var index;
  15180. for (index = 0; index < totalIndices; index++) {
  15181. var vertexIndex = indices[index];
  15182. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15183. kind = kinds[kindIndex];
  15184. var stride = vbs[kind].getStrideSize();
  15185. for (var offset = 0; offset < stride; offset++) {
  15186. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15187. }
  15188. }
  15189. }
  15190. // Updating faces & normal
  15191. var normals = [];
  15192. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15193. for (index = 0; index < totalIndices; index += 3) {
  15194. indices[index] = index;
  15195. indices[index + 1] = index + 1;
  15196. indices[index + 2] = index + 2;
  15197. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15198. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15199. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15200. var p1p2 = p1.subtract(p2);
  15201. var p3p2 = p3.subtract(p2);
  15202. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15203. // Store same normals for every vertex
  15204. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15205. normals.push(normal.x);
  15206. normals.push(normal.y);
  15207. normals.push(normal.z);
  15208. }
  15209. }
  15210. this.setIndices(indices);
  15211. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15212. // Updating vertex buffers
  15213. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15214. kind = kinds[kindIndex];
  15215. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15216. }
  15217. // Updating submeshes
  15218. this.releaseSubMeshes();
  15219. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15220. var previousOne = previousSubmeshes[submeshIndex];
  15221. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15222. }
  15223. this.synchronizeInstances();
  15224. };
  15225. // will inverse faces orientations, and invert normals too if specified
  15226. Mesh.prototype.flipFaces = function (flipNormals) {
  15227. if (flipNormals === void 0) { flipNormals = false; }
  15228. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15229. var i;
  15230. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15231. for (i = 0; i < vertex_data.normals.length; i++) {
  15232. vertex_data.normals[i] *= -1;
  15233. }
  15234. }
  15235. var temp;
  15236. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15237. // reassign indices
  15238. temp = vertex_data.indices[i + 1];
  15239. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15240. vertex_data.indices[i + 2] = temp;
  15241. }
  15242. vertex_data.applyToMesh(this);
  15243. };
  15244. // Instances
  15245. Mesh.prototype.createInstance = function (name) {
  15246. return new BABYLON.InstancedMesh(name, this);
  15247. };
  15248. Mesh.prototype.synchronizeInstances = function () {
  15249. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15250. var instance = this.instances[instanceIndex];
  15251. instance._syncSubMeshes();
  15252. }
  15253. };
  15254. /**
  15255. * Simplify the mesh according to the given array of settings.
  15256. * Function will return immediately and will simplify async.
  15257. * @param settings a collection of simplification settings.
  15258. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15259. * @param type the type of simplification to run.
  15260. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15261. */
  15262. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15263. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15264. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15265. this.getScene().simplificationQueue.addTask({
  15266. settings: settings,
  15267. parallelProcessing: parallelProcessing,
  15268. mesh: this,
  15269. simplificationType: simplificationType,
  15270. successCallback: successCallback
  15271. });
  15272. };
  15273. /**
  15274. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15275. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15276. * This should be used together with the simplification to avoid disappearing triangles.
  15277. * @param successCallback an optional success callback to be called after the optimization finished.
  15278. */
  15279. Mesh.prototype.optimizeIndices = function (successCallback) {
  15280. var _this = this;
  15281. var indices = this.getIndices();
  15282. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15283. var vectorPositions = [];
  15284. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15285. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15286. }
  15287. var dupes = [];
  15288. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15289. var realPos = vectorPositions.length - 1 - iteration;
  15290. var testedPosition = vectorPositions[realPos];
  15291. for (var j = 0; j < realPos; ++j) {
  15292. var againstPosition = vectorPositions[j];
  15293. if (testedPosition.equals(againstPosition)) {
  15294. dupes[realPos] = j;
  15295. break;
  15296. }
  15297. }
  15298. }, function () {
  15299. for (var i = 0; i < indices.length; ++i) {
  15300. indices[i] = dupes[indices[i]] || indices[i];
  15301. }
  15302. //indices are now reordered
  15303. var originalSubMeshes = _this.subMeshes.slice(0);
  15304. _this.setIndices(indices);
  15305. _this.subMeshes = originalSubMeshes;
  15306. if (successCallback) {
  15307. successCallback(_this);
  15308. }
  15309. });
  15310. };
  15311. // Statics
  15312. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15313. var mesh = new Mesh(parsedMesh.name, scene);
  15314. mesh.id = parsedMesh.id;
  15315. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15316. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15317. if (parsedMesh.rotationQuaternion) {
  15318. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15319. }
  15320. else if (parsedMesh.rotation) {
  15321. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15322. }
  15323. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15324. if (parsedMesh.localMatrix) {
  15325. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15326. }
  15327. else if (parsedMesh.pivotMatrix) {
  15328. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15329. }
  15330. mesh.setEnabled(parsedMesh.isEnabled);
  15331. mesh.isVisible = parsedMesh.isVisible;
  15332. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15333. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15334. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15335. if (parsedMesh.applyFog !== undefined) {
  15336. mesh.applyFog = parsedMesh.applyFog;
  15337. }
  15338. if (parsedMesh.pickable !== undefined) {
  15339. mesh.isPickable = parsedMesh.pickable;
  15340. }
  15341. if (parsedMesh.alphaIndex !== undefined) {
  15342. mesh.alphaIndex = parsedMesh.alphaIndex;
  15343. }
  15344. mesh.receiveShadows = parsedMesh.receiveShadows;
  15345. mesh.billboardMode = parsedMesh.billboardMode;
  15346. if (parsedMesh.visibility !== undefined) {
  15347. mesh.visibility = parsedMesh.visibility;
  15348. }
  15349. mesh.checkCollisions = parsedMesh.checkCollisions;
  15350. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15351. // freezeWorldMatrix
  15352. if (parsedMesh.freezeWorldMatrix) {
  15353. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15354. }
  15355. // Parent
  15356. if (parsedMesh.parentId) {
  15357. mesh._waitingParentId = parsedMesh.parentId;
  15358. }
  15359. // Actions
  15360. if (parsedMesh.actions !== undefined) {
  15361. mesh._waitingActions = parsedMesh.actions;
  15362. }
  15363. // Geometry
  15364. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15365. if (parsedMesh.delayLoadingFile) {
  15366. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15367. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15368. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15369. if (parsedMesh._binaryInfo) {
  15370. mesh._binaryInfo = parsedMesh._binaryInfo;
  15371. }
  15372. mesh._delayInfo = [];
  15373. if (parsedMesh.hasUVs) {
  15374. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15375. }
  15376. if (parsedMesh.hasUVs2) {
  15377. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15378. }
  15379. if (parsedMesh.hasUVs3) {
  15380. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15381. }
  15382. if (parsedMesh.hasUVs4) {
  15383. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15384. }
  15385. if (parsedMesh.hasUVs5) {
  15386. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15387. }
  15388. if (parsedMesh.hasUVs6) {
  15389. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15390. }
  15391. if (parsedMesh.hasColors) {
  15392. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15393. }
  15394. if (parsedMesh.hasMatricesIndices) {
  15395. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15396. }
  15397. if (parsedMesh.hasMatricesWeights) {
  15398. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15399. }
  15400. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15401. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15402. mesh._checkDelayState();
  15403. }
  15404. }
  15405. else {
  15406. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15407. }
  15408. // Material
  15409. if (parsedMesh.materialId) {
  15410. mesh.setMaterialByID(parsedMesh.materialId);
  15411. }
  15412. else {
  15413. mesh.material = null;
  15414. }
  15415. // Skeleton
  15416. if (parsedMesh.skeletonId > -1) {
  15417. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15418. if (parsedMesh.numBoneInfluencers) {
  15419. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15420. }
  15421. }
  15422. // Physics
  15423. if (parsedMesh.physicsImpostor) {
  15424. if (!scene.isPhysicsEnabled()) {
  15425. scene.enablePhysics();
  15426. }
  15427. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15428. }
  15429. // Animations
  15430. if (parsedMesh.animations) {
  15431. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15432. var parsedAnimation = parsedMesh.animations[animationIndex];
  15433. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15434. }
  15435. }
  15436. if (parsedMesh.autoAnimate) {
  15437. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15438. }
  15439. // Layer Mask
  15440. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15441. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15442. }
  15443. else {
  15444. mesh.layerMask = 0x0FFFFFFF;
  15445. }
  15446. // Instances
  15447. if (parsedMesh.instances) {
  15448. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15449. var parsedInstance = parsedMesh.instances[index];
  15450. var instance = mesh.createInstance(parsedInstance.name);
  15451. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15452. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15453. if (parsedInstance.rotationQuaternion) {
  15454. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15455. }
  15456. else if (parsedInstance.rotation) {
  15457. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15458. }
  15459. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15460. instance.checkCollisions = mesh.checkCollisions;
  15461. if (parsedMesh.animations) {
  15462. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15463. parsedAnimation = parsedMesh.animations[animationIndex];
  15464. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15465. }
  15466. }
  15467. }
  15468. }
  15469. return mesh;
  15470. };
  15471. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15472. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15473. pathArray: pathArray,
  15474. closeArray: closeArray,
  15475. closePath: closePath,
  15476. offset: offset,
  15477. updatable: updatable,
  15478. sideOrientation: sideOrientation,
  15479. instance: instance
  15480. }, scene);
  15481. };
  15482. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15483. var options = {
  15484. radius: radius,
  15485. tessellation: tessellation,
  15486. sideOrientation: sideOrientation,
  15487. updatable: updatable
  15488. };
  15489. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15490. };
  15491. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15492. var options = {
  15493. size: size,
  15494. sideOrientation: sideOrientation,
  15495. updatable: updatable
  15496. };
  15497. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15498. };
  15499. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15500. var options = {
  15501. segments: segments,
  15502. diameterX: diameter,
  15503. diameterY: diameter,
  15504. diameterZ: diameter,
  15505. sideOrientation: sideOrientation,
  15506. updatable: updatable
  15507. };
  15508. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15509. };
  15510. // Cylinder and cone
  15511. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15512. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15513. if (scene !== undefined) {
  15514. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15515. updatable = scene;
  15516. }
  15517. scene = subdivisions;
  15518. subdivisions = 1;
  15519. }
  15520. var options = {
  15521. height: height,
  15522. diameterTop: diameterTop,
  15523. diameterBottom: diameterBottom,
  15524. tessellation: tessellation,
  15525. subdivisions: subdivisions,
  15526. sideOrientation: sideOrientation,
  15527. updatable: updatable
  15528. };
  15529. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15530. };
  15531. // Torus (Code from SharpDX.org)
  15532. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15533. var options = {
  15534. diameter: diameter,
  15535. thickness: thickness,
  15536. tessellation: tessellation,
  15537. sideOrientation: sideOrientation,
  15538. updatable: updatable
  15539. };
  15540. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15541. };
  15542. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15543. var options = {
  15544. radius: radius,
  15545. tube: tube,
  15546. radialSegments: radialSegments,
  15547. tubularSegments: tubularSegments,
  15548. p: p,
  15549. q: q,
  15550. sideOrientation: sideOrientation,
  15551. updatable: updatable
  15552. };
  15553. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15554. };
  15555. // Lines
  15556. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15557. var options = {
  15558. points: points,
  15559. updatable: updatable,
  15560. instance: instance
  15561. };
  15562. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15563. };
  15564. // Dashed Lines
  15565. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15566. var options = {
  15567. points: points,
  15568. dashSize: dashSize,
  15569. gapSize: gapSize,
  15570. dashNb: dashNb,
  15571. updatable: updatable
  15572. };
  15573. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15574. };
  15575. // Extrusion
  15576. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15577. var options = {
  15578. shape: shape,
  15579. path: path,
  15580. scale: scale,
  15581. rotation: rotation,
  15582. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15583. sideOrientation: sideOrientation,
  15584. instance: instance,
  15585. updatable: updatable
  15586. };
  15587. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15588. };
  15589. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15590. var options = {
  15591. shape: shape,
  15592. path: path,
  15593. scaleFunction: scaleFunction,
  15594. rotationFunction: rotationFunction,
  15595. ribbonCloseArray: ribbonCloseArray,
  15596. ribbonClosePath: ribbonClosePath,
  15597. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15598. sideOrientation: sideOrientation,
  15599. instance: instance,
  15600. updatable: updatable
  15601. };
  15602. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15603. };
  15604. // Lathe
  15605. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15606. var options = {
  15607. shape: shape,
  15608. radius: radius,
  15609. tessellation: tessellation,
  15610. sideOrientation: sideOrientation,
  15611. updatable: updatable
  15612. };
  15613. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15614. };
  15615. // Plane & ground
  15616. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15617. var options = {
  15618. size: size,
  15619. width: size,
  15620. height: size,
  15621. sideOrientation: sideOrientation,
  15622. updatable: updatable
  15623. };
  15624. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15625. };
  15626. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15627. var options = {
  15628. width: width,
  15629. height: height,
  15630. subdivisions: subdivisions,
  15631. updatable: updatable
  15632. };
  15633. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15634. };
  15635. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15636. var options = {
  15637. xmin: xmin,
  15638. zmin: zmin,
  15639. xmax: xmax,
  15640. zmax: zmax,
  15641. subdivisions: subdivisions,
  15642. precision: precision,
  15643. updatable: updatable
  15644. };
  15645. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15646. };
  15647. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15648. var options = {
  15649. width: width,
  15650. height: height,
  15651. subdivisions: subdivisions,
  15652. minHeight: minHeight,
  15653. maxHeight: maxHeight,
  15654. updatable: updatable,
  15655. onReady: onReady
  15656. };
  15657. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15658. };
  15659. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15660. var options = {
  15661. path: path,
  15662. radius: radius,
  15663. tessellation: tessellation,
  15664. radiusFunction: radiusFunction,
  15665. arc: 1,
  15666. cap: cap,
  15667. updatable: updatable,
  15668. sideOrientation: sideOrientation,
  15669. instance: instance
  15670. };
  15671. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15672. };
  15673. Mesh.CreatePolyhedron = function (name, options, scene) {
  15674. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15675. };
  15676. Mesh.CreateIcoSphere = function (name, options, scene) {
  15677. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15678. };
  15679. // Decals
  15680. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15681. var options = {
  15682. position: position,
  15683. normal: normal,
  15684. size: size,
  15685. angle: angle
  15686. };
  15687. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15688. };
  15689. // Skeletons
  15690. /**
  15691. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15692. */
  15693. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15694. var source;
  15695. if (!this._sourcePositions) {
  15696. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15697. this._sourcePositions = new Float32Array(source);
  15698. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15699. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15700. }
  15701. }
  15702. return this._sourcePositions;
  15703. };
  15704. /**
  15705. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15706. */
  15707. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15708. var source;
  15709. if (!this._sourceNormals) {
  15710. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15711. this._sourceNormals = new Float32Array(source);
  15712. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15713. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15714. }
  15715. }
  15716. return this._sourceNormals;
  15717. };
  15718. /**
  15719. * Update the vertex buffers by applying transformation from the bones
  15720. * @param {skeleton} skeleton to apply
  15721. */
  15722. Mesh.prototype.applySkeleton = function (skeleton) {
  15723. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15724. return this;
  15725. }
  15726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15727. return this;
  15728. }
  15729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15730. return this;
  15731. }
  15732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15733. return this;
  15734. }
  15735. if (!this._sourcePositions) {
  15736. this.setPositionsForCPUSkinning();
  15737. }
  15738. if (!this._sourceNormals) {
  15739. this.setNormalsForCPUSkinning();
  15740. }
  15741. // positionsData checks for not being Float32Array will only pass at most once
  15742. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15743. if (!(positionsData instanceof Float32Array)) {
  15744. positionsData = new Float32Array(positionsData);
  15745. }
  15746. // normalsData checks for not being Float32Array will only pass at most once
  15747. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15748. if (!(normalsData instanceof Float32Array)) {
  15749. normalsData = new Float32Array(normalsData);
  15750. }
  15751. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15752. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15753. var needExtras = this.numBoneInfluencers > 4;
  15754. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15755. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15756. var skeletonMatrices = skeleton.getTransformMatrices();
  15757. var tempVector3 = BABYLON.Vector3.Zero();
  15758. var finalMatrix = new BABYLON.Matrix();
  15759. var tempMatrix = new BABYLON.Matrix();
  15760. var matWeightIdx = 0;
  15761. var inf;
  15762. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15763. var weight;
  15764. for (inf = 0; inf < 4; inf++) {
  15765. weight = matricesWeightsData[matWeightIdx + inf];
  15766. if (weight > 0) {
  15767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15768. finalMatrix.addToSelf(tempMatrix);
  15769. }
  15770. else
  15771. break;
  15772. }
  15773. if (needExtras) {
  15774. for (inf = 0; inf < 4; inf++) {
  15775. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15776. if (weight > 0) {
  15777. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15778. finalMatrix.addToSelf(tempMatrix);
  15779. }
  15780. else
  15781. break;
  15782. }
  15783. }
  15784. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15785. tempVector3.toArray(positionsData, index);
  15786. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15787. tempVector3.toArray(normalsData, index);
  15788. finalMatrix.reset();
  15789. }
  15790. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15791. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15792. return this;
  15793. };
  15794. // Tools
  15795. Mesh.MinMax = function (meshes) {
  15796. var minVector = null;
  15797. var maxVector = null;
  15798. for (var i in meshes) {
  15799. var mesh = meshes[i];
  15800. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15801. if (!minVector) {
  15802. minVector = boundingBox.minimumWorld;
  15803. maxVector = boundingBox.maximumWorld;
  15804. continue;
  15805. }
  15806. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15807. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15808. }
  15809. return {
  15810. min: minVector,
  15811. max: maxVector
  15812. };
  15813. };
  15814. Mesh.Center = function (meshesOrMinMaxVector) {
  15815. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15816. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15817. };
  15818. /**
  15819. * Merge the array of meshes into a single mesh for performance reasons.
  15820. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15821. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15822. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15823. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15824. */
  15825. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15826. if (disposeSource === void 0) { disposeSource = true; }
  15827. var index;
  15828. if (!allow32BitsIndices) {
  15829. var totalVertices = 0;
  15830. // Counting vertices
  15831. for (index = 0; index < meshes.length; index++) {
  15832. if (meshes[index]) {
  15833. totalVertices += meshes[index].getTotalVertices();
  15834. if (totalVertices > 65536) {
  15835. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15836. return null;
  15837. }
  15838. }
  15839. }
  15840. }
  15841. // Merge
  15842. var vertexData;
  15843. var otherVertexData;
  15844. var source;
  15845. for (index = 0; index < meshes.length; index++) {
  15846. if (meshes[index]) {
  15847. meshes[index].computeWorldMatrix(true);
  15848. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15849. otherVertexData.transform(meshes[index].getWorldMatrix());
  15850. if (vertexData) {
  15851. vertexData.merge(otherVertexData);
  15852. }
  15853. else {
  15854. vertexData = otherVertexData;
  15855. source = meshes[index];
  15856. }
  15857. }
  15858. }
  15859. if (!meshSubclass) {
  15860. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15861. }
  15862. vertexData.applyToMesh(meshSubclass);
  15863. // Setting properties
  15864. meshSubclass.material = source.material;
  15865. meshSubclass.checkCollisions = source.checkCollisions;
  15866. // Cleaning
  15867. if (disposeSource) {
  15868. for (index = 0; index < meshes.length; index++) {
  15869. if (meshes[index]) {
  15870. meshes[index].dispose();
  15871. }
  15872. }
  15873. }
  15874. return meshSubclass;
  15875. };
  15876. // Consts
  15877. Mesh._FRONTSIDE = 0;
  15878. Mesh._BACKSIDE = 1;
  15879. Mesh._DOUBLESIDE = 2;
  15880. Mesh._DEFAULTSIDE = 0;
  15881. Mesh._NO_CAP = 0;
  15882. Mesh._CAP_START = 1;
  15883. Mesh._CAP_END = 2;
  15884. Mesh._CAP_ALL = 3;
  15885. return Mesh;
  15886. })(BABYLON.AbstractMesh);
  15887. BABYLON.Mesh = Mesh;
  15888. })(BABYLON || (BABYLON = {}));
  15889. var BABYLON;
  15890. (function (BABYLON) {
  15891. var SubMesh = (function () {
  15892. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15893. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15894. this.materialIndex = materialIndex;
  15895. this.verticesStart = verticesStart;
  15896. this.verticesCount = verticesCount;
  15897. this.indexStart = indexStart;
  15898. this.indexCount = indexCount;
  15899. this._renderId = 0;
  15900. this._mesh = mesh;
  15901. this._renderingMesh = renderingMesh || mesh;
  15902. mesh.subMeshes.push(this);
  15903. this._trianglePlanes = [];
  15904. this._id = mesh.subMeshes.length - 1;
  15905. if (createBoundingBox) {
  15906. this.refreshBoundingInfo();
  15907. mesh.computeWorldMatrix(true);
  15908. }
  15909. }
  15910. SubMesh.prototype.getBoundingInfo = function () {
  15911. return this._boundingInfo;
  15912. };
  15913. SubMesh.prototype.getMesh = function () {
  15914. return this._mesh;
  15915. };
  15916. SubMesh.prototype.getRenderingMesh = function () {
  15917. return this._renderingMesh;
  15918. };
  15919. SubMesh.prototype.getMaterial = function () {
  15920. var rootMaterial = this._renderingMesh.material;
  15921. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15922. var multiMaterial = rootMaterial;
  15923. return multiMaterial.getSubMaterial(this.materialIndex);
  15924. }
  15925. if (!rootMaterial) {
  15926. return this._mesh.getScene().defaultMaterial;
  15927. }
  15928. return rootMaterial;
  15929. };
  15930. // Methods
  15931. SubMesh.prototype.refreshBoundingInfo = function () {
  15932. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15933. if (!data) {
  15934. this._boundingInfo = this._mesh._boundingInfo;
  15935. return;
  15936. }
  15937. var indices = this._renderingMesh.getIndices();
  15938. var extend;
  15939. //is this the only submesh?
  15940. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15941. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15942. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15943. }
  15944. else {
  15945. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15946. }
  15947. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15948. };
  15949. SubMesh.prototype._checkCollision = function (collider) {
  15950. return this._boundingInfo._checkCollision(collider);
  15951. };
  15952. SubMesh.prototype.updateBoundingInfo = function (world) {
  15953. if (!this._boundingInfo) {
  15954. this.refreshBoundingInfo();
  15955. }
  15956. this._boundingInfo._update(world);
  15957. };
  15958. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15959. return this._boundingInfo.isInFrustum(frustumPlanes);
  15960. };
  15961. SubMesh.prototype.render = function (enableAlphaMode) {
  15962. this._renderingMesh.render(this, enableAlphaMode);
  15963. };
  15964. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15965. if (!this._linesIndexBuffer) {
  15966. var linesIndices = [];
  15967. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15968. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15969. }
  15970. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15971. this.linesIndexCount = linesIndices.length;
  15972. }
  15973. return this._linesIndexBuffer;
  15974. };
  15975. SubMesh.prototype.canIntersects = function (ray) {
  15976. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15977. };
  15978. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15979. var intersectInfo = null;
  15980. // Triangles test
  15981. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15982. var p0 = positions[indices[index]];
  15983. var p1 = positions[indices[index + 1]];
  15984. var p2 = positions[indices[index + 2]];
  15985. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15986. if (currentIntersectInfo) {
  15987. if (currentIntersectInfo.distance < 0) {
  15988. continue;
  15989. }
  15990. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15991. intersectInfo = currentIntersectInfo;
  15992. intersectInfo.faceId = index / 3;
  15993. if (fastCheck) {
  15994. break;
  15995. }
  15996. }
  15997. }
  15998. }
  15999. return intersectInfo;
  16000. };
  16001. // Clone
  16002. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16003. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16004. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16005. return result;
  16006. };
  16007. // Dispose
  16008. SubMesh.prototype.dispose = function () {
  16009. if (this._linesIndexBuffer) {
  16010. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16011. this._linesIndexBuffer = null;
  16012. }
  16013. // Remove from mesh
  16014. var index = this._mesh.subMeshes.indexOf(this);
  16015. this._mesh.subMeshes.splice(index, 1);
  16016. };
  16017. // Statics
  16018. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16019. var minVertexIndex = Number.MAX_VALUE;
  16020. var maxVertexIndex = -Number.MAX_VALUE;
  16021. renderingMesh = renderingMesh || mesh;
  16022. var indices = renderingMesh.getIndices();
  16023. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16024. var vertexIndex = indices[index];
  16025. if (vertexIndex < minVertexIndex)
  16026. minVertexIndex = vertexIndex;
  16027. if (vertexIndex > maxVertexIndex)
  16028. maxVertexIndex = vertexIndex;
  16029. }
  16030. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16031. };
  16032. return SubMesh;
  16033. })();
  16034. BABYLON.SubMesh = SubMesh;
  16035. })(BABYLON || (BABYLON = {}));
  16036. var BABYLON;
  16037. (function (BABYLON) {
  16038. var MeshBuilder = (function () {
  16039. function MeshBuilder() {
  16040. }
  16041. MeshBuilder.CreateBox = function (name, options, scene) {
  16042. var box = new BABYLON.Mesh(name, scene);
  16043. var vertexData = BABYLON.VertexData.CreateBox(options);
  16044. vertexData.applyToMesh(box, options.updatable);
  16045. return box;
  16046. };
  16047. MeshBuilder.CreateSphere = function (name, options, scene) {
  16048. var sphere = new BABYLON.Mesh(name, scene);
  16049. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16050. vertexData.applyToMesh(sphere, options.updatable);
  16051. return sphere;
  16052. };
  16053. MeshBuilder.CreateDisc = function (name, options, scene) {
  16054. var disc = new BABYLON.Mesh(name, scene);
  16055. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16056. vertexData.applyToMesh(disc, options.updatable);
  16057. return disc;
  16058. };
  16059. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16060. var sphere = new BABYLON.Mesh(name, scene);
  16061. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16062. vertexData.applyToMesh(sphere, options.updatable);
  16063. return sphere;
  16064. };
  16065. ;
  16066. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16067. var pathArray = options.pathArray;
  16068. var closeArray = options.closeArray;
  16069. var closePath = options.closePath;
  16070. var offset = options.offset;
  16071. var sideOrientation = options.sideOrientation;
  16072. var instance = options.instance;
  16073. var updatable = options.updatable;
  16074. if (instance) {
  16075. // positionFunction : ribbon case
  16076. // only pathArray and sideOrientation parameters are taken into account for positions update
  16077. var positionFunction = function (positions) {
  16078. var minlg = pathArray[0].length;
  16079. var i = 0;
  16080. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16081. for (var si = 1; si <= ns; si++) {
  16082. for (var p = 0; p < pathArray.length; p++) {
  16083. var path = pathArray[p];
  16084. var l = path.length;
  16085. minlg = (minlg < l) ? minlg : l;
  16086. var j = 0;
  16087. while (j < minlg) {
  16088. positions[i] = path[j].x;
  16089. positions[i + 1] = path[j].y;
  16090. positions[i + 2] = path[j].z;
  16091. j++;
  16092. i += 3;
  16093. }
  16094. if (instance._closePath) {
  16095. positions[i] = path[0].x;
  16096. positions[i + 1] = path[0].y;
  16097. positions[i + 2] = path[0].z;
  16098. i += 3;
  16099. }
  16100. }
  16101. }
  16102. };
  16103. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16104. positionFunction(positions);
  16105. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16106. if (!(instance.areNormalsFrozen)) {
  16107. var indices = instance.getIndices();
  16108. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16109. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16110. if (instance._closePath) {
  16111. var indexFirst = 0;
  16112. var indexLast = 0;
  16113. for (var p = 0; p < pathArray.length; p++) {
  16114. indexFirst = instance._idx[p] * 3;
  16115. if (p + 1 < pathArray.length) {
  16116. indexLast = (instance._idx[p + 1] - 1) * 3;
  16117. }
  16118. else {
  16119. indexLast = normals.length - 3;
  16120. }
  16121. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16122. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16123. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16124. normals[indexLast] = normals[indexFirst];
  16125. normals[indexLast + 1] = normals[indexFirst + 1];
  16126. normals[indexLast + 2] = normals[indexFirst + 2];
  16127. }
  16128. }
  16129. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16130. }
  16131. return instance;
  16132. }
  16133. else {
  16134. var ribbon = new BABYLON.Mesh(name, scene);
  16135. ribbon.sideOrientation = sideOrientation;
  16136. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16137. if (closePath) {
  16138. ribbon._idx = vertexData._idx;
  16139. }
  16140. ribbon._closePath = closePath;
  16141. ribbon._closeArray = closeArray;
  16142. vertexData.applyToMesh(ribbon, updatable);
  16143. return ribbon;
  16144. }
  16145. };
  16146. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16147. var cylinder = new BABYLON.Mesh(name, scene);
  16148. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16149. vertexData.applyToMesh(cylinder, options.updatable);
  16150. return cylinder;
  16151. };
  16152. MeshBuilder.CreateTorus = function (name, options, scene) {
  16153. var torus = new BABYLON.Mesh(name, scene);
  16154. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16155. vertexData.applyToMesh(torus, options.updatable);
  16156. return torus;
  16157. };
  16158. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16159. var torusKnot = new BABYLON.Mesh(name, scene);
  16160. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16161. vertexData.applyToMesh(torusKnot, options.updatable);
  16162. return torusKnot;
  16163. };
  16164. MeshBuilder.CreateLines = function (name, options, scene) {
  16165. var instance = options.instance;
  16166. var points = options.points;
  16167. if (instance) {
  16168. var positionFunction = function (positions) {
  16169. var i = 0;
  16170. for (var p = 0; p < points.length; p++) {
  16171. positions[i] = points[p].x;
  16172. positions[i + 1] = points[p].y;
  16173. positions[i + 2] = points[p].z;
  16174. i += 3;
  16175. }
  16176. };
  16177. instance.updateMeshPositions(positionFunction, false);
  16178. return instance;
  16179. }
  16180. // lines creation
  16181. var lines = new BABYLON.LinesMesh(name, scene);
  16182. var vertexData = BABYLON.VertexData.CreateLines(options);
  16183. vertexData.applyToMesh(lines, options.updatable);
  16184. return lines;
  16185. };
  16186. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16187. var points = options.points;
  16188. var instance = options.instance;
  16189. var gapSize = options.gapSize;
  16190. var dashNb = options.dashNb;
  16191. var dashSize = options.dashSize;
  16192. if (instance) {
  16193. var positionFunction = function (positions) {
  16194. var curvect = BABYLON.Vector3.Zero();
  16195. var nbSeg = positions.length / 6;
  16196. var lg = 0;
  16197. var nb = 0;
  16198. var shft = 0;
  16199. var dashshft = 0;
  16200. var curshft = 0;
  16201. var p = 0;
  16202. var i = 0;
  16203. var j = 0;
  16204. for (i = 0; i < points.length - 1; i++) {
  16205. points[i + 1].subtractToRef(points[i], curvect);
  16206. lg += curvect.length();
  16207. }
  16208. shft = lg / nbSeg;
  16209. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16210. for (i = 0; i < points.length - 1; i++) {
  16211. points[i + 1].subtractToRef(points[i], curvect);
  16212. nb = Math.floor(curvect.length() / shft);
  16213. curvect.normalize();
  16214. j = 0;
  16215. while (j < nb && p < positions.length) {
  16216. curshft = shft * j;
  16217. positions[p] = points[i].x + curshft * curvect.x;
  16218. positions[p + 1] = points[i].y + curshft * curvect.y;
  16219. positions[p + 2] = points[i].z + curshft * curvect.z;
  16220. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16221. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16222. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16223. p += 6;
  16224. j++;
  16225. }
  16226. }
  16227. while (p < positions.length) {
  16228. positions[p] = points[i].x;
  16229. positions[p + 1] = points[i].y;
  16230. positions[p + 2] = points[i].z;
  16231. p += 3;
  16232. }
  16233. };
  16234. instance.updateMeshPositions(positionFunction, false);
  16235. return instance;
  16236. }
  16237. // dashed lines creation
  16238. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16239. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16240. vertexData.applyToMesh(dashedLines, options.updatable);
  16241. dashedLines.dashSize = dashSize;
  16242. dashedLines.gapSize = gapSize;
  16243. return dashedLines;
  16244. };
  16245. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16246. var path = options.path;
  16247. var shape = options.shape;
  16248. var scale = options.scale || 1;
  16249. var rotation = options.rotation || 0;
  16250. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16251. var updatable = options.updatable;
  16252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16253. var instance = options.instance;
  16254. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16255. };
  16256. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16257. var path = options.path;
  16258. var shape = options.shape;
  16259. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16260. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16261. var ribbonCloseArray = options.ribbonCloseArray || false;
  16262. var ribbonClosePath = options.ribbonClosePath || false;
  16263. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16264. var updatable = options.updatable;
  16265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16266. var instance = options.instance;
  16267. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16268. };
  16269. MeshBuilder.CreateLathe = function (name, options, scene) {
  16270. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16271. var closed = (options.closed === undefined) ? true : options.closed;
  16272. var shape = options.shape;
  16273. var radius = options.radius || 1;
  16274. var tessellation = options.tessellation || 64;
  16275. var updatable = options.updatable;
  16276. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16277. var pi2 = Math.PI * 2;
  16278. var shapeLathe = new Array();
  16279. // first rotatable point
  16280. var i = 0;
  16281. while (shape[i].x === 0) {
  16282. i++;
  16283. }
  16284. var pt = shape[i];
  16285. for (i = 0; i < shape.length; i++) {
  16286. shapeLathe.push(shape[i].subtract(pt));
  16287. }
  16288. // circle path
  16289. var step = pi2 / tessellation * arc;
  16290. var rotated;
  16291. var path = new Array();
  16292. ;
  16293. for (i = 0; i <= tessellation; i++) {
  16294. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16295. path.push(rotated);
  16296. }
  16297. if (closed) {
  16298. path.push(path[0]);
  16299. }
  16300. // extrusion
  16301. var scaleFunction = function () { return 1; };
  16302. var rotateFunction = function () { return 0; };
  16303. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  16304. return lathe;
  16305. };
  16306. MeshBuilder.CreatePlane = function (name, options, scene) {
  16307. var plane = new BABYLON.Mesh(name, scene);
  16308. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16309. vertexData.applyToMesh(plane, options.updatable);
  16310. if (options.sourcePlane) {
  16311. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16312. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16313. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16314. plane.rotate(vectorProduct, product);
  16315. }
  16316. return plane;
  16317. };
  16318. MeshBuilder.CreateGround = function (name, options, scene) {
  16319. var ground = new BABYLON.GroundMesh(name, scene);
  16320. ground._setReady(false);
  16321. ground._subdivisions = options.subdivisions || 1;
  16322. var vertexData = BABYLON.VertexData.CreateGround(options);
  16323. vertexData.applyToMesh(ground, options.updatable);
  16324. ground._setReady(true);
  16325. return ground;
  16326. };
  16327. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16328. var tiledGround = new BABYLON.Mesh(name, scene);
  16329. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16330. vertexData.applyToMesh(tiledGround, options.updatable);
  16331. return tiledGround;
  16332. };
  16333. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16334. var width = options.width || 10;
  16335. var height = options.height || 10;
  16336. var subdivisions = options.subdivisions || 1;
  16337. var minHeight = options.minHeight;
  16338. var maxHeight = options.maxHeight || 10;
  16339. var updatable = options.updatable;
  16340. var onReady = options.onReady;
  16341. var ground = new BABYLON.GroundMesh(name, scene);
  16342. ground._subdivisions = subdivisions;
  16343. ground._setReady(false);
  16344. var onload = function (img) {
  16345. // Getting height map data
  16346. var canvas = document.createElement("canvas");
  16347. var context = canvas.getContext("2d");
  16348. var bufferWidth = img.width;
  16349. var bufferHeight = img.height;
  16350. canvas.width = bufferWidth;
  16351. canvas.height = bufferHeight;
  16352. context.drawImage(img, 0, 0);
  16353. // Create VertexData from map data
  16354. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16355. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16356. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16357. width: width, height: height,
  16358. subdivisions: subdivisions,
  16359. minHeight: minHeight, maxHeight: maxHeight,
  16360. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16361. });
  16362. vertexData.applyToMesh(ground, updatable);
  16363. ground._setReady(true);
  16364. //execute ready callback, if set
  16365. if (onReady) {
  16366. onReady(ground);
  16367. }
  16368. };
  16369. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16370. return ground;
  16371. };
  16372. MeshBuilder.CreateTube = function (name, options, scene) {
  16373. var path = options.path;
  16374. var radius = options.radius || 1;
  16375. var tessellation = options.tessellation || 64;
  16376. var radiusFunction = options.radiusFunction;
  16377. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16378. var updatable = options.updatable;
  16379. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16380. var instance = options.instance;
  16381. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16382. // tube geometry
  16383. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16384. var tangents = path3D.getTangents();
  16385. var normals = path3D.getNormals();
  16386. var distances = path3D.getDistances();
  16387. var pi2 = Math.PI * 2;
  16388. var step = pi2 / tessellation * arc;
  16389. var returnRadius = function () { return radius; };
  16390. var radiusFunctionFinal = radiusFunction || returnRadius;
  16391. var circlePath;
  16392. var rad;
  16393. var normal;
  16394. var rotated;
  16395. var rotationMatrix = BABYLON.Matrix.Zero();
  16396. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16397. for (var i = 0; i < path.length; i++) {
  16398. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16399. circlePath = Array(); // current circle array
  16400. normal = normals[i]; // current normal
  16401. for (var t = 0; t < tessellation; t++) {
  16402. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16403. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16404. circlePath.push(rotated);
  16405. }
  16406. circlePaths[index] = circlePath;
  16407. index++;
  16408. }
  16409. // cap
  16410. var capPath = function (nbPoints, pathIndex) {
  16411. var pointCap = Array();
  16412. for (var i = 0; i < nbPoints; i++) {
  16413. pointCap.push(path[pathIndex]);
  16414. }
  16415. return pointCap;
  16416. };
  16417. switch (cap) {
  16418. case BABYLON.Mesh.NO_CAP:
  16419. break;
  16420. case BABYLON.Mesh.CAP_START:
  16421. circlePaths[0] = capPath(tessellation, 0);
  16422. circlePaths[1] = circlePaths[2].slice(0);
  16423. break;
  16424. case BABYLON.Mesh.CAP_END:
  16425. circlePaths[index] = circlePaths[index - 1].slice(0);
  16426. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16427. break;
  16428. case BABYLON.Mesh.CAP_ALL:
  16429. circlePaths[0] = capPath(tessellation, 0);
  16430. circlePaths[1] = circlePaths[2].slice(0);
  16431. circlePaths[index] = circlePaths[index - 1].slice(0);
  16432. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16433. break;
  16434. default:
  16435. break;
  16436. }
  16437. return circlePaths;
  16438. };
  16439. var path3D;
  16440. var pathArray;
  16441. if (instance) {
  16442. var arc = options.arc || instance.arc;
  16443. path3D = (instance.path3D).update(path);
  16444. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16445. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16446. instance.path3D = path3D;
  16447. instance.pathArray = pathArray;
  16448. instance.arc = arc;
  16449. return instance;
  16450. }
  16451. // tube creation
  16452. path3D = new BABYLON.Path3D(path);
  16453. var newPathArray = new Array();
  16454. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16455. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16456. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16457. tube.pathArray = pathArray;
  16458. tube.path3D = path3D;
  16459. tube.tessellation = tessellation;
  16460. tube.cap = cap;
  16461. tube.arc = options.arc;
  16462. return tube;
  16463. };
  16464. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16465. var polyhedron = new BABYLON.Mesh(name, scene);
  16466. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16467. vertexData.applyToMesh(polyhedron, options.updatable);
  16468. return polyhedron;
  16469. };
  16470. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16471. var indices = sourceMesh.getIndices();
  16472. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16473. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16474. var position = options.position || BABYLON.Vector3.Zero();
  16475. var normal = options.normal || BABYLON.Vector3.Up();
  16476. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16477. var angle = options.angle || 0;
  16478. // Getting correct rotation
  16479. if (!normal) {
  16480. var target = new BABYLON.Vector3(0, 0, 1);
  16481. var camera = sourceMesh.getScene().activeCamera;
  16482. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16483. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16484. }
  16485. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16486. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16487. var pitch = Math.atan2(normal.y, len);
  16488. // Matrix
  16489. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16490. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16491. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16492. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16493. var vertexData = new BABYLON.VertexData();
  16494. vertexData.indices = [];
  16495. vertexData.positions = [];
  16496. vertexData.normals = [];
  16497. vertexData.uvs = [];
  16498. var currentVertexDataIndex = 0;
  16499. var extractDecalVector3 = function (indexId) {
  16500. var vertexId = indices[indexId];
  16501. var result = new BABYLON.PositionNormalVertex();
  16502. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16503. // Send vector to decal local world
  16504. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16505. // Get normal
  16506. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16507. return result;
  16508. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16509. var clip = function (vertices, axis) {
  16510. if (vertices.length === 0) {
  16511. return vertices;
  16512. }
  16513. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16514. var clipVertices = function (v0, v1) {
  16515. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16516. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16517. };
  16518. var result = new Array();
  16519. for (var index = 0; index < vertices.length; index += 3) {
  16520. var v1Out;
  16521. var v2Out;
  16522. var v3Out;
  16523. var total = 0;
  16524. var nV1, nV2, nV3, nV4;
  16525. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16526. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16527. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16528. v1Out = d1 > 0;
  16529. v2Out = d2 > 0;
  16530. v3Out = d3 > 0;
  16531. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16532. switch (total) {
  16533. case 0:
  16534. result.push(vertices[index]);
  16535. result.push(vertices[index + 1]);
  16536. result.push(vertices[index + 2]);
  16537. break;
  16538. case 1:
  16539. if (v1Out) {
  16540. nV1 = vertices[index + 1];
  16541. nV2 = vertices[index + 2];
  16542. nV3 = clipVertices(vertices[index], nV1);
  16543. nV4 = clipVertices(vertices[index], nV2);
  16544. }
  16545. if (v2Out) {
  16546. nV1 = vertices[index];
  16547. nV2 = vertices[index + 2];
  16548. nV3 = clipVertices(vertices[index + 1], nV1);
  16549. nV4 = clipVertices(vertices[index + 1], nV2);
  16550. result.push(nV3);
  16551. result.push(nV2.clone());
  16552. result.push(nV1.clone());
  16553. result.push(nV2.clone());
  16554. result.push(nV3.clone());
  16555. result.push(nV4);
  16556. break;
  16557. }
  16558. if (v3Out) {
  16559. nV1 = vertices[index];
  16560. nV2 = vertices[index + 1];
  16561. nV3 = clipVertices(vertices[index + 2], nV1);
  16562. nV4 = clipVertices(vertices[index + 2], nV2);
  16563. }
  16564. result.push(nV1.clone());
  16565. result.push(nV2.clone());
  16566. result.push(nV3);
  16567. result.push(nV4);
  16568. result.push(nV3.clone());
  16569. result.push(nV2.clone());
  16570. break;
  16571. case 2:
  16572. if (!v1Out) {
  16573. nV1 = vertices[index].clone();
  16574. nV2 = clipVertices(nV1, vertices[index + 1]);
  16575. nV3 = clipVertices(nV1, vertices[index + 2]);
  16576. result.push(nV1);
  16577. result.push(nV2);
  16578. result.push(nV3);
  16579. }
  16580. if (!v2Out) {
  16581. nV1 = vertices[index + 1].clone();
  16582. nV2 = clipVertices(nV1, vertices[index + 2]);
  16583. nV3 = clipVertices(nV1, vertices[index]);
  16584. result.push(nV1);
  16585. result.push(nV2);
  16586. result.push(nV3);
  16587. }
  16588. if (!v3Out) {
  16589. nV1 = vertices[index + 2].clone();
  16590. nV2 = clipVertices(nV1, vertices[index]);
  16591. nV3 = clipVertices(nV1, vertices[index + 1]);
  16592. result.push(nV1);
  16593. result.push(nV2);
  16594. result.push(nV3);
  16595. }
  16596. break;
  16597. case 3:
  16598. break;
  16599. }
  16600. }
  16601. return result;
  16602. };
  16603. for (var index = 0; index < indices.length; index += 3) {
  16604. var faceVertices = new Array();
  16605. faceVertices.push(extractDecalVector3(index));
  16606. faceVertices.push(extractDecalVector3(index + 1));
  16607. faceVertices.push(extractDecalVector3(index + 2));
  16608. // Clip
  16609. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16610. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16611. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16612. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16615. if (faceVertices.length === 0) {
  16616. continue;
  16617. }
  16618. // Add UVs and get back to world
  16619. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16620. var vertex = faceVertices[vIndex];
  16621. //TODO check for Int32Array
  16622. vertexData.indices.push(currentVertexDataIndex);
  16623. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16624. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16625. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16626. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16627. currentVertexDataIndex++;
  16628. }
  16629. }
  16630. // Return mesh
  16631. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16632. vertexData.applyToMesh(decal);
  16633. decal.position = position.clone();
  16634. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16635. return decal;
  16636. };
  16637. // Privates
  16638. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16639. // extrusion geometry
  16640. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16641. var tangents = path3D.getTangents();
  16642. var normals = path3D.getNormals();
  16643. var binormals = path3D.getBinormals();
  16644. var distances = path3D.getDistances();
  16645. var angle = 0;
  16646. var returnScale = function () { return scale; };
  16647. var returnRotation = function () { return rotation; };
  16648. var rotate = custom ? rotateFunction : returnRotation;
  16649. var scl = custom ? scaleFunction : returnScale;
  16650. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16651. var rotationMatrix = BABYLON.Matrix.Zero();
  16652. for (var i = 0; i < curve.length; i++) {
  16653. var shapePath = new Array();
  16654. var angleStep = rotate(i, distances[i]);
  16655. var scaleRatio = scl(i, distances[i]);
  16656. for (var p = 0; p < shape.length; p++) {
  16657. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16658. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16659. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16660. shapePath.push(rotated);
  16661. }
  16662. shapePaths[index] = shapePath;
  16663. angle += angleStep;
  16664. index++;
  16665. }
  16666. // cap
  16667. var capPath = function (shapePath) {
  16668. var pointCap = Array();
  16669. var barycenter = BABYLON.Vector3.Zero();
  16670. var i;
  16671. for (i = 0; i < shapePath.length; i++) {
  16672. barycenter.addInPlace(shapePath[i]);
  16673. }
  16674. barycenter.scaleInPlace(1 / shapePath.length);
  16675. for (i = 0; i < shapePath.length; i++) {
  16676. pointCap.push(barycenter);
  16677. }
  16678. return pointCap;
  16679. };
  16680. switch (cap) {
  16681. case BABYLON.Mesh.NO_CAP:
  16682. break;
  16683. case BABYLON.Mesh.CAP_START:
  16684. shapePaths[0] = capPath(shapePaths[2]);
  16685. shapePaths[1] = shapePaths[2].slice(0);
  16686. break;
  16687. case BABYLON.Mesh.CAP_END:
  16688. shapePaths[index] = shapePaths[index - 1];
  16689. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16690. break;
  16691. case BABYLON.Mesh.CAP_ALL:
  16692. shapePaths[0] = capPath(shapePaths[2]);
  16693. shapePaths[1] = shapePaths[2].slice(0);
  16694. shapePaths[index] = shapePaths[index - 1];
  16695. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16696. break;
  16697. default:
  16698. break;
  16699. }
  16700. return shapePaths;
  16701. };
  16702. var path3D;
  16703. var pathArray;
  16704. if (instance) {
  16705. path3D = (instance.path3D).update(curve);
  16706. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16707. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16708. return instance;
  16709. }
  16710. // extruded shape creation
  16711. path3D = new BABYLON.Path3D(curve);
  16712. var newShapePaths = new Array();
  16713. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16714. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16715. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16716. extrudedGeneric.pathArray = pathArray;
  16717. extrudedGeneric.path3D = path3D;
  16718. extrudedGeneric.cap = cap;
  16719. return extrudedGeneric;
  16720. };
  16721. return MeshBuilder;
  16722. })();
  16723. BABYLON.MeshBuilder = MeshBuilder;
  16724. })(BABYLON || (BABYLON = {}));
  16725. var BABYLON;
  16726. (function (BABYLON) {
  16727. var BaseTexture = (function () {
  16728. function BaseTexture(scene) {
  16729. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16730. this.hasAlpha = false;
  16731. this.getAlphaFromRGB = false;
  16732. this.level = 1;
  16733. this.isCube = false;
  16734. this.isRenderTarget = false;
  16735. this.animations = new Array();
  16736. this.coordinatesIndex = 0;
  16737. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16738. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16739. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16740. this.anisotropicFilteringLevel = 4;
  16741. this._scene = scene;
  16742. this._scene.textures.push(this);
  16743. }
  16744. BaseTexture.prototype.getScene = function () {
  16745. return this._scene;
  16746. };
  16747. BaseTexture.prototype.getTextureMatrix = function () {
  16748. return null;
  16749. };
  16750. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16751. return null;
  16752. };
  16753. BaseTexture.prototype.getInternalTexture = function () {
  16754. return this._texture;
  16755. };
  16756. BaseTexture.prototype.isReady = function () {
  16757. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16758. return true;
  16759. }
  16760. if (this._texture) {
  16761. return this._texture.isReady;
  16762. }
  16763. return false;
  16764. };
  16765. BaseTexture.prototype.getSize = function () {
  16766. if (this._texture._width) {
  16767. return { width: this._texture._width, height: this._texture._height };
  16768. }
  16769. if (this._texture._size) {
  16770. return { width: this._texture._size, height: this._texture._size };
  16771. }
  16772. return { width: 0, height: 0 };
  16773. };
  16774. BaseTexture.prototype.getBaseSize = function () {
  16775. if (!this.isReady())
  16776. return { width: 0, height: 0 };
  16777. if (this._texture._size) {
  16778. return { width: this._texture._size, height: this._texture._size };
  16779. }
  16780. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16781. };
  16782. BaseTexture.prototype.scale = function (ratio) {
  16783. };
  16784. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16785. get: function () {
  16786. return false;
  16787. },
  16788. enumerable: true,
  16789. configurable: true
  16790. });
  16791. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16792. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16793. for (var index = 0; index < texturesCache.length; index++) {
  16794. var texturesCacheEntry = texturesCache[index];
  16795. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16796. texturesCache.splice(index, 1);
  16797. return;
  16798. }
  16799. }
  16800. };
  16801. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16802. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16803. for (var index = 0; index < texturesCache.length; index++) {
  16804. var texturesCacheEntry = texturesCache[index];
  16805. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16806. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16807. texturesCacheEntry.references++;
  16808. return texturesCacheEntry;
  16809. }
  16810. }
  16811. }
  16812. return null;
  16813. };
  16814. BaseTexture.prototype.delayLoad = function () {
  16815. };
  16816. BaseTexture.prototype.clone = function () {
  16817. return null;
  16818. };
  16819. BaseTexture.prototype.releaseInternalTexture = function () {
  16820. if (this._texture) {
  16821. this._scene.getEngine().releaseInternalTexture(this._texture);
  16822. delete this._texture;
  16823. }
  16824. };
  16825. BaseTexture.prototype.dispose = function () {
  16826. // Animations
  16827. this.getScene().stopAnimation(this);
  16828. // Remove from scene
  16829. var index = this._scene.textures.indexOf(this);
  16830. if (index >= 0) {
  16831. this._scene.textures.splice(index, 1);
  16832. }
  16833. if (this._texture === undefined) {
  16834. return;
  16835. }
  16836. // Release
  16837. this.releaseInternalTexture();
  16838. // Callback
  16839. if (this.onDispose) {
  16840. this.onDispose();
  16841. }
  16842. };
  16843. BaseTexture.prototype.serialize = function () {
  16844. var serializationObject = {};
  16845. if (!this.name) {
  16846. return null;
  16847. }
  16848. serializationObject.name = this.name;
  16849. serializationObject.hasAlpha = this.hasAlpha;
  16850. serializationObject.level = this.level;
  16851. serializationObject.coordinatesIndex = this.coordinatesIndex;
  16852. serializationObject.coordinatesMode = this.coordinatesMode;
  16853. serializationObject.wrapU = this.wrapU;
  16854. serializationObject.wrapV = this.wrapV;
  16855. // Animations
  16856. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16857. return serializationObject;
  16858. };
  16859. return BaseTexture;
  16860. })();
  16861. BABYLON.BaseTexture = BaseTexture;
  16862. })(BABYLON || (BABYLON = {}));
  16863. var BABYLON;
  16864. (function (BABYLON) {
  16865. var Texture = (function (_super) {
  16866. __extends(Texture, _super);
  16867. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16868. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16869. if (onLoad === void 0) { onLoad = null; }
  16870. if (onError === void 0) { onError = null; }
  16871. if (buffer === void 0) { buffer = null; }
  16872. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16873. _super.call(this, scene);
  16874. this.uOffset = 0;
  16875. this.vOffset = 0;
  16876. this.uScale = 1.0;
  16877. this.vScale = 1.0;
  16878. this.uAng = 0;
  16879. this.vAng = 0;
  16880. this.wAng = 0;
  16881. this.name = url;
  16882. this.url = url;
  16883. this._noMipmap = noMipmap;
  16884. this._invertY = invertY;
  16885. this._samplingMode = samplingMode;
  16886. this._buffer = buffer;
  16887. this._deleteBuffer = deleteBuffer;
  16888. if (!url) {
  16889. return;
  16890. }
  16891. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16892. if (!this._texture) {
  16893. if (!scene.useDelayedTextureLoading) {
  16894. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16895. if (deleteBuffer) {
  16896. delete this._buffer;
  16897. }
  16898. }
  16899. else {
  16900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16901. }
  16902. }
  16903. else {
  16904. BABYLON.Tools.SetImmediate(function () {
  16905. if (onLoad) {
  16906. onLoad();
  16907. }
  16908. });
  16909. }
  16910. }
  16911. Texture.prototype.delayLoad = function () {
  16912. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16913. return;
  16914. }
  16915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16916. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16917. if (!this._texture) {
  16918. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16919. if (this._deleteBuffer) {
  16920. delete this._buffer;
  16921. }
  16922. }
  16923. };
  16924. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16925. if (!this._texture) {
  16926. return;
  16927. }
  16928. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16929. };
  16930. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16931. x *= this.uScale;
  16932. y *= this.vScale;
  16933. x -= 0.5 * this.uScale;
  16934. y -= 0.5 * this.vScale;
  16935. z -= 0.5;
  16936. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16937. t.x += 0.5 * this.uScale + this.uOffset;
  16938. t.y += 0.5 * this.vScale + this.vOffset;
  16939. t.z += 0.5;
  16940. };
  16941. Texture.prototype.getTextureMatrix = function () {
  16942. if (this.uOffset === this._cachedUOffset &&
  16943. this.vOffset === this._cachedVOffset &&
  16944. this.uScale === this._cachedUScale &&
  16945. this.vScale === this._cachedVScale &&
  16946. this.uAng === this._cachedUAng &&
  16947. this.vAng === this._cachedVAng &&
  16948. this.wAng === this._cachedWAng) {
  16949. return this._cachedTextureMatrix;
  16950. }
  16951. this._cachedUOffset = this.uOffset;
  16952. this._cachedVOffset = this.vOffset;
  16953. this._cachedUScale = this.uScale;
  16954. this._cachedVScale = this.vScale;
  16955. this._cachedUAng = this.uAng;
  16956. this._cachedVAng = this.vAng;
  16957. this._cachedWAng = this.wAng;
  16958. if (!this._cachedTextureMatrix) {
  16959. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16960. this._rowGenerationMatrix = new BABYLON.Matrix();
  16961. this._t0 = BABYLON.Vector3.Zero();
  16962. this._t1 = BABYLON.Vector3.Zero();
  16963. this._t2 = BABYLON.Vector3.Zero();
  16964. }
  16965. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16966. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16967. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16968. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16969. this._t1.subtractInPlace(this._t0);
  16970. this._t2.subtractInPlace(this._t0);
  16971. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16972. this._cachedTextureMatrix.m[0] = this._t1.x;
  16973. this._cachedTextureMatrix.m[1] = this._t1.y;
  16974. this._cachedTextureMatrix.m[2] = this._t1.z;
  16975. this._cachedTextureMatrix.m[4] = this._t2.x;
  16976. this._cachedTextureMatrix.m[5] = this._t2.y;
  16977. this._cachedTextureMatrix.m[6] = this._t2.z;
  16978. this._cachedTextureMatrix.m[8] = this._t0.x;
  16979. this._cachedTextureMatrix.m[9] = this._t0.y;
  16980. this._cachedTextureMatrix.m[10] = this._t0.z;
  16981. return this._cachedTextureMatrix;
  16982. };
  16983. Texture.prototype.getReflectionTextureMatrix = function () {
  16984. if (this.uOffset === this._cachedUOffset &&
  16985. this.vOffset === this._cachedVOffset &&
  16986. this.uScale === this._cachedUScale &&
  16987. this.vScale === this._cachedVScale &&
  16988. this.coordinatesMode === this._cachedCoordinatesMode) {
  16989. return this._cachedTextureMatrix;
  16990. }
  16991. if (!this._cachedTextureMatrix) {
  16992. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16993. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16994. }
  16995. this._cachedCoordinatesMode = this.coordinatesMode;
  16996. switch (this.coordinatesMode) {
  16997. case Texture.PLANAR_MODE:
  16998. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16999. this._cachedTextureMatrix[0] = this.uScale;
  17000. this._cachedTextureMatrix[5] = this.vScale;
  17001. this._cachedTextureMatrix[12] = this.uOffset;
  17002. this._cachedTextureMatrix[13] = this.vOffset;
  17003. break;
  17004. case Texture.PROJECTION_MODE:
  17005. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17006. this._projectionModeMatrix.m[0] = 0.5;
  17007. this._projectionModeMatrix.m[5] = -0.5;
  17008. this._projectionModeMatrix.m[10] = 0.0;
  17009. this._projectionModeMatrix.m[12] = 0.5;
  17010. this._projectionModeMatrix.m[13] = 0.5;
  17011. this._projectionModeMatrix.m[14] = 1.0;
  17012. this._projectionModeMatrix.m[15] = 1.0;
  17013. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17014. break;
  17015. default:
  17016. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17017. break;
  17018. }
  17019. return this._cachedTextureMatrix;
  17020. };
  17021. Texture.prototype.clone = function () {
  17022. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17023. // Base texture
  17024. newTexture.hasAlpha = this.hasAlpha;
  17025. newTexture.level = this.level;
  17026. newTexture.wrapU = this.wrapU;
  17027. newTexture.wrapV = this.wrapV;
  17028. newTexture.coordinatesIndex = this.coordinatesIndex;
  17029. newTexture.coordinatesMode = this.coordinatesMode;
  17030. // Texture
  17031. newTexture.uOffset = this.uOffset;
  17032. newTexture.vOffset = this.vOffset;
  17033. newTexture.uScale = this.uScale;
  17034. newTexture.vScale = this.vScale;
  17035. newTexture.uAng = this.uAng;
  17036. newTexture.vAng = this.vAng;
  17037. newTexture.wAng = this.wAng;
  17038. return newTexture;
  17039. };
  17040. Texture.prototype.serialize = function () {
  17041. if (!this.name) {
  17042. return null;
  17043. }
  17044. var serializationObject = _super.prototype.serialize.call(this);
  17045. serializationObject.uOffset = this.uOffset;
  17046. serializationObject.vOffset = this.vOffset;
  17047. serializationObject.uScale = this.uScale;
  17048. serializationObject.vScale = this.vScale;
  17049. serializationObject.uAng = this.uAng;
  17050. serializationObject.vAng = this.vAng;
  17051. serializationObject.wAng = this.wAng;
  17052. return serializationObject;
  17053. };
  17054. // Statics
  17055. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17056. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17057. if (onLoad === void 0) { onLoad = null; }
  17058. if (onError === void 0) { onError = null; }
  17059. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17060. };
  17061. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17062. if (parsedTexture.isCube) {
  17063. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17064. }
  17065. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17066. return null;
  17067. }
  17068. var texture;
  17069. if (parsedTexture.mirrorPlane) {
  17070. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17071. texture._waitingRenderList = parsedTexture.renderList;
  17072. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17073. }
  17074. else if (parsedTexture.isRenderTarget) {
  17075. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17076. texture._waitingRenderList = parsedTexture.renderList;
  17077. }
  17078. else {
  17079. if (parsedTexture.base64String) {
  17080. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17081. }
  17082. else {
  17083. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17084. }
  17085. }
  17086. texture.name = parsedTexture.name;
  17087. texture.hasAlpha = parsedTexture.hasAlpha;
  17088. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17089. texture.level = parsedTexture.level;
  17090. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17091. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17092. texture.uOffset = parsedTexture.uOffset;
  17093. texture.vOffset = parsedTexture.vOffset;
  17094. texture.uScale = parsedTexture.uScale;
  17095. texture.vScale = parsedTexture.vScale;
  17096. texture.uAng = parsedTexture.uAng;
  17097. texture.vAng = parsedTexture.vAng;
  17098. texture.wAng = parsedTexture.wAng;
  17099. texture.wrapU = parsedTexture.wrapU;
  17100. texture.wrapV = parsedTexture.wrapV;
  17101. // Animations
  17102. if (parsedTexture.animations) {
  17103. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17104. var parsedAnimation = parsedTexture.animations[animationIndex];
  17105. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17106. }
  17107. }
  17108. return texture;
  17109. };
  17110. // Constants
  17111. Texture.NEAREST_SAMPLINGMODE = 1;
  17112. Texture.BILINEAR_SAMPLINGMODE = 2;
  17113. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17114. Texture.EXPLICIT_MODE = 0;
  17115. Texture.SPHERICAL_MODE = 1;
  17116. Texture.PLANAR_MODE = 2;
  17117. Texture.CUBIC_MODE = 3;
  17118. Texture.PROJECTION_MODE = 4;
  17119. Texture.SKYBOX_MODE = 5;
  17120. Texture.INVCUBIC_MODE = 6;
  17121. Texture.EQUIRECTANGULAR_MODE = 7;
  17122. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17123. Texture.CLAMP_ADDRESSMODE = 0;
  17124. Texture.WRAP_ADDRESSMODE = 1;
  17125. Texture.MIRROR_ADDRESSMODE = 2;
  17126. return Texture;
  17127. })(BABYLON.BaseTexture);
  17128. BABYLON.Texture = Texture;
  17129. })(BABYLON || (BABYLON = {}));
  17130. var BABYLON;
  17131. (function (BABYLON) {
  17132. var CubeTexture = (function (_super) {
  17133. __extends(CubeTexture, _super);
  17134. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17135. _super.call(this, scene);
  17136. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17137. this.name = rootUrl;
  17138. this.url = rootUrl;
  17139. this._noMipmap = noMipmap;
  17140. this.hasAlpha = false;
  17141. if (!rootUrl) {
  17142. return;
  17143. }
  17144. this._texture = this._getFromCache(rootUrl, noMipmap);
  17145. if (!extensions) {
  17146. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17147. }
  17148. this._extensions = extensions;
  17149. if (!this._texture) {
  17150. if (!scene.useDelayedTextureLoading) {
  17151. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17152. }
  17153. else {
  17154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17155. }
  17156. }
  17157. this.isCube = true;
  17158. this._textureMatrix = BABYLON.Matrix.Identity();
  17159. }
  17160. CubeTexture.prototype.clone = function () {
  17161. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17162. // Base texture
  17163. newTexture.level = this.level;
  17164. newTexture.wrapU = this.wrapU;
  17165. newTexture.wrapV = this.wrapV;
  17166. newTexture.coordinatesIndex = this.coordinatesIndex;
  17167. newTexture.coordinatesMode = this.coordinatesMode;
  17168. return newTexture;
  17169. };
  17170. // Methods
  17171. CubeTexture.prototype.delayLoad = function () {
  17172. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17173. return;
  17174. }
  17175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17176. this._texture = this._getFromCache(this.url, this._noMipmap);
  17177. if (!this._texture) {
  17178. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17179. }
  17180. };
  17181. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17182. return this._textureMatrix;
  17183. };
  17184. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17185. var texture = null;
  17186. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17187. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17188. texture.name = parsedTexture.name;
  17189. texture.hasAlpha = parsedTexture.hasAlpha;
  17190. texture.level = parsedTexture.level;
  17191. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17192. }
  17193. return texture;
  17194. };
  17195. CubeTexture.prototype.serialize = function () {
  17196. if (!this.name) {
  17197. return null;
  17198. }
  17199. var serializationObject = {};
  17200. serializationObject.name = this.name;
  17201. serializationObject.hasAlpha = this.hasAlpha;
  17202. serializationObject.isCube = true;
  17203. serializationObject.level = this.level;
  17204. serializationObject.coordinatesMode = this.coordinatesMode;
  17205. return serializationObject;
  17206. };
  17207. return CubeTexture;
  17208. })(BABYLON.BaseTexture);
  17209. BABYLON.CubeTexture = CubeTexture;
  17210. })(BABYLON || (BABYLON = {}));
  17211. var BABYLON;
  17212. (function (BABYLON) {
  17213. var RenderTargetTexture = (function (_super) {
  17214. __extends(RenderTargetTexture, _super);
  17215. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17216. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17217. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17218. if (isCube === void 0) { isCube = false; }
  17219. _super.call(this, null, scene, !generateMipMaps);
  17220. this.isCube = isCube;
  17221. this.renderList = new Array();
  17222. this.renderParticles = true;
  17223. this.renderSprites = false;
  17224. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17225. this._currentRefreshId = -1;
  17226. this._refreshRate = 1;
  17227. this.name = name;
  17228. this.isRenderTarget = true;
  17229. this._size = size;
  17230. this._generateMipMaps = generateMipMaps;
  17231. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17232. if (isCube) {
  17233. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17234. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17235. this._textureMatrix = BABYLON.Matrix.Identity();
  17236. }
  17237. else {
  17238. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17239. }
  17240. // Rendering groups
  17241. this._renderingManager = new BABYLON.RenderingManager(scene);
  17242. }
  17243. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17244. get: function () {
  17245. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17251. get: function () {
  17252. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17253. },
  17254. enumerable: true,
  17255. configurable: true
  17256. });
  17257. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17258. get: function () {
  17259. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17260. },
  17261. enumerable: true,
  17262. configurable: true
  17263. });
  17264. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17265. this._currentRefreshId = -1;
  17266. };
  17267. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17268. get: function () {
  17269. return this._refreshRate;
  17270. },
  17271. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17272. set: function (value) {
  17273. this._refreshRate = value;
  17274. this.resetRefreshCounter();
  17275. },
  17276. enumerable: true,
  17277. configurable: true
  17278. });
  17279. RenderTargetTexture.prototype._shouldRender = function () {
  17280. if (this._currentRefreshId === -1) {
  17281. this._currentRefreshId = 1;
  17282. return true;
  17283. }
  17284. if (this.refreshRate === this._currentRefreshId) {
  17285. this._currentRefreshId = 1;
  17286. return true;
  17287. }
  17288. this._currentRefreshId++;
  17289. return false;
  17290. };
  17291. RenderTargetTexture.prototype.isReady = function () {
  17292. if (!this.getScene().renderTargetsEnabled) {
  17293. return false;
  17294. }
  17295. return _super.prototype.isReady.call(this);
  17296. };
  17297. RenderTargetTexture.prototype.getRenderSize = function () {
  17298. return this._size;
  17299. };
  17300. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17301. get: function () {
  17302. return true;
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. RenderTargetTexture.prototype.scale = function (ratio) {
  17308. var newSize = this._size * ratio;
  17309. this.resize(newSize, this._generateMipMaps);
  17310. };
  17311. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17312. if (this.isCube) {
  17313. return this._textureMatrix;
  17314. }
  17315. return _super.prototype.getReflectionTextureMatrix.call(this);
  17316. };
  17317. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17318. this.releaseInternalTexture();
  17319. if (this.isCube) {
  17320. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17321. }
  17322. else {
  17323. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17324. }
  17325. };
  17326. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17327. var scene = this.getScene();
  17328. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17329. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17330. }
  17331. if (this._waitingRenderList) {
  17332. this.renderList = [];
  17333. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17334. var id = this._waitingRenderList[index];
  17335. this.renderList.push(scene.getMeshByID(id));
  17336. }
  17337. delete this._waitingRenderList;
  17338. }
  17339. if (this.renderList && this.renderList.length === 0) {
  17340. return;
  17341. }
  17342. // Prepare renderingManager
  17343. this._renderingManager.reset();
  17344. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17345. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17346. var mesh = currentRenderList[meshIndex];
  17347. if (mesh) {
  17348. if (!mesh.isReady()) {
  17349. // Reset _currentRefreshId
  17350. this.resetRefreshCounter();
  17351. continue;
  17352. }
  17353. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17354. mesh._activate(scene.getRenderId());
  17355. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17356. var subMesh = mesh.subMeshes[subIndex];
  17357. scene._activeIndices += subMesh.indexCount;
  17358. this._renderingManager.dispatch(subMesh);
  17359. }
  17360. }
  17361. }
  17362. }
  17363. if (this.isCube) {
  17364. for (var face = 0; face < 6; face++) {
  17365. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17366. }
  17367. }
  17368. else {
  17369. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17370. }
  17371. if (this.onAfterUnbind) {
  17372. this.onAfterUnbind();
  17373. }
  17374. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17375. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17376. }
  17377. scene.resetCachedMaterial();
  17378. };
  17379. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17380. var scene = this.getScene();
  17381. var engine = scene.getEngine();
  17382. // Bind
  17383. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17384. if (this.isCube) {
  17385. engine.bindFramebuffer(this._texture, faceIndex);
  17386. }
  17387. else {
  17388. engine.bindFramebuffer(this._texture);
  17389. }
  17390. }
  17391. if (this.onBeforeRender) {
  17392. this.onBeforeRender(faceIndex);
  17393. }
  17394. // Clear
  17395. if (this.onClear) {
  17396. this.onClear(engine);
  17397. }
  17398. else {
  17399. engine.clear(scene.clearColor, true, true);
  17400. }
  17401. if (!this._doNotChangeAspectRatio) {
  17402. scene.updateTransformMatrix(true);
  17403. }
  17404. // Render
  17405. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17406. if (useCameraPostProcess) {
  17407. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17408. }
  17409. if (!this._doNotChangeAspectRatio) {
  17410. scene.updateTransformMatrix(true);
  17411. }
  17412. if (this.onAfterRender) {
  17413. this.onAfterRender(faceIndex);
  17414. }
  17415. // Dump ?
  17416. if (dumpForDebug) {
  17417. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17418. }
  17419. // Unbind
  17420. if (!this.isCube || faceIndex === 5) {
  17421. if (this.isCube) {
  17422. if (faceIndex === 5) {
  17423. engine.generateMipMapsForCubemap(this._texture);
  17424. }
  17425. }
  17426. engine.unBindFramebuffer(this._texture, this.isCube);
  17427. }
  17428. };
  17429. RenderTargetTexture.prototype.clone = function () {
  17430. var textureSize = this.getSize();
  17431. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17432. // Base texture
  17433. newTexture.hasAlpha = this.hasAlpha;
  17434. newTexture.level = this.level;
  17435. // RenderTarget Texture
  17436. newTexture.coordinatesMode = this.coordinatesMode;
  17437. newTexture.renderList = this.renderList.slice(0);
  17438. return newTexture;
  17439. };
  17440. RenderTargetTexture.prototype.serialize = function () {
  17441. if (!this.name) {
  17442. return null;
  17443. }
  17444. var serializationObject = _super.prototype.serialize.call(this);
  17445. serializationObject.renderTargetSize = this.getRenderSize();
  17446. serializationObject.renderList = [];
  17447. for (var index = 0; index < this.renderList.length; index++) {
  17448. serializationObject.renderList.push(this.renderList[index].id);
  17449. }
  17450. return serializationObject;
  17451. };
  17452. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17453. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17454. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17455. return RenderTargetTexture;
  17456. })(BABYLON.Texture);
  17457. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17458. })(BABYLON || (BABYLON = {}));
  17459. var BABYLON;
  17460. (function (BABYLON) {
  17461. var ProceduralTexture = (function (_super) {
  17462. __extends(ProceduralTexture, _super);
  17463. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17464. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17465. _super.call(this, null, scene, !generateMipMaps);
  17466. this.isEnabled = true;
  17467. this._currentRefreshId = -1;
  17468. this._refreshRate = 1;
  17469. this._vertexDeclaration = [2];
  17470. this._vertexStrideSize = 2 * 4;
  17471. this._uniforms = new Array();
  17472. this._samplers = new Array();
  17473. this._textures = new Array();
  17474. this._floats = new Array();
  17475. this._floatsArrays = {};
  17476. this._colors3 = new Array();
  17477. this._colors4 = new Array();
  17478. this._vectors2 = new Array();
  17479. this._vectors3 = new Array();
  17480. this._matrices = new Array();
  17481. this._fallbackTextureUsed = false;
  17482. scene._proceduralTextures.push(this);
  17483. this.name = name;
  17484. this.isRenderTarget = true;
  17485. this._size = size;
  17486. this._generateMipMaps = generateMipMaps;
  17487. this.setFragment(fragment);
  17488. this._fallbackTexture = fallbackTexture;
  17489. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17490. // VBO
  17491. var vertices = [];
  17492. vertices.push(1, 1);
  17493. vertices.push(-1, 1);
  17494. vertices.push(-1, -1);
  17495. vertices.push(1, -1);
  17496. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17497. // Indices
  17498. var indices = [];
  17499. indices.push(0);
  17500. indices.push(1);
  17501. indices.push(2);
  17502. indices.push(0);
  17503. indices.push(2);
  17504. indices.push(3);
  17505. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17506. }
  17507. ProceduralTexture.prototype.reset = function () {
  17508. if (this._effect === undefined) {
  17509. return;
  17510. }
  17511. var engine = this.getScene().getEngine();
  17512. engine._releaseEffect(this._effect);
  17513. };
  17514. ProceduralTexture.prototype.isReady = function () {
  17515. var _this = this;
  17516. var engine = this.getScene().getEngine();
  17517. var shaders;
  17518. if (!this._fragment) {
  17519. return false;
  17520. }
  17521. if (this._fallbackTextureUsed) {
  17522. return true;
  17523. }
  17524. if (this._fragment.fragmentElement !== undefined) {
  17525. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17526. }
  17527. else {
  17528. shaders = { vertex: "procedural", fragment: this._fragment };
  17529. }
  17530. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17531. _this.releaseInternalTexture();
  17532. if (_this._fallbackTexture) {
  17533. _this._texture = _this._fallbackTexture._texture;
  17534. _this._texture.references++;
  17535. }
  17536. _this._fallbackTextureUsed = true;
  17537. });
  17538. return this._effect.isReady();
  17539. };
  17540. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17541. this._currentRefreshId = -1;
  17542. };
  17543. ProceduralTexture.prototype.setFragment = function (fragment) {
  17544. this._fragment = fragment;
  17545. };
  17546. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17547. get: function () {
  17548. return this._refreshRate;
  17549. },
  17550. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17551. set: function (value) {
  17552. this._refreshRate = value;
  17553. this.resetRefreshCounter();
  17554. },
  17555. enumerable: true,
  17556. configurable: true
  17557. });
  17558. ProceduralTexture.prototype._shouldRender = function () {
  17559. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17560. return false;
  17561. }
  17562. if (this._fallbackTextureUsed) {
  17563. return false;
  17564. }
  17565. if (this._currentRefreshId === -1) {
  17566. this._currentRefreshId = 1;
  17567. return true;
  17568. }
  17569. if (this.refreshRate === this._currentRefreshId) {
  17570. this._currentRefreshId = 1;
  17571. return true;
  17572. }
  17573. this._currentRefreshId++;
  17574. return false;
  17575. };
  17576. ProceduralTexture.prototype.getRenderSize = function () {
  17577. return this._size;
  17578. };
  17579. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17580. if (this._fallbackTextureUsed) {
  17581. return;
  17582. }
  17583. this.releaseInternalTexture();
  17584. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17585. };
  17586. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17587. if (this._uniforms.indexOf(uniformName) === -1) {
  17588. this._uniforms.push(uniformName);
  17589. }
  17590. };
  17591. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17592. if (this._samplers.indexOf(name) === -1) {
  17593. this._samplers.push(name);
  17594. }
  17595. this._textures[name] = texture;
  17596. return this;
  17597. };
  17598. ProceduralTexture.prototype.setFloat = function (name, value) {
  17599. this._checkUniform(name);
  17600. this._floats[name] = value;
  17601. return this;
  17602. };
  17603. ProceduralTexture.prototype.setFloats = function (name, value) {
  17604. this._checkUniform(name);
  17605. this._floatsArrays[name] = value;
  17606. return this;
  17607. };
  17608. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17609. this._checkUniform(name);
  17610. this._colors3[name] = value;
  17611. return this;
  17612. };
  17613. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17614. this._checkUniform(name);
  17615. this._colors4[name] = value;
  17616. return this;
  17617. };
  17618. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17619. this._checkUniform(name);
  17620. this._vectors2[name] = value;
  17621. return this;
  17622. };
  17623. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17624. this._checkUniform(name);
  17625. this._vectors3[name] = value;
  17626. return this;
  17627. };
  17628. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17629. this._checkUniform(name);
  17630. this._matrices[name] = value;
  17631. return this;
  17632. };
  17633. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17634. var scene = this.getScene();
  17635. var engine = scene.getEngine();
  17636. engine.bindFramebuffer(this._texture);
  17637. // Clear
  17638. engine.clear(scene.clearColor, true, true);
  17639. // Render
  17640. engine.enableEffect(this._effect);
  17641. engine.setState(false);
  17642. // Texture
  17643. for (var name in this._textures) {
  17644. this._effect.setTexture(name, this._textures[name]);
  17645. }
  17646. // Float
  17647. for (name in this._floats) {
  17648. this._effect.setFloat(name, this._floats[name]);
  17649. }
  17650. // Floats
  17651. for (name in this._floatsArrays) {
  17652. this._effect.setArray(name, this._floatsArrays[name]);
  17653. }
  17654. // Color3
  17655. for (name in this._colors3) {
  17656. this._effect.setColor3(name, this._colors3[name]);
  17657. }
  17658. // Color4
  17659. for (name in this._colors4) {
  17660. var color = this._colors4[name];
  17661. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17662. }
  17663. // Vector2
  17664. for (name in this._vectors2) {
  17665. this._effect.setVector2(name, this._vectors2[name]);
  17666. }
  17667. // Vector3
  17668. for (name in this._vectors3) {
  17669. this._effect.setVector3(name, this._vectors3[name]);
  17670. }
  17671. // Matrix
  17672. for (name in this._matrices) {
  17673. this._effect.setMatrix(name, this._matrices[name]);
  17674. }
  17675. // VBOs
  17676. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17677. // Draw order
  17678. engine.draw(true, 0, 6);
  17679. // Unbind
  17680. engine.unBindFramebuffer(this._texture);
  17681. };
  17682. ProceduralTexture.prototype.clone = function () {
  17683. var textureSize = this.getSize();
  17684. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17685. // Base texture
  17686. newTexture.hasAlpha = this.hasAlpha;
  17687. newTexture.level = this.level;
  17688. // RenderTarget Texture
  17689. newTexture.coordinatesMode = this.coordinatesMode;
  17690. return newTexture;
  17691. };
  17692. ProceduralTexture.prototype.dispose = function () {
  17693. var index = this.getScene()._proceduralTextures.indexOf(this);
  17694. if (index >= 0) {
  17695. this.getScene()._proceduralTextures.splice(index, 1);
  17696. }
  17697. _super.prototype.dispose.call(this);
  17698. };
  17699. return ProceduralTexture;
  17700. })(BABYLON.Texture);
  17701. BABYLON.ProceduralTexture = ProceduralTexture;
  17702. })(BABYLON || (BABYLON = {}));
  17703. var BABYLON;
  17704. (function (BABYLON) {
  17705. var MirrorTexture = (function (_super) {
  17706. __extends(MirrorTexture, _super);
  17707. function MirrorTexture(name, size, scene, generateMipMaps) {
  17708. var _this = this;
  17709. _super.call(this, name, size, scene, generateMipMaps, true);
  17710. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17711. this._transformMatrix = BABYLON.Matrix.Zero();
  17712. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17713. this.onBeforeRender = function () {
  17714. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17715. _this._savedViewMatrix = scene.getViewMatrix();
  17716. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17717. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17718. scene.clipPlane = _this.mirrorPlane;
  17719. scene.getEngine().cullBackFaces = false;
  17720. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17721. };
  17722. this.onAfterRender = function () {
  17723. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17724. scene.getEngine().cullBackFaces = true;
  17725. scene._mirroredCameraPosition = null;
  17726. delete scene.clipPlane;
  17727. };
  17728. }
  17729. MirrorTexture.prototype.clone = function () {
  17730. var textureSize = this.getSize();
  17731. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17732. // Base texture
  17733. newTexture.hasAlpha = this.hasAlpha;
  17734. newTexture.level = this.level;
  17735. // Mirror Texture
  17736. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17737. newTexture.renderList = this.renderList.slice(0);
  17738. return newTexture;
  17739. };
  17740. MirrorTexture.prototype.serialize = function () {
  17741. if (!this.name) {
  17742. return null;
  17743. }
  17744. var serializationObject = _super.prototype.serialize.call(this);
  17745. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  17746. return serializationObject;
  17747. };
  17748. return MirrorTexture;
  17749. })(BABYLON.RenderTargetTexture);
  17750. BABYLON.MirrorTexture = MirrorTexture;
  17751. })(BABYLON || (BABYLON = {}));
  17752. var BABYLON;
  17753. (function (BABYLON) {
  17754. var DynamicTexture = (function (_super) {
  17755. __extends(DynamicTexture, _super);
  17756. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17758. _super.call(this, null, scene, !generateMipMaps);
  17759. this.name = name;
  17760. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17761. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17762. this._generateMipMaps = generateMipMaps;
  17763. if (options.getContext) {
  17764. this._canvas = options;
  17765. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17766. }
  17767. else {
  17768. this._canvas = document.createElement("canvas");
  17769. if (options.width) {
  17770. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17771. }
  17772. else {
  17773. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17774. }
  17775. }
  17776. var textureSize = this.getSize();
  17777. this._canvas.width = textureSize.width;
  17778. this._canvas.height = textureSize.height;
  17779. this._context = this._canvas.getContext("2d");
  17780. }
  17781. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17782. get: function () {
  17783. return true;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. DynamicTexture.prototype.scale = function (ratio) {
  17789. var textureSize = this.getSize();
  17790. textureSize.width *= ratio;
  17791. textureSize.height *= ratio;
  17792. this._canvas.width = textureSize.width;
  17793. this._canvas.height = textureSize.height;
  17794. this.releaseInternalTexture();
  17795. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17796. };
  17797. DynamicTexture.prototype.getContext = function () {
  17798. return this._context;
  17799. };
  17800. DynamicTexture.prototype.clear = function () {
  17801. var size = this.getSize();
  17802. this._context.fillRect(0, 0, size.width, size.height);
  17803. };
  17804. DynamicTexture.prototype.update = function (invertY) {
  17805. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17806. };
  17807. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17808. if (update === void 0) { update = true; }
  17809. var size = this.getSize();
  17810. if (clearColor) {
  17811. this._context.fillStyle = clearColor;
  17812. this._context.fillRect(0, 0, size.width, size.height);
  17813. }
  17814. this._context.font = font;
  17815. if (x === null) {
  17816. var textSize = this._context.measureText(text);
  17817. x = (size.width - textSize.width) / 2;
  17818. }
  17819. this._context.fillStyle = color;
  17820. this._context.fillText(text, x, y);
  17821. if (update) {
  17822. this.update(invertY);
  17823. }
  17824. };
  17825. DynamicTexture.prototype.clone = function () {
  17826. var textureSize = this.getSize();
  17827. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17828. // Base texture
  17829. newTexture.hasAlpha = this.hasAlpha;
  17830. newTexture.level = this.level;
  17831. // Dynamic Texture
  17832. newTexture.wrapU = this.wrapU;
  17833. newTexture.wrapV = this.wrapV;
  17834. return newTexture;
  17835. };
  17836. return DynamicTexture;
  17837. })(BABYLON.Texture);
  17838. BABYLON.DynamicTexture = DynamicTexture;
  17839. })(BABYLON || (BABYLON = {}));
  17840. var BABYLON;
  17841. (function (BABYLON) {
  17842. var VideoTexture = (function (_super) {
  17843. __extends(VideoTexture, _super);
  17844. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17845. var _this = this;
  17846. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17847. if (invertY === void 0) { invertY = false; }
  17848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17849. _super.call(this, null, scene, !generateMipMaps, invertY);
  17850. this._autoLaunch = true;
  17851. this.name = name;
  17852. this.video = document.createElement("video");
  17853. this.video.autoplay = false;
  17854. this.video.loop = true;
  17855. this.video.addEventListener("canplaythrough", function () {
  17856. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17857. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17858. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17859. }
  17860. else {
  17861. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17862. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17863. generateMipMaps = false;
  17864. }
  17865. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17866. _this._texture.isReady = true;
  17867. });
  17868. urls.forEach(function (url) {
  17869. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17870. var source = document.createElement("source");
  17871. source.src = url;
  17872. _this.video.appendChild(source);
  17873. });
  17874. this._lastUpdate = BABYLON.Tools.Now;
  17875. }
  17876. VideoTexture.prototype.update = function () {
  17877. if (this._autoLaunch) {
  17878. this._autoLaunch = false;
  17879. this.video.play();
  17880. }
  17881. var now = BABYLON.Tools.Now;
  17882. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17883. return false;
  17884. }
  17885. this._lastUpdate = now;
  17886. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17887. return true;
  17888. };
  17889. return VideoTexture;
  17890. })(BABYLON.Texture);
  17891. BABYLON.VideoTexture = VideoTexture;
  17892. })(BABYLON || (BABYLON = {}));
  17893. var BABYLON;
  17894. (function (BABYLON) {
  17895. var CustomProceduralTexture = (function (_super) {
  17896. __extends(CustomProceduralTexture, _super);
  17897. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17898. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17899. this._animate = true;
  17900. this._time = 0;
  17901. this._texturePath = texturePath;
  17902. //Try to load json
  17903. this.loadJson(texturePath);
  17904. this.refreshRate = 1;
  17905. }
  17906. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17907. var _this = this;
  17908. var that = this;
  17909. function noConfigFile() {
  17910. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17911. try {
  17912. that.setFragment(that._texturePath);
  17913. }
  17914. catch (ex) {
  17915. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17916. }
  17917. }
  17918. var configFileUrl = jsonUrl + "/config.json";
  17919. var xhr = new XMLHttpRequest();
  17920. xhr.open("GET", configFileUrl, true);
  17921. xhr.addEventListener("load", function () {
  17922. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17923. try {
  17924. _this._config = JSON.parse(xhr.response);
  17925. _this.updateShaderUniforms();
  17926. _this.updateTextures();
  17927. _this.setFragment(_this._texturePath + "/custom");
  17928. _this._animate = _this._config.animate;
  17929. _this.refreshRate = _this._config.refreshrate;
  17930. }
  17931. catch (ex) {
  17932. noConfigFile();
  17933. }
  17934. }
  17935. else {
  17936. noConfigFile();
  17937. }
  17938. }, false);
  17939. xhr.addEventListener("error", function () {
  17940. noConfigFile();
  17941. }, false);
  17942. try {
  17943. xhr.send();
  17944. }
  17945. catch (ex) {
  17946. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17947. }
  17948. };
  17949. CustomProceduralTexture.prototype.isReady = function () {
  17950. if (!_super.prototype.isReady.call(this)) {
  17951. return false;
  17952. }
  17953. for (var name in this._textures) {
  17954. var texture = this._textures[name];
  17955. if (!texture.isReady()) {
  17956. return false;
  17957. }
  17958. }
  17959. return true;
  17960. };
  17961. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17962. if (this._animate) {
  17963. this._time += this.getScene().getAnimationRatio() * 0.03;
  17964. this.updateShaderUniforms();
  17965. }
  17966. _super.prototype.render.call(this, useCameraPostProcess);
  17967. };
  17968. CustomProceduralTexture.prototype.updateTextures = function () {
  17969. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17970. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17971. }
  17972. };
  17973. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17974. if (this._config) {
  17975. for (var j = 0; j < this._config.uniforms.length; j++) {
  17976. var uniform = this._config.uniforms[j];
  17977. switch (uniform.type) {
  17978. case "float":
  17979. this.setFloat(uniform.name, uniform.value);
  17980. break;
  17981. case "color3":
  17982. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17983. break;
  17984. case "color4":
  17985. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17986. break;
  17987. case "vector2":
  17988. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17989. break;
  17990. case "vector3":
  17991. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17992. break;
  17993. }
  17994. }
  17995. }
  17996. this.setFloat("time", this._time);
  17997. };
  17998. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17999. get: function () {
  18000. return this._animate;
  18001. },
  18002. set: function (value) {
  18003. this._animate = value;
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. return CustomProceduralTexture;
  18009. })(BABYLON.ProceduralTexture);
  18010. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18011. })(BABYLON || (BABYLON = {}));
  18012. var BABYLON;
  18013. (function (BABYLON) {
  18014. var EffectFallbacks = (function () {
  18015. function EffectFallbacks() {
  18016. this._defines = {};
  18017. this._currentRank = 32;
  18018. this._maxRank = -1;
  18019. }
  18020. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18021. if (!this._defines[rank]) {
  18022. if (rank < this._currentRank) {
  18023. this._currentRank = rank;
  18024. }
  18025. if (rank > this._maxRank) {
  18026. this._maxRank = rank;
  18027. }
  18028. this._defines[rank] = new Array();
  18029. }
  18030. this._defines[rank].push(define);
  18031. };
  18032. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18033. this._meshRank = rank;
  18034. this._mesh = mesh;
  18035. if (rank > this._maxRank) {
  18036. this._maxRank = rank;
  18037. }
  18038. };
  18039. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18040. get: function () {
  18041. return this._currentRank <= this._maxRank;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18047. var currentFallbacks = this._defines[this._currentRank];
  18048. for (var index = 0; index < currentFallbacks.length; index++) {
  18049. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18050. }
  18051. if (this._mesh && this._currentRank === this._meshRank) {
  18052. this._mesh.computeBonesUsingShaders = false;
  18053. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18054. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18055. }
  18056. this._currentRank++;
  18057. return currentDefines;
  18058. };
  18059. return EffectFallbacks;
  18060. })();
  18061. BABYLON.EffectFallbacks = EffectFallbacks;
  18062. var Effect = (function () {
  18063. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18064. var _this = this;
  18065. this._isReady = false;
  18066. this._compilationError = "";
  18067. this._valueCache = [];
  18068. this._engine = engine;
  18069. this.name = baseName;
  18070. this.defines = defines;
  18071. this._uniformsNames = uniformsNames.concat(samplers);
  18072. this._samplers = samplers;
  18073. this._attributesNames = attributesNames;
  18074. this.onError = onError;
  18075. this.onCompiled = onCompiled;
  18076. var vertexSource;
  18077. var fragmentSource;
  18078. if (baseName.vertexElement) {
  18079. vertexSource = document.getElementById(baseName.vertexElement);
  18080. if (!vertexSource) {
  18081. vertexSource = baseName.vertexElement;
  18082. }
  18083. }
  18084. else {
  18085. vertexSource = baseName.vertex || baseName;
  18086. }
  18087. if (baseName.fragmentElement) {
  18088. fragmentSource = document.getElementById(baseName.fragmentElement);
  18089. if (!fragmentSource) {
  18090. fragmentSource = baseName.fragmentElement;
  18091. }
  18092. }
  18093. else {
  18094. fragmentSource = baseName.fragment || baseName;
  18095. }
  18096. this._loadVertexShader(vertexSource, function (vertexCode) {
  18097. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18098. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18099. });
  18100. });
  18101. }
  18102. // Properties
  18103. Effect.prototype.isReady = function () {
  18104. return this._isReady;
  18105. };
  18106. Effect.prototype.getProgram = function () {
  18107. return this._program;
  18108. };
  18109. Effect.prototype.getAttributesNames = function () {
  18110. return this._attributesNames;
  18111. };
  18112. Effect.prototype.getAttributeLocation = function (index) {
  18113. return this._attributes[index];
  18114. };
  18115. Effect.prototype.getAttributeLocationByName = function (name) {
  18116. var index = this._attributesNames.indexOf(name);
  18117. return this._attributes[index];
  18118. };
  18119. Effect.prototype.getAttributesCount = function () {
  18120. return this._attributes.length;
  18121. };
  18122. Effect.prototype.getUniformIndex = function (uniformName) {
  18123. return this._uniformsNames.indexOf(uniformName);
  18124. };
  18125. Effect.prototype.getUniform = function (uniformName) {
  18126. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18127. };
  18128. Effect.prototype.getSamplers = function () {
  18129. return this._samplers;
  18130. };
  18131. Effect.prototype.getCompilationError = function () {
  18132. return this._compilationError;
  18133. };
  18134. // Methods
  18135. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18136. // DOM element ?
  18137. if (vertex instanceof HTMLElement) {
  18138. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18139. callback(vertexCode);
  18140. return;
  18141. }
  18142. // Is in local store ?
  18143. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18144. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18145. return;
  18146. }
  18147. var vertexShaderUrl;
  18148. if (vertex[0] === "." || vertex[0] === "/") {
  18149. vertexShaderUrl = vertex;
  18150. }
  18151. else {
  18152. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18153. }
  18154. // Vertex shader
  18155. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18156. };
  18157. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18158. // DOM element ?
  18159. if (fragment instanceof HTMLElement) {
  18160. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18161. callback(fragmentCode);
  18162. return;
  18163. }
  18164. // Is in local store ?
  18165. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18166. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18167. return;
  18168. }
  18169. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18170. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18171. return;
  18172. }
  18173. var fragmentShaderUrl;
  18174. if (fragment[0] === "." || fragment[0] === "/") {
  18175. fragmentShaderUrl = fragment;
  18176. }
  18177. else {
  18178. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18179. }
  18180. // Fragment shader
  18181. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18182. };
  18183. Effect.prototype._dumpShadersName = function () {
  18184. if (this.name.vertexElement) {
  18185. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18186. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18187. }
  18188. else if (this.name.vertex) {
  18189. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18190. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18191. }
  18192. else {
  18193. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18194. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18195. }
  18196. };
  18197. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18198. try {
  18199. var engine = this._engine;
  18200. if (!engine.getCaps().highPrecisionShaderSupported) {
  18201. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18202. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18203. }
  18204. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18205. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18206. this._attributes = engine.getAttributes(this._program, attributesNames);
  18207. for (var index = 0; index < this._samplers.length; index++) {
  18208. var sampler = this.getUniform(this._samplers[index]);
  18209. if (sampler == null) {
  18210. this._samplers.splice(index, 1);
  18211. index--;
  18212. }
  18213. }
  18214. engine.bindSamplers(this);
  18215. this._isReady = true;
  18216. if (this.onCompiled) {
  18217. this.onCompiled(this);
  18218. }
  18219. }
  18220. catch (e) {
  18221. // Is it a problem with precision?
  18222. if (e.message.indexOf("highp") !== -1) {
  18223. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18224. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18225. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18226. return;
  18227. }
  18228. // Let's go through fallbacks then
  18229. if (fallbacks && fallbacks.isMoreFallbacks) {
  18230. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18231. this._dumpShadersName();
  18232. defines = fallbacks.reduce(defines);
  18233. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18234. }
  18235. else {
  18236. BABYLON.Tools.Error("Unable to compile effect: ");
  18237. this._dumpShadersName();
  18238. BABYLON.Tools.Error("Defines: " + defines);
  18239. BABYLON.Tools.Error("Error: " + e.message);
  18240. this._compilationError = e.message;
  18241. if (this.onError) {
  18242. this.onError(this, this._compilationError);
  18243. }
  18244. }
  18245. }
  18246. };
  18247. Object.defineProperty(Effect.prototype, "isSupported", {
  18248. get: function () {
  18249. return this._compilationError === "";
  18250. },
  18251. enumerable: true,
  18252. configurable: true
  18253. });
  18254. Effect.prototype._bindTexture = function (channel, texture) {
  18255. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18256. };
  18257. Effect.prototype.setTexture = function (channel, texture) {
  18258. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18259. };
  18260. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18261. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18262. };
  18263. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18264. if (!this._valueCache[uniformName]) {
  18265. this._valueCache[uniformName] = new BABYLON.Matrix();
  18266. }
  18267. for (var index = 0; index < 16; index++) {
  18268. this._valueCache[uniformName].m[index] = matrix.m[index];
  18269. }
  18270. };
  18271. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18272. if (!this._valueCache[uniformName]) {
  18273. this._valueCache[uniformName] = [x, y];
  18274. return;
  18275. }
  18276. this._valueCache[uniformName][0] = x;
  18277. this._valueCache[uniformName][1] = y;
  18278. };
  18279. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18280. if (!this._valueCache[uniformName]) {
  18281. this._valueCache[uniformName] = [x, y, z];
  18282. return;
  18283. }
  18284. this._valueCache[uniformName][0] = x;
  18285. this._valueCache[uniformName][1] = y;
  18286. this._valueCache[uniformName][2] = z;
  18287. };
  18288. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18289. if (!this._valueCache[uniformName]) {
  18290. this._valueCache[uniformName] = [x, y, z, w];
  18291. return;
  18292. }
  18293. this._valueCache[uniformName][0] = x;
  18294. this._valueCache[uniformName][1] = y;
  18295. this._valueCache[uniformName][2] = z;
  18296. this._valueCache[uniformName][3] = w;
  18297. };
  18298. Effect.prototype.setArray = function (uniformName, array) {
  18299. this._engine.setArray(this.getUniform(uniformName), array);
  18300. return this;
  18301. };
  18302. Effect.prototype.setArray2 = function (uniformName, array) {
  18303. this._engine.setArray2(this.getUniform(uniformName), array);
  18304. return this;
  18305. };
  18306. Effect.prototype.setArray3 = function (uniformName, array) {
  18307. this._engine.setArray3(this.getUniform(uniformName), array);
  18308. return this;
  18309. };
  18310. Effect.prototype.setArray4 = function (uniformName, array) {
  18311. this._engine.setArray4(this.getUniform(uniformName), array);
  18312. return this;
  18313. };
  18314. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18315. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18316. return this;
  18317. };
  18318. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18319. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18320. return this;
  18321. this._cacheMatrix(uniformName, matrix);
  18322. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18323. return this;
  18324. };
  18325. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18326. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18327. return this;
  18328. };
  18329. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18330. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18331. return this;
  18332. };
  18333. Effect.prototype.setFloat = function (uniformName, value) {
  18334. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18335. return this;
  18336. this._valueCache[uniformName] = value;
  18337. this._engine.setFloat(this.getUniform(uniformName), value);
  18338. return this;
  18339. };
  18340. Effect.prototype.setBool = function (uniformName, bool) {
  18341. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18342. return this;
  18343. this._valueCache[uniformName] = bool;
  18344. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18345. return this;
  18346. };
  18347. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18348. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18349. return this;
  18350. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18351. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18352. return this;
  18353. };
  18354. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18355. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18356. return this;
  18357. this._cacheFloat2(uniformName, x, y);
  18358. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18359. return this;
  18360. };
  18361. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18362. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18363. return this;
  18364. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18365. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18366. return this;
  18367. };
  18368. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18369. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18370. return this;
  18371. this._cacheFloat3(uniformName, x, y, z);
  18372. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18373. return this;
  18374. };
  18375. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18376. 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)
  18377. return this;
  18378. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18379. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18380. return this;
  18381. };
  18382. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18383. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18384. return this;
  18385. this._cacheFloat4(uniformName, x, y, z, w);
  18386. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18387. return this;
  18388. };
  18389. Effect.prototype.setColor3 = function (uniformName, color3) {
  18390. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18391. return this;
  18392. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18393. this._engine.setColor3(this.getUniform(uniformName), color3);
  18394. return this;
  18395. };
  18396. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18397. 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)
  18398. return this;
  18399. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18400. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18401. return this;
  18402. };
  18403. // Statics
  18404. Effect.ShadersStore = {};
  18405. return Effect;
  18406. })();
  18407. BABYLON.Effect = Effect;
  18408. })(BABYLON || (BABYLON = {}));
  18409. var BABYLON;
  18410. (function (BABYLON) {
  18411. var MaterialDefines = (function () {
  18412. function MaterialDefines() {
  18413. }
  18414. MaterialDefines.prototype.isEqual = function (other) {
  18415. for (var index = 0; index < this._keys.length; index++) {
  18416. var prop = this._keys[index];
  18417. if (this[prop] !== other[prop]) {
  18418. return false;
  18419. }
  18420. }
  18421. return true;
  18422. };
  18423. MaterialDefines.prototype.cloneTo = function (other) {
  18424. for (var index = 0; index < this._keys.length; index++) {
  18425. var prop = this._keys[index];
  18426. other[prop] = this[prop];
  18427. }
  18428. };
  18429. MaterialDefines.prototype.reset = function () {
  18430. for (var index = 0; index < this._keys.length; index++) {
  18431. var prop = this._keys[index];
  18432. if (typeof (this[prop]) === "number") {
  18433. this[prop] = 0;
  18434. }
  18435. else {
  18436. this[prop] = false;
  18437. }
  18438. }
  18439. };
  18440. MaterialDefines.prototype.toString = function () {
  18441. var result = "";
  18442. for (var index = 0; index < this._keys.length; index++) {
  18443. var prop = this._keys[index];
  18444. if (typeof (this[prop]) === "number") {
  18445. result += "#define " + prop + " " + this[prop] + "\n";
  18446. }
  18447. else if (this[prop]) {
  18448. result += "#define " + prop + "\n";
  18449. }
  18450. }
  18451. return result;
  18452. };
  18453. return MaterialDefines;
  18454. })();
  18455. BABYLON.MaterialDefines = MaterialDefines;
  18456. var Material = (function () {
  18457. function Material(name, scene, doNotAdd) {
  18458. this.name = name;
  18459. this.checkReadyOnEveryCall = false;
  18460. this.checkReadyOnlyOnce = false;
  18461. this.state = "";
  18462. this.alpha = 1.0;
  18463. this.backFaceCulling = true;
  18464. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18465. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18466. this.disableDepthWrite = false;
  18467. this.fogEnabled = true;
  18468. this._wasPreviouslyReady = false;
  18469. this._fillMode = Material.TriangleFillMode;
  18470. this.pointSize = 1.0;
  18471. this.zOffset = 0;
  18472. this.id = name;
  18473. this._scene = scene;
  18474. if (!doNotAdd) {
  18475. scene.materials.push(this);
  18476. }
  18477. }
  18478. Object.defineProperty(Material, "TriangleFillMode", {
  18479. get: function () {
  18480. return Material._TriangleFillMode;
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. Object.defineProperty(Material, "WireFrameFillMode", {
  18486. get: function () {
  18487. return Material._WireFrameFillMode;
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(Material, "PointFillMode", {
  18493. get: function () {
  18494. return Material._PointFillMode;
  18495. },
  18496. enumerable: true,
  18497. configurable: true
  18498. });
  18499. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18500. get: function () {
  18501. return Material._ClockWiseSideOrientation;
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18507. get: function () {
  18508. return Material._CounterClockWiseSideOrientation;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. Object.defineProperty(Material.prototype, "wireframe", {
  18514. get: function () {
  18515. return this._fillMode === Material.WireFrameFillMode;
  18516. },
  18517. set: function (value) {
  18518. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18519. },
  18520. enumerable: true,
  18521. configurable: true
  18522. });
  18523. Object.defineProperty(Material.prototype, "pointsCloud", {
  18524. get: function () {
  18525. return this._fillMode === Material.PointFillMode;
  18526. },
  18527. set: function (value) {
  18528. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(Material.prototype, "fillMode", {
  18534. get: function () {
  18535. return this._fillMode;
  18536. },
  18537. set: function (value) {
  18538. this._fillMode = value;
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. Material.prototype.isReady = function (mesh, useInstances) {
  18544. return true;
  18545. };
  18546. Material.prototype.getEffect = function () {
  18547. return this._effect;
  18548. };
  18549. Material.prototype.getScene = function () {
  18550. return this._scene;
  18551. };
  18552. Material.prototype.needAlphaBlending = function () {
  18553. return (this.alpha < 1.0);
  18554. };
  18555. Material.prototype.needAlphaTesting = function () {
  18556. return false;
  18557. };
  18558. Material.prototype.getAlphaTestTexture = function () {
  18559. return null;
  18560. };
  18561. Material.prototype.trackCreation = function (onCompiled, onError) {
  18562. };
  18563. Material.prototype.markDirty = function () {
  18564. this._wasPreviouslyReady = false;
  18565. };
  18566. Material.prototype._preBind = function () {
  18567. var engine = this._scene.getEngine();
  18568. engine.enableEffect(this._effect);
  18569. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18570. };
  18571. Material.prototype.bind = function (world, mesh) {
  18572. this._scene._cachedMaterial = this;
  18573. if (this.onBind) {
  18574. this.onBind(this, mesh);
  18575. }
  18576. if (this.disableDepthWrite) {
  18577. var engine = this._scene.getEngine();
  18578. this._cachedDepthWriteState = engine.getDepthWrite();
  18579. engine.setDepthWrite(false);
  18580. }
  18581. };
  18582. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18583. };
  18584. Material.prototype.unbind = function () {
  18585. if (this.disableDepthWrite) {
  18586. var engine = this._scene.getEngine();
  18587. engine.setDepthWrite(this._cachedDepthWriteState);
  18588. }
  18589. };
  18590. Material.prototype.clone = function (name) {
  18591. return null;
  18592. };
  18593. Material.prototype.getBindedMeshes = function () {
  18594. var result = new Array();
  18595. for (var index = 0; index < this._scene.meshes.length; index++) {
  18596. var mesh = this._scene.meshes[index];
  18597. if (mesh.material === this) {
  18598. result.push(mesh);
  18599. }
  18600. }
  18601. return result;
  18602. };
  18603. Material.prototype.dispose = function (forceDisposeEffect) {
  18604. // Animations
  18605. this.getScene().stopAnimation(this);
  18606. // Remove from scene
  18607. var index = this._scene.materials.indexOf(this);
  18608. if (index >= 0) {
  18609. this._scene.materials.splice(index, 1);
  18610. }
  18611. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18612. if (forceDisposeEffect && this._effect) {
  18613. this._scene.getEngine()._releaseEffect(this._effect);
  18614. this._effect = null;
  18615. }
  18616. // Remove from meshes
  18617. for (index = 0; index < this._scene.meshes.length; index++) {
  18618. var mesh = this._scene.meshes[index];
  18619. if (mesh.material === this) {
  18620. mesh.material = null;
  18621. }
  18622. }
  18623. // Callback
  18624. if (this.onDispose) {
  18625. this.onDispose();
  18626. }
  18627. };
  18628. Material.prototype.copyTo = function (other) {
  18629. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18630. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18631. other.alpha = this.alpha;
  18632. other.fillMode = this.fillMode;
  18633. other.backFaceCulling = this.backFaceCulling;
  18634. other.fogEnabled = this.fogEnabled;
  18635. other.wireframe = this.wireframe;
  18636. other.zOffset = this.zOffset;
  18637. other.alphaMode = this.alphaMode;
  18638. other.sideOrientation = this.sideOrientation;
  18639. other.disableDepthWrite = this.disableDepthWrite;
  18640. other.pointSize = this.pointSize;
  18641. other.pointsCloud = this.pointsCloud;
  18642. };
  18643. Material.prototype.serialize = function () {
  18644. var serializationObject = {};
  18645. serializationObject.name = this.name;
  18646. serializationObject.alpha = this.alpha;
  18647. serializationObject.id = this.id;
  18648. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18649. serializationObject.backFaceCulling = this.backFaceCulling;
  18650. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18651. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18652. return serializationObject;
  18653. };
  18654. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18655. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18656. multiMaterial.id = parsedMultiMaterial.id;
  18657. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18658. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18659. var subMatId = parsedMultiMaterial.materials[matIndex];
  18660. if (subMatId) {
  18661. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18662. }
  18663. else {
  18664. multiMaterial.subMaterials.push(null);
  18665. }
  18666. }
  18667. return multiMaterial;
  18668. };
  18669. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  18670. if (!parsedMaterial.customType) {
  18671. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  18672. }
  18673. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  18674. return materialType.Parse(parsedMaterial, scene, rootUrl);
  18675. ;
  18676. };
  18677. Material._TriangleFillMode = 0;
  18678. Material._WireFrameFillMode = 1;
  18679. Material._PointFillMode = 2;
  18680. Material._ClockWiseSideOrientation = 0;
  18681. Material._CounterClockWiseSideOrientation = 1;
  18682. return Material;
  18683. })();
  18684. BABYLON.Material = Material;
  18685. })(BABYLON || (BABYLON = {}));
  18686. var BABYLON;
  18687. (function (BABYLON) {
  18688. var maxSimultaneousLights = 4;
  18689. var FresnelParameters = (function () {
  18690. function FresnelParameters() {
  18691. this.isEnabled = true;
  18692. this.leftColor = BABYLON.Color3.White();
  18693. this.rightColor = BABYLON.Color3.Black();
  18694. this.bias = 0;
  18695. this.power = 1;
  18696. }
  18697. FresnelParameters.prototype.clone = function () {
  18698. var newFresnelParameters = new FresnelParameters();
  18699. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18700. return new FresnelParameters;
  18701. };
  18702. FresnelParameters.prototype.serialize = function () {
  18703. var serializationObject = {};
  18704. serializationObject.isEnabled = this.isEnabled;
  18705. serializationObject.leftColor = this.leftColor;
  18706. serializationObject.rightColor = this.rightColor;
  18707. serializationObject.bias = this.bias;
  18708. serializationObject.power = this.power;
  18709. return serializationObject;
  18710. };
  18711. FresnelParameters.Parse = function (parsedFresnelParameters) {
  18712. var fresnelParameters = new FresnelParameters();
  18713. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18714. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18715. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18716. fresnelParameters.bias = parsedFresnelParameters.bias;
  18717. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18718. return fresnelParameters;
  18719. };
  18720. return FresnelParameters;
  18721. })();
  18722. BABYLON.FresnelParameters = FresnelParameters;
  18723. var StandardMaterialDefines = (function (_super) {
  18724. __extends(StandardMaterialDefines, _super);
  18725. function StandardMaterialDefines() {
  18726. _super.call(this);
  18727. this.DIFFUSE = false;
  18728. this.AMBIENT = false;
  18729. this.OPACITY = false;
  18730. this.OPACITYRGB = false;
  18731. this.REFLECTION = false;
  18732. this.EMISSIVE = false;
  18733. this.SPECULAR = false;
  18734. this.BUMP = false;
  18735. this.SPECULAROVERALPHA = false;
  18736. this.CLIPPLANE = false;
  18737. this.ALPHATEST = false;
  18738. this.ALPHAFROMDIFFUSE = false;
  18739. this.POINTSIZE = false;
  18740. this.FOG = false;
  18741. this.LIGHT0 = false;
  18742. this.LIGHT1 = false;
  18743. this.LIGHT2 = false;
  18744. this.LIGHT3 = false;
  18745. this.SPOTLIGHT0 = false;
  18746. this.SPOTLIGHT1 = false;
  18747. this.SPOTLIGHT2 = false;
  18748. this.SPOTLIGHT3 = false;
  18749. this.HEMILIGHT0 = false;
  18750. this.HEMILIGHT1 = false;
  18751. this.HEMILIGHT2 = false;
  18752. this.HEMILIGHT3 = false;
  18753. this.POINTLIGHT0 = false;
  18754. this.POINTLIGHT1 = false;
  18755. this.POINTLIGHT2 = false;
  18756. this.POINTLIGHT3 = false;
  18757. this.DIRLIGHT0 = false;
  18758. this.DIRLIGHT1 = false;
  18759. this.DIRLIGHT2 = false;
  18760. this.DIRLIGHT3 = false;
  18761. this.SPECULARTERM = false;
  18762. this.SHADOW0 = false;
  18763. this.SHADOW1 = false;
  18764. this.SHADOW2 = false;
  18765. this.SHADOW3 = false;
  18766. this.SHADOWS = false;
  18767. this.SHADOWVSM0 = false;
  18768. this.SHADOWVSM1 = false;
  18769. this.SHADOWVSM2 = false;
  18770. this.SHADOWVSM3 = false;
  18771. this.SHADOWPCF0 = false;
  18772. this.SHADOWPCF1 = false;
  18773. this.SHADOWPCF2 = false;
  18774. this.SHADOWPCF3 = false;
  18775. this.DIFFUSEFRESNEL = false;
  18776. this.OPACITYFRESNEL = false;
  18777. this.REFLECTIONFRESNEL = false;
  18778. this.EMISSIVEFRESNEL = false;
  18779. this.FRESNEL = false;
  18780. this.NORMAL = false;
  18781. this.UV1 = false;
  18782. this.UV2 = false;
  18783. this.VERTEXCOLOR = false;
  18784. this.VERTEXALPHA = false;
  18785. this.NUM_BONE_INFLUENCERS = 0;
  18786. this.BonesPerMesh = 0;
  18787. this.INSTANCES = false;
  18788. this.GLOSSINESS = false;
  18789. this.ROUGHNESS = false;
  18790. this.EMISSIVEASILLUMINATION = false;
  18791. this.LINKEMISSIVEWITHDIFFUSE = false;
  18792. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18793. this.LIGHTMAP = false;
  18794. this.USELIGHTMAPASSHADOWMAP = false;
  18795. this.REFLECTIONMAP_3D = false;
  18796. this.REFLECTIONMAP_SPHERICAL = false;
  18797. this.REFLECTIONMAP_PLANAR = false;
  18798. this.REFLECTIONMAP_CUBIC = false;
  18799. this.REFLECTIONMAP_PROJECTION = false;
  18800. this.REFLECTIONMAP_SKYBOX = false;
  18801. this.REFLECTIONMAP_EXPLICIT = false;
  18802. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18803. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18804. this.INVERTCUBICMAP = false;
  18805. this.LOGARITHMICDEPTH = false;
  18806. this._keys = Object.keys(this);
  18807. }
  18808. return StandardMaterialDefines;
  18809. })(BABYLON.MaterialDefines);
  18810. var StandardMaterial = (function (_super) {
  18811. __extends(StandardMaterial, _super);
  18812. function StandardMaterial(name, scene) {
  18813. var _this = this;
  18814. _super.call(this, name, scene);
  18815. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18816. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18817. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18818. this.specularPower = 64;
  18819. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18820. this.useAlphaFromDiffuseTexture = false;
  18821. this.useEmissiveAsIllumination = false;
  18822. this.linkEmissiveWithDiffuse = false;
  18823. this.useReflectionFresnelFromSpecular = false;
  18824. this.useSpecularOverAlpha = true;
  18825. this.disableLighting = false;
  18826. this.roughness = 0;
  18827. this.useLightmapAsShadowmap = false;
  18828. this.useGlossinessFromSpecularMapAlpha = false;
  18829. this._renderTargets = new BABYLON.SmartArray(16);
  18830. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18831. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18832. this._defines = new StandardMaterialDefines();
  18833. this._cachedDefines = new StandardMaterialDefines();
  18834. this._cachedDefines.BonesPerMesh = -1;
  18835. this.getRenderTargetTextures = function () {
  18836. _this._renderTargets.reset();
  18837. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18838. _this._renderTargets.push(_this.reflectionTexture);
  18839. }
  18840. return _this._renderTargets;
  18841. };
  18842. }
  18843. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18844. get: function () {
  18845. return this._useLogarithmicDepth;
  18846. },
  18847. set: function (value) {
  18848. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. StandardMaterial.prototype.needAlphaBlending = function () {
  18854. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18855. };
  18856. StandardMaterial.prototype.needAlphaTesting = function () {
  18857. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18858. };
  18859. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18860. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18861. };
  18862. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18863. return this.diffuseTexture;
  18864. };
  18865. // Methods
  18866. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18867. if (!mesh) {
  18868. return true;
  18869. }
  18870. if (this._defines.INSTANCES !== useInstances) {
  18871. return false;
  18872. }
  18873. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18874. return true;
  18875. }
  18876. return false;
  18877. };
  18878. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18879. var lightIndex = 0;
  18880. var needNormals = false;
  18881. for (var index = 0; index < scene.lights.length; index++) {
  18882. var light = scene.lights[index];
  18883. if (!light.isEnabled()) {
  18884. continue;
  18885. }
  18886. // Excluded check
  18887. if (light._excludedMeshesIds.length > 0) {
  18888. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18889. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18890. if (excludedMesh) {
  18891. light.excludedMeshes.push(excludedMesh);
  18892. }
  18893. }
  18894. light._excludedMeshesIds = [];
  18895. }
  18896. // Included check
  18897. if (light._includedOnlyMeshesIds.length > 0) {
  18898. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18899. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18900. if (includedOnlyMesh) {
  18901. light.includedOnlyMeshes.push(includedOnlyMesh);
  18902. }
  18903. }
  18904. light._includedOnlyMeshesIds = [];
  18905. }
  18906. if (!light.canAffectMesh(mesh)) {
  18907. continue;
  18908. }
  18909. needNormals = true;
  18910. defines["LIGHT" + lightIndex] = true;
  18911. var type;
  18912. if (light instanceof BABYLON.SpotLight) {
  18913. type = "SPOTLIGHT" + lightIndex;
  18914. }
  18915. else if (light instanceof BABYLON.HemisphericLight) {
  18916. type = "HEMILIGHT" + lightIndex;
  18917. }
  18918. else if (light instanceof BABYLON.PointLight) {
  18919. type = "POINTLIGHT" + lightIndex;
  18920. }
  18921. else {
  18922. type = "DIRLIGHT" + lightIndex;
  18923. }
  18924. defines[type] = true;
  18925. // Specular
  18926. if (!light.specular.equalsFloats(0, 0, 0)) {
  18927. defines["SPECULARTERM"] = true;
  18928. }
  18929. // Shadows
  18930. if (scene.shadowsEnabled) {
  18931. var shadowGenerator = light.getShadowGenerator();
  18932. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18933. defines["SHADOW" + lightIndex] = true;
  18934. defines["SHADOWS"] = true;
  18935. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18936. defines["SHADOWVSM" + lightIndex] = true;
  18937. }
  18938. if (shadowGenerator.usePoissonSampling) {
  18939. defines["SHADOWPCF" + lightIndex] = true;
  18940. }
  18941. }
  18942. }
  18943. lightIndex++;
  18944. if (lightIndex === maxSimultaneousLights)
  18945. break;
  18946. }
  18947. return needNormals;
  18948. };
  18949. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18950. var lightIndex = 0;
  18951. for (var index = 0; index < scene.lights.length; index++) {
  18952. var light = scene.lights[index];
  18953. if (!light.isEnabled()) {
  18954. continue;
  18955. }
  18956. if (!light.canAffectMesh(mesh)) {
  18957. continue;
  18958. }
  18959. if (light instanceof BABYLON.PointLight) {
  18960. // Point Light
  18961. light.transferToEffect(effect, "vLightData" + lightIndex);
  18962. }
  18963. else if (light instanceof BABYLON.DirectionalLight) {
  18964. // Directional Light
  18965. light.transferToEffect(effect, "vLightData" + lightIndex);
  18966. }
  18967. else if (light instanceof BABYLON.SpotLight) {
  18968. // Spot Light
  18969. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18970. }
  18971. else if (light instanceof BABYLON.HemisphericLight) {
  18972. // Hemispheric Light
  18973. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18974. }
  18975. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18976. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18977. if (defines["SPECULARTERM"]) {
  18978. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18979. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18980. }
  18981. // Shadows
  18982. if (scene.shadowsEnabled) {
  18983. var shadowGenerator = light.getShadowGenerator();
  18984. if (mesh.receiveShadows && shadowGenerator) {
  18985. if (!light.needCube()) {
  18986. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18987. }
  18988. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18989. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18990. }
  18991. }
  18992. lightIndex++;
  18993. if (lightIndex === maxSimultaneousLights)
  18994. break;
  18995. }
  18996. };
  18997. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18998. if (this.checkReadyOnlyOnce) {
  18999. if (this._wasPreviouslyReady) {
  19000. return true;
  19001. }
  19002. }
  19003. var scene = this.getScene();
  19004. if (!this.checkReadyOnEveryCall) {
  19005. if (this._renderId === scene.getRenderId()) {
  19006. if (this._checkCache(scene, mesh, useInstances)) {
  19007. return true;
  19008. }
  19009. }
  19010. }
  19011. var engine = scene.getEngine();
  19012. var needNormals = false;
  19013. var needUVs = false;
  19014. this._defines.reset();
  19015. // Textures
  19016. if (scene.texturesEnabled) {
  19017. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19018. if (!this.diffuseTexture.isReady()) {
  19019. return false;
  19020. }
  19021. else {
  19022. needUVs = true;
  19023. this._defines.DIFFUSE = true;
  19024. }
  19025. }
  19026. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19027. if (!this.ambientTexture.isReady()) {
  19028. return false;
  19029. }
  19030. else {
  19031. needUVs = true;
  19032. this._defines.AMBIENT = true;
  19033. }
  19034. }
  19035. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19036. if (!this.opacityTexture.isReady()) {
  19037. return false;
  19038. }
  19039. else {
  19040. needUVs = true;
  19041. this._defines.OPACITY = true;
  19042. if (this.opacityTexture.getAlphaFromRGB) {
  19043. this._defines.OPACITYRGB = true;
  19044. }
  19045. }
  19046. }
  19047. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19048. if (!this.reflectionTexture.isReady()) {
  19049. return false;
  19050. }
  19051. else {
  19052. needNormals = true;
  19053. this._defines.REFLECTION = true;
  19054. if (this.roughness > 0) {
  19055. this._defines.ROUGHNESS = true;
  19056. }
  19057. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19058. this._defines.INVERTCUBICMAP = true;
  19059. }
  19060. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19061. switch (this.reflectionTexture.coordinatesMode) {
  19062. case BABYLON.Texture.CUBIC_MODE:
  19063. case BABYLON.Texture.INVCUBIC_MODE:
  19064. this._defines.REFLECTIONMAP_CUBIC = true;
  19065. break;
  19066. case BABYLON.Texture.EXPLICIT_MODE:
  19067. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19068. break;
  19069. case BABYLON.Texture.PLANAR_MODE:
  19070. this._defines.REFLECTIONMAP_PLANAR = true;
  19071. break;
  19072. case BABYLON.Texture.PROJECTION_MODE:
  19073. this._defines.REFLECTIONMAP_PROJECTION = true;
  19074. break;
  19075. case BABYLON.Texture.SKYBOX_MODE:
  19076. this._defines.REFLECTIONMAP_SKYBOX = true;
  19077. break;
  19078. case BABYLON.Texture.SPHERICAL_MODE:
  19079. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19080. break;
  19081. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19082. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19083. break;
  19084. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19085. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19086. break;
  19087. }
  19088. }
  19089. }
  19090. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19091. if (!this.emissiveTexture.isReady()) {
  19092. return false;
  19093. }
  19094. else {
  19095. needUVs = true;
  19096. this._defines.EMISSIVE = true;
  19097. }
  19098. }
  19099. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19100. if (!this.lightmapTexture.isReady()) {
  19101. return false;
  19102. }
  19103. else {
  19104. needUVs = true;
  19105. this._defines.LIGHTMAP = true;
  19106. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19107. }
  19108. }
  19109. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19110. if (!this.specularTexture.isReady()) {
  19111. return false;
  19112. }
  19113. else {
  19114. needUVs = true;
  19115. this._defines.SPECULAR = true;
  19116. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19117. }
  19118. }
  19119. }
  19120. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19121. if (!this.bumpTexture.isReady()) {
  19122. return false;
  19123. }
  19124. else {
  19125. needUVs = true;
  19126. this._defines.BUMP = true;
  19127. }
  19128. }
  19129. // Effect
  19130. if (scene.clipPlane) {
  19131. this._defines.CLIPPLANE = true;
  19132. }
  19133. if (engine.getAlphaTesting()) {
  19134. this._defines.ALPHATEST = true;
  19135. }
  19136. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19137. this._defines.ALPHAFROMDIFFUSE = true;
  19138. }
  19139. if (this.useEmissiveAsIllumination) {
  19140. this._defines.EMISSIVEASILLUMINATION = true;
  19141. }
  19142. if (this.linkEmissiveWithDiffuse) {
  19143. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19144. }
  19145. if (this.useReflectionFresnelFromSpecular) {
  19146. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19147. }
  19148. if (this.useLogarithmicDepth) {
  19149. this._defines.LOGARITHMICDEPTH = true;
  19150. }
  19151. // Point size
  19152. if (this.pointsCloud || scene.forcePointsCloud) {
  19153. this._defines.POINTSIZE = true;
  19154. }
  19155. // Fog
  19156. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19157. this._defines.FOG = true;
  19158. }
  19159. if (scene.lightsEnabled && !this.disableLighting) {
  19160. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19161. }
  19162. if (StandardMaterial.FresnelEnabled) {
  19163. // Fresnel
  19164. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19165. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19166. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19167. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19168. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19169. this._defines.DIFFUSEFRESNEL = true;
  19170. }
  19171. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19172. this._defines.OPACITYFRESNEL = true;
  19173. }
  19174. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19175. this._defines.REFLECTIONFRESNEL = true;
  19176. }
  19177. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19178. this._defines.EMISSIVEFRESNEL = true;
  19179. }
  19180. needNormals = true;
  19181. this._defines.FRESNEL = true;
  19182. }
  19183. }
  19184. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19185. this._defines.SPECULAROVERALPHA = true;
  19186. }
  19187. // Attribs
  19188. if (mesh) {
  19189. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19190. this._defines.NORMAL = true;
  19191. }
  19192. if (needUVs) {
  19193. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19194. this._defines.UV1 = true;
  19195. }
  19196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19197. this._defines.UV2 = true;
  19198. }
  19199. }
  19200. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19201. this._defines.VERTEXCOLOR = true;
  19202. if (mesh.hasVertexAlpha) {
  19203. this._defines.VERTEXALPHA = true;
  19204. }
  19205. }
  19206. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19207. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19208. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19209. }
  19210. // Instances
  19211. if (useInstances) {
  19212. this._defines.INSTANCES = true;
  19213. }
  19214. }
  19215. // Get correct effect
  19216. if (!this._defines.isEqual(this._cachedDefines)) {
  19217. this._defines.cloneTo(this._cachedDefines);
  19218. scene.resetCachedMaterial();
  19219. // Fallbacks
  19220. var fallbacks = new BABYLON.EffectFallbacks();
  19221. if (this._defines.REFLECTION) {
  19222. fallbacks.addFallback(0, "REFLECTION");
  19223. }
  19224. if (this._defines.SPECULAR) {
  19225. fallbacks.addFallback(0, "SPECULAR");
  19226. }
  19227. if (this._defines.BUMP) {
  19228. fallbacks.addFallback(0, "BUMP");
  19229. }
  19230. if (this._defines.SPECULAROVERALPHA) {
  19231. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19232. }
  19233. if (this._defines.FOG) {
  19234. fallbacks.addFallback(1, "FOG");
  19235. }
  19236. if (this._defines.POINTSIZE) {
  19237. fallbacks.addFallback(0, "POINTSIZE");
  19238. }
  19239. if (this._defines.LOGARITHMICDEPTH) {
  19240. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19241. }
  19242. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19243. if (!this._defines["LIGHT" + lightIndex]) {
  19244. continue;
  19245. }
  19246. if (lightIndex > 0) {
  19247. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19248. }
  19249. if (this._defines["SHADOW" + lightIndex]) {
  19250. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19251. }
  19252. if (this._defines["SHADOWPCF" + lightIndex]) {
  19253. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19254. }
  19255. if (this._defines["SHADOWVSM" + lightIndex]) {
  19256. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19257. }
  19258. }
  19259. if (this._defines.SPECULARTERM) {
  19260. fallbacks.addFallback(0, "SPECULARTERM");
  19261. }
  19262. if (this._defines.DIFFUSEFRESNEL) {
  19263. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19264. }
  19265. if (this._defines.OPACITYFRESNEL) {
  19266. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19267. }
  19268. if (this._defines.REFLECTIONFRESNEL) {
  19269. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19270. }
  19271. if (this._defines.EMISSIVEFRESNEL) {
  19272. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19273. }
  19274. if (this._defines.FRESNEL) {
  19275. fallbacks.addFallback(4, "FRESNEL");
  19276. }
  19277. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19278. fallbacks.addCPUSkinningFallback(0, mesh);
  19279. }
  19280. //Attributes
  19281. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19282. if (this._defines.NORMAL) {
  19283. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19284. }
  19285. if (this._defines.UV1) {
  19286. attribs.push(BABYLON.VertexBuffer.UVKind);
  19287. }
  19288. if (this._defines.UV2) {
  19289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19290. }
  19291. if (this._defines.VERTEXCOLOR) {
  19292. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19293. }
  19294. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19297. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19300. }
  19301. }
  19302. if (this._defines.INSTANCES) {
  19303. attribs.push("world0");
  19304. attribs.push("world1");
  19305. attribs.push("world2");
  19306. attribs.push("world3");
  19307. }
  19308. // Legacy browser patch
  19309. var shaderName = "default";
  19310. if (!scene.getEngine().getCaps().standardDerivatives) {
  19311. shaderName = "legacydefault";
  19312. }
  19313. var join = this._defines.toString();
  19314. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19315. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19316. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19317. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19318. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19319. "vFogInfos", "vFogColor", "pointSize",
  19320. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19321. "mBones",
  19322. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19323. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19324. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19325. "logarithmicDepthConstant"
  19326. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19327. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19328. ], join, fallbacks, this.onCompiled, this.onError);
  19329. }
  19330. if (!this._effect.isReady()) {
  19331. return false;
  19332. }
  19333. this._renderId = scene.getRenderId();
  19334. this._wasPreviouslyReady = true;
  19335. if (mesh) {
  19336. if (!mesh._materialDefines) {
  19337. mesh._materialDefines = new StandardMaterialDefines();
  19338. }
  19339. this._defines.cloneTo(mesh._materialDefines);
  19340. }
  19341. return true;
  19342. };
  19343. StandardMaterial.prototype.unbind = function () {
  19344. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19345. this._effect.setTexture("reflection2DSampler", null);
  19346. }
  19347. _super.prototype.unbind.call(this);
  19348. };
  19349. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19350. this._effect.setMatrix("world", world);
  19351. };
  19352. StandardMaterial.prototype.bind = function (world, mesh) {
  19353. var scene = this.getScene();
  19354. // Matrices
  19355. this.bindOnlyWorldMatrix(world);
  19356. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19357. // Bones
  19358. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19359. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19360. }
  19361. if (scene.getCachedMaterial() !== this) {
  19362. if (StandardMaterial.FresnelEnabled) {
  19363. // Fresnel
  19364. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19365. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19366. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19367. }
  19368. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19369. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19370. }
  19371. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19372. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19373. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19374. }
  19375. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19376. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19377. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19378. }
  19379. }
  19380. // Textures
  19381. if (scene.texturesEnabled) {
  19382. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19383. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19384. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19385. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19386. }
  19387. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19388. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19389. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19390. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19391. }
  19392. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19393. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19394. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19395. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19396. }
  19397. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19398. if (this.reflectionTexture.isCube) {
  19399. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19400. }
  19401. else {
  19402. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19403. }
  19404. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19405. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19406. }
  19407. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19408. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19409. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19410. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19411. }
  19412. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19413. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19414. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19415. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19416. }
  19417. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19418. this._effect.setTexture("specularSampler", this.specularTexture);
  19419. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19420. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19421. }
  19422. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19423. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19424. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19425. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19426. }
  19427. }
  19428. // Clip plane
  19429. if (scene.clipPlane) {
  19430. var clipPlane = scene.clipPlane;
  19431. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19432. }
  19433. // Point size
  19434. if (this.pointsCloud) {
  19435. this._effect.setFloat("pointSize", this.pointSize);
  19436. }
  19437. // Colors
  19438. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19439. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19440. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19441. if (this._defines.SPECULARTERM) {
  19442. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19443. }
  19444. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19445. }
  19446. // Diffuse
  19447. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19448. // Lights
  19449. if (scene.lightsEnabled && !this.disableLighting) {
  19450. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19451. }
  19452. // View
  19453. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19454. this._effect.setMatrix("view", scene.getViewMatrix());
  19455. }
  19456. // Fog
  19457. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19458. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19459. this._effect.setColor3("vFogColor", scene.fogColor);
  19460. }
  19461. // Log. depth
  19462. if (this._defines.LOGARITHMICDEPTH) {
  19463. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19464. }
  19465. _super.prototype.bind.call(this, world, mesh);
  19466. };
  19467. StandardMaterial.prototype.getAnimatables = function () {
  19468. var results = [];
  19469. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19470. results.push(this.diffuseTexture);
  19471. }
  19472. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19473. results.push(this.ambientTexture);
  19474. }
  19475. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19476. results.push(this.opacityTexture);
  19477. }
  19478. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19479. results.push(this.reflectionTexture);
  19480. }
  19481. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19482. results.push(this.emissiveTexture);
  19483. }
  19484. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19485. results.push(this.specularTexture);
  19486. }
  19487. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19488. results.push(this.bumpTexture);
  19489. }
  19490. return results;
  19491. };
  19492. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19493. if (this.diffuseTexture) {
  19494. this.diffuseTexture.dispose();
  19495. }
  19496. if (this.ambientTexture) {
  19497. this.ambientTexture.dispose();
  19498. }
  19499. if (this.opacityTexture) {
  19500. this.opacityTexture.dispose();
  19501. }
  19502. if (this.reflectionTexture) {
  19503. this.reflectionTexture.dispose();
  19504. }
  19505. if (this.emissiveTexture) {
  19506. this.emissiveTexture.dispose();
  19507. }
  19508. if (this.specularTexture) {
  19509. this.specularTexture.dispose();
  19510. }
  19511. if (this.bumpTexture) {
  19512. this.bumpTexture.dispose();
  19513. }
  19514. _super.prototype.dispose.call(this, forceDisposeEffect);
  19515. };
  19516. StandardMaterial.prototype.clone = function (name) {
  19517. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19518. // Base material
  19519. this.copyTo(newStandardMaterial);
  19520. // Standard material
  19521. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19522. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19523. }
  19524. if (this.ambientTexture && this.ambientTexture.clone) {
  19525. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19526. }
  19527. if (this.opacityTexture && this.opacityTexture.clone) {
  19528. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19529. }
  19530. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19531. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19532. }
  19533. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19534. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19535. }
  19536. if (this.specularTexture && this.specularTexture.clone) {
  19537. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19538. }
  19539. if (this.bumpTexture && this.bumpTexture.clone) {
  19540. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19541. }
  19542. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19543. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19544. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19545. }
  19546. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19547. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19548. newStandardMaterial.specularColor = this.specularColor.clone();
  19549. newStandardMaterial.specularPower = this.specularPower;
  19550. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19551. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19552. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19553. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19554. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19555. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19556. newStandardMaterial.roughness = this.roughness;
  19557. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19558. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19559. }
  19560. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19561. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19562. }
  19563. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19564. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19565. }
  19566. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19567. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19568. }
  19569. return newStandardMaterial;
  19570. };
  19571. StandardMaterial.prototype.serialize = function () {
  19572. var serializationObject = _super.prototype.serialize.call(this);
  19573. serializationObject.ambient = this.ambientColor.asArray();
  19574. serializationObject.diffuse = this.diffuseColor.asArray();
  19575. serializationObject.specular = this.specularColor.asArray();
  19576. serializationObject.specularPower = this.specularPower;
  19577. serializationObject.emissive = this.emissiveColor.asArray();
  19578. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19579. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19580. if (this.diffuseTexture) {
  19581. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19582. }
  19583. if (this.diffuseFresnelParameters) {
  19584. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19585. }
  19586. if (this.ambientTexture) {
  19587. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19588. }
  19589. if (this.opacityTexture) {
  19590. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19591. }
  19592. if (this.opacityFresnelParameters) {
  19593. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19594. }
  19595. if (this.reflectionTexture) {
  19596. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19597. }
  19598. if (this.reflectionFresnelParameters) {
  19599. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19600. }
  19601. if (this.emissiveTexture) {
  19602. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19603. }
  19604. if (this.lightmapTexture) {
  19605. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19606. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19607. }
  19608. if (this.emissiveFresnelParameters) {
  19609. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19610. }
  19611. if (this.specularTexture) {
  19612. serializationObject.specularTexture = this.specularTexture.serialize();
  19613. }
  19614. if (this.bumpTexture) {
  19615. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19616. }
  19617. return serializationObject;
  19618. };
  19619. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19620. var material = new StandardMaterial(source.name, scene);
  19621. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19622. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19623. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19624. material.specularPower = source.specularPower;
  19625. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19626. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19627. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19628. material.alpha = source.alpha;
  19629. material.id = source.id;
  19630. if (source.disableDepthWrite) {
  19631. material.disableDepthWrite = source.disableDepthWrite;
  19632. }
  19633. BABYLON.Tags.AddTagsTo(material, source.tags);
  19634. material.backFaceCulling = source.backFaceCulling;
  19635. material.wireframe = source.wireframe;
  19636. if (source.diffuseTexture) {
  19637. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19638. }
  19639. if (source.diffuseFresnelParameters) {
  19640. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19641. }
  19642. if (source.ambientTexture) {
  19643. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19644. }
  19645. if (source.opacityTexture) {
  19646. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19647. }
  19648. if (source.opacityFresnelParameters) {
  19649. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19650. }
  19651. if (source.reflectionTexture) {
  19652. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19653. }
  19654. if (source.reflectionFresnelParameters) {
  19655. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  19656. }
  19657. if (source.emissiveTexture) {
  19658. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  19659. }
  19660. if (source.lightmapTexture) {
  19661. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  19662. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  19663. }
  19664. if (source.emissiveFresnelParameters) {
  19665. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  19666. }
  19667. if (source.specularTexture) {
  19668. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  19669. }
  19670. if (source.bumpTexture) {
  19671. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  19672. }
  19673. if (source.checkReadyOnlyOnce) {
  19674. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  19675. }
  19676. return material;
  19677. };
  19678. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19679. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19680. // Statics
  19681. // Flags used to enable or disable a type of texture for all Standard Materials
  19682. StandardMaterial.DiffuseTextureEnabled = true;
  19683. StandardMaterial.AmbientTextureEnabled = true;
  19684. StandardMaterial.OpacityTextureEnabled = true;
  19685. StandardMaterial.ReflectionTextureEnabled = true;
  19686. StandardMaterial.EmissiveTextureEnabled = true;
  19687. StandardMaterial.SpecularTextureEnabled = true;
  19688. StandardMaterial.BumpTextureEnabled = true;
  19689. StandardMaterial.FresnelEnabled = true;
  19690. StandardMaterial.LightmapEnabled = true;
  19691. return StandardMaterial;
  19692. })(BABYLON.Material);
  19693. BABYLON.StandardMaterial = StandardMaterial;
  19694. })(BABYLON || (BABYLON = {}));
  19695. var BABYLON;
  19696. (function (BABYLON) {
  19697. var MultiMaterial = (function (_super) {
  19698. __extends(MultiMaterial, _super);
  19699. function MultiMaterial(name, scene) {
  19700. _super.call(this, name, scene, true);
  19701. this.subMaterials = new Array();
  19702. scene.multiMaterials.push(this);
  19703. }
  19704. // Properties
  19705. MultiMaterial.prototype.getSubMaterial = function (index) {
  19706. if (index < 0 || index >= this.subMaterials.length) {
  19707. return this.getScene().defaultMaterial;
  19708. }
  19709. return this.subMaterials[index];
  19710. };
  19711. // Methods
  19712. MultiMaterial.prototype.isReady = function (mesh) {
  19713. for (var index = 0; index < this.subMaterials.length; index++) {
  19714. var subMaterial = this.subMaterials[index];
  19715. if (subMaterial) {
  19716. if (!this.subMaterials[index].isReady(mesh)) {
  19717. return false;
  19718. }
  19719. }
  19720. }
  19721. return true;
  19722. };
  19723. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  19724. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19725. for (var index = 0; index < this.subMaterials.length; index++) {
  19726. var subMaterial = null;
  19727. if (cloneChildren) {
  19728. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  19729. }
  19730. else {
  19731. subMaterial = this.subMaterials[index];
  19732. }
  19733. newMultiMaterial.subMaterials.push(subMaterial);
  19734. }
  19735. return newMultiMaterial;
  19736. };
  19737. MultiMaterial.prototype.serialize = function () {
  19738. var serializationObject = {};
  19739. serializationObject.name = this.name;
  19740. serializationObject.id = this.id;
  19741. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19742. serializationObject.materials = [];
  19743. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  19744. var subMat = this.subMaterials[matIndex];
  19745. if (subMat) {
  19746. serializationObject.materials.push(subMat.id);
  19747. }
  19748. else {
  19749. serializationObject.materials.push(null);
  19750. }
  19751. }
  19752. return serializationObject;
  19753. };
  19754. return MultiMaterial;
  19755. })(BABYLON.Material);
  19756. BABYLON.MultiMaterial = MultiMaterial;
  19757. })(BABYLON || (BABYLON = {}));
  19758. var BABYLON;
  19759. (function (BABYLON) {
  19760. var SceneLoader = (function () {
  19761. function SceneLoader() {
  19762. }
  19763. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19764. get: function () {
  19765. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19766. },
  19767. set: function (value) {
  19768. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19774. get: function () {
  19775. return SceneLoader._ShowLoadingScreen;
  19776. },
  19777. set: function (value) {
  19778. SceneLoader._ShowLoadingScreen = value;
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19784. var dotPosition = sceneFilename.lastIndexOf(".");
  19785. var queryStringPosition = sceneFilename.indexOf("?");
  19786. if (queryStringPosition === -1) {
  19787. queryStringPosition = sceneFilename.length;
  19788. }
  19789. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19790. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19791. var plugin = this._registeredPlugins[index];
  19792. if (plugin.extensions.indexOf(extension) !== -1) {
  19793. return plugin;
  19794. }
  19795. }
  19796. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19797. };
  19798. // Public functions
  19799. SceneLoader.RegisterPlugin = function (plugin) {
  19800. plugin.extensions = plugin.extensions.toLowerCase();
  19801. SceneLoader._registeredPlugins.push(plugin);
  19802. };
  19803. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19804. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19805. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19806. return;
  19807. }
  19808. var loadingToken = {};
  19809. scene._addPendingData(loadingToken);
  19810. var manifestChecked = function (success) {
  19811. scene.database = database;
  19812. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19813. var importMeshFromData = function (data) {
  19814. var meshes = [];
  19815. var particleSystems = [];
  19816. var skeletons = [];
  19817. try {
  19818. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19819. if (onerror) {
  19820. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19821. }
  19822. scene._removePendingData(loadingToken);
  19823. return;
  19824. }
  19825. }
  19826. catch (e) {
  19827. if (onerror) {
  19828. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19829. }
  19830. scene._removePendingData(loadingToken);
  19831. return;
  19832. }
  19833. if (onsuccess) {
  19834. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19835. onsuccess(meshes, particleSystems, skeletons);
  19836. scene._removePendingData(loadingToken);
  19837. }
  19838. };
  19839. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19840. // Direct load
  19841. importMeshFromData(sceneFilename.substr(5));
  19842. return;
  19843. }
  19844. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19845. importMeshFromData(data);
  19846. }, progressCallBack, database);
  19847. };
  19848. if (scene.getEngine().enableOfflineSupport) {
  19849. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19850. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19851. }
  19852. else {
  19853. manifestChecked(true);
  19854. }
  19855. };
  19856. /**
  19857. * Load a scene
  19858. * @param rootUrl a string that defines the root url for scene and resources
  19859. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19860. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19861. */
  19862. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19863. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19864. };
  19865. /**
  19866. * Append a scene
  19867. * @param rootUrl a string that defines the root url for scene and resources
  19868. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19869. * @param scene is the instance of BABYLON.Scene to append to
  19870. */
  19871. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19872. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19873. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19874. return;
  19875. }
  19876. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19877. var database;
  19878. var loadingToken = {};
  19879. scene._addPendingData(loadingToken);
  19880. if (SceneLoader.ShowLoadingScreen) {
  19881. scene.getEngine().displayLoadingUI();
  19882. }
  19883. var loadSceneFromData = function (data) {
  19884. scene.database = database;
  19885. if (!plugin.load(scene, data, rootUrl)) {
  19886. if (onerror) {
  19887. onerror(scene);
  19888. }
  19889. scene._removePendingData(loadingToken);
  19890. scene.getEngine().hideLoadingUI();
  19891. return;
  19892. }
  19893. if (onsuccess) {
  19894. onsuccess(scene);
  19895. }
  19896. scene._removePendingData(loadingToken);
  19897. if (SceneLoader.ShowLoadingScreen) {
  19898. scene.executeWhenReady(function () {
  19899. scene.getEngine().hideLoadingUI();
  19900. });
  19901. }
  19902. };
  19903. var manifestChecked = function (success) {
  19904. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19905. };
  19906. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19907. // Direct load
  19908. loadSceneFromData(sceneFilename.substr(5));
  19909. return;
  19910. }
  19911. if (rootUrl.indexOf("file:") === -1) {
  19912. if (scene.getEngine().enableOfflineSupport) {
  19913. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19914. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19915. }
  19916. else {
  19917. manifestChecked(true);
  19918. }
  19919. }
  19920. else {
  19921. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19922. }
  19923. };
  19924. // Flags
  19925. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19926. SceneLoader._ShowLoadingScreen = true;
  19927. // Members
  19928. SceneLoader._registeredPlugins = new Array();
  19929. return SceneLoader;
  19930. })();
  19931. BABYLON.SceneLoader = SceneLoader;
  19932. ;
  19933. })(BABYLON || (BABYLON = {}));
  19934. var BABYLON;
  19935. (function (BABYLON) {
  19936. var Internals;
  19937. (function (Internals) {
  19938. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19939. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  19940. var parsedMaterial = parsedData.materials[index];
  19941. if (parsedMaterial.id === id) {
  19942. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  19943. }
  19944. }
  19945. return null;
  19946. };
  19947. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19948. names = (names instanceof Array) ? names : [names];
  19949. for (var i in names) {
  19950. if (mesh.name === names[i]) {
  19951. hierarchyIds.push(mesh.id);
  19952. return true;
  19953. }
  19954. }
  19955. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19956. hierarchyIds.push(mesh.id);
  19957. return true;
  19958. }
  19959. return false;
  19960. };
  19961. BABYLON.SceneLoader.RegisterPlugin({
  19962. extensions: ".babylon",
  19963. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19964. var parsedData = JSON.parse(data);
  19965. var loadedSkeletonsIds = [];
  19966. var loadedMaterialsIds = [];
  19967. var hierarchyIds = [];
  19968. var index;
  19969. var cache;
  19970. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  19971. var parsedMesh = parsedData.meshes[index];
  19972. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19973. if (meshesNames instanceof Array) {
  19974. // Remove found mesh name from list.
  19975. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19976. }
  19977. //Geometry?
  19978. if (parsedMesh.geometryId) {
  19979. //does the file contain geometries?
  19980. if (parsedData.geometries) {
  19981. //find the correct geometry and add it to the scene
  19982. var found = false;
  19983. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19984. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19985. return;
  19986. }
  19987. else {
  19988. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19989. if (parsedGeometryData.id === parsedMesh.geometryId) {
  19990. switch (geometryType) {
  19991. case "boxes":
  19992. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  19993. break;
  19994. case "spheres":
  19995. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  19996. break;
  19997. case "cylinders":
  19998. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  19999. break;
  20000. case "toruses":
  20001. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20002. break;
  20003. case "grounds":
  20004. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20005. break;
  20006. case "planes":
  20007. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20008. break;
  20009. case "torusKnots":
  20010. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20011. break;
  20012. case "vertexData":
  20013. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20014. break;
  20015. }
  20016. found = true;
  20017. }
  20018. });
  20019. }
  20020. });
  20021. if (!found) {
  20022. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20023. }
  20024. }
  20025. }
  20026. // Material ?
  20027. if (parsedMesh.materialId) {
  20028. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20029. if (!materialFound && parsedData.multiMaterials) {
  20030. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20031. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20032. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20033. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20034. var subMatId = parsedMultiMaterial.materials[matIndex];
  20035. loadedMaterialsIds.push(subMatId);
  20036. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20037. }
  20038. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20039. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20040. materialFound = true;
  20041. break;
  20042. }
  20043. }
  20044. }
  20045. if (!materialFound) {
  20046. loadedMaterialsIds.push(parsedMesh.materialId);
  20047. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20048. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20049. }
  20050. }
  20051. }
  20052. // Skeleton ?
  20053. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20054. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20055. if (!skeletonAlreadyLoaded) {
  20056. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20057. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20058. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20059. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20060. loadedSkeletonsIds.push(parsedSkeleton.id);
  20061. }
  20062. }
  20063. }
  20064. }
  20065. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20066. meshes.push(mesh);
  20067. }
  20068. }
  20069. // Connecting parents
  20070. var currentMesh;
  20071. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20072. currentMesh = scene.meshes[index];
  20073. if (currentMesh._waitingParentId) {
  20074. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20075. currentMesh._waitingParentId = undefined;
  20076. }
  20077. }
  20078. // freeze world matrix application
  20079. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20080. currentMesh = scene.meshes[index];
  20081. if (currentMesh._waitingFreezeWorldMatrix) {
  20082. currentMesh.freezeWorldMatrix();
  20083. currentMesh._waitingFreezeWorldMatrix = undefined;
  20084. }
  20085. }
  20086. // Particles
  20087. if (parsedData.particleSystems) {
  20088. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20089. var parsedParticleSystem = parsedData.particleSystems[index];
  20090. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20091. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20092. }
  20093. }
  20094. }
  20095. return true;
  20096. },
  20097. load: function (scene, data, rootUrl) {
  20098. var parsedData = JSON.parse(data);
  20099. // Scene
  20100. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20101. scene.autoClear = parsedData.autoClear;
  20102. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20103. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20104. if (parsedData.gravity) {
  20105. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20106. }
  20107. // Fog
  20108. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20109. scene.fogMode = parsedData.fogMode;
  20110. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20111. scene.fogStart = parsedData.fogStart;
  20112. scene.fogEnd = parsedData.fogEnd;
  20113. scene.fogDensity = parsedData.fogDensity;
  20114. }
  20115. //Physics
  20116. if (parsedData.physicsEnabled) {
  20117. var physicsPlugin;
  20118. if (parsedData.physicsEngine === "cannon") {
  20119. physicsPlugin = new BABYLON.CannonJSPlugin();
  20120. }
  20121. else if (parsedData.physicsEngine === "oimo") {
  20122. physicsPlugin = new BABYLON.OimoJSPlugin();
  20123. }
  20124. //else - default engine, which is currently oimo
  20125. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20126. scene.enablePhysics(physicsGravity, physicsPlugin);
  20127. }
  20128. //collisions, if defined. otherwise, default is true
  20129. if (parsedData.collisionsEnabled != undefined) {
  20130. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20131. }
  20132. scene.workerCollisions = !!parsedData.workerCollisions;
  20133. var index;
  20134. var cache;
  20135. // Lights
  20136. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20137. var parsedLight = parsedData.lights[index];
  20138. BABYLON.Light.Parse(parsedLight, scene);
  20139. }
  20140. // Materials
  20141. if (parsedData.materials) {
  20142. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20143. var parsedMaterial = parsedData.materials[index];
  20144. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20145. }
  20146. }
  20147. if (parsedData.multiMaterials) {
  20148. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20149. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20150. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20151. }
  20152. }
  20153. // Skeletons
  20154. if (parsedData.skeletons) {
  20155. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20156. var parsedSkeleton = parsedData.skeletons[index];
  20157. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20158. }
  20159. }
  20160. // Geometries
  20161. var geometries = parsedData.geometries;
  20162. if (geometries) {
  20163. // Boxes
  20164. var boxes = geometries.boxes;
  20165. if (boxes) {
  20166. for (index = 0, cache = boxes.length; index < cache; index++) {
  20167. var parsedBox = boxes[index];
  20168. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20169. }
  20170. }
  20171. // Spheres
  20172. var spheres = geometries.spheres;
  20173. if (spheres) {
  20174. for (index = 0, cache = spheres.length; index < cache; index++) {
  20175. var parsedSphere = spheres[index];
  20176. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20177. }
  20178. }
  20179. // Cylinders
  20180. var cylinders = geometries.cylinders;
  20181. if (cylinders) {
  20182. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20183. var parsedCylinder = cylinders[index];
  20184. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20185. }
  20186. }
  20187. // Toruses
  20188. var toruses = geometries.toruses;
  20189. if (toruses) {
  20190. for (index = 0, cache = toruses.length; index < cache; index++) {
  20191. var parsedTorus = toruses[index];
  20192. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20193. }
  20194. }
  20195. // Grounds
  20196. var grounds = geometries.grounds;
  20197. if (grounds) {
  20198. for (index = 0, cache = grounds.length; index < cache; index++) {
  20199. var parsedGround = grounds[index];
  20200. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20201. }
  20202. }
  20203. // Planes
  20204. var planes = geometries.planes;
  20205. if (planes) {
  20206. for (index = 0, cache = planes.length; index < cache; index++) {
  20207. var parsedPlane = planes[index];
  20208. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20209. }
  20210. }
  20211. // TorusKnots
  20212. var torusKnots = geometries.torusKnots;
  20213. if (torusKnots) {
  20214. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20215. var parsedTorusKnot = torusKnots[index];
  20216. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20217. }
  20218. }
  20219. // VertexData
  20220. var vertexData = geometries.vertexData;
  20221. if (vertexData) {
  20222. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20223. var parsedVertexData = vertexData[index];
  20224. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20225. }
  20226. }
  20227. }
  20228. // Meshes
  20229. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20230. var parsedMesh = parsedData.meshes[index];
  20231. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20232. }
  20233. // Cameras
  20234. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20235. var parsedCamera = parsedData.cameras[index];
  20236. BABYLON.Camera.Parse(parsedCamera, scene);
  20237. }
  20238. if (parsedData.activeCameraID) {
  20239. scene.setActiveCameraByID(parsedData.activeCameraID);
  20240. }
  20241. // Browsing all the graph to connect the dots
  20242. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20243. var camera = scene.cameras[index];
  20244. if (camera._waitingParentId) {
  20245. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20246. camera._waitingParentId = undefined;
  20247. }
  20248. }
  20249. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20250. var light = scene.lights[index];
  20251. if (light._waitingParentId) {
  20252. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20253. light._waitingParentId = undefined;
  20254. }
  20255. }
  20256. // Sounds
  20257. if (BABYLON.AudioEngine && parsedData.sounds) {
  20258. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20259. var parsedSound = parsedData.sounds[index];
  20260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20261. BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20262. }
  20263. else {
  20264. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20265. }
  20266. }
  20267. }
  20268. // Connect parents & children and parse actions
  20269. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20270. var mesh = scene.meshes[index];
  20271. if (mesh._waitingParentId) {
  20272. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20273. mesh._waitingParentId = undefined;
  20274. }
  20275. if (mesh._waitingActions) {
  20276. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20277. mesh._waitingActions = undefined;
  20278. }
  20279. }
  20280. // freeze world matrix application
  20281. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20282. var currentMesh = scene.meshes[index];
  20283. if (currentMesh._waitingFreezeWorldMatrix) {
  20284. currentMesh.freezeWorldMatrix();
  20285. currentMesh._waitingFreezeWorldMatrix = undefined;
  20286. }
  20287. }
  20288. // Particles Systems
  20289. if (parsedData.particleSystems) {
  20290. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20291. var parsedParticleSystem = parsedData.particleSystems[index];
  20292. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20293. }
  20294. }
  20295. // Lens flares
  20296. if (parsedData.lensFlareSystems) {
  20297. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20298. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20299. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20300. }
  20301. }
  20302. // Shadows
  20303. if (parsedData.shadowGenerators) {
  20304. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20305. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20306. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20307. }
  20308. }
  20309. // Actions (scene)
  20310. if (parsedData.actions) {
  20311. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20312. }
  20313. // Finish
  20314. return true;
  20315. }
  20316. });
  20317. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20318. })(BABYLON || (BABYLON = {}));
  20319. var BABYLON;
  20320. (function (BABYLON) {
  20321. var SpriteManager = (function () {
  20322. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20324. this.name = name;
  20325. this.cellSize = cellSize;
  20326. this.sprites = new Array();
  20327. this.renderingGroupId = 0;
  20328. this.layerMask = 0x0FFFFFFF;
  20329. this.fogEnabled = true;
  20330. this.isPickable = false;
  20331. this._vertexDeclaration = [4, 4, 4, 4];
  20332. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20333. this._capacity = capacity;
  20334. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20335. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20336. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20337. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20338. this._scene = scene;
  20339. this._scene.spriteManagers.push(this);
  20340. // VBO
  20341. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20342. var indices = [];
  20343. var index = 0;
  20344. for (var count = 0; count < capacity; count++) {
  20345. indices.push(index);
  20346. indices.push(index + 1);
  20347. indices.push(index + 2);
  20348. indices.push(index);
  20349. indices.push(index + 2);
  20350. indices.push(index + 3);
  20351. index += 4;
  20352. }
  20353. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20354. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20355. // Effects
  20356. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20357. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20358. }
  20359. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20360. var arrayOffset = index * 16;
  20361. if (offsetX === 0)
  20362. offsetX = this._epsilon;
  20363. else if (offsetX === 1)
  20364. offsetX = 1 - this._epsilon;
  20365. if (offsetY === 0)
  20366. offsetY = this._epsilon;
  20367. else if (offsetY === 1)
  20368. offsetY = 1 - this._epsilon;
  20369. this._vertices[arrayOffset] = sprite.position.x;
  20370. this._vertices[arrayOffset + 1] = sprite.position.y;
  20371. this._vertices[arrayOffset + 2] = sprite.position.z;
  20372. this._vertices[arrayOffset + 3] = sprite.angle;
  20373. this._vertices[arrayOffset + 4] = sprite.width;
  20374. this._vertices[arrayOffset + 5] = sprite.height;
  20375. this._vertices[arrayOffset + 6] = offsetX;
  20376. this._vertices[arrayOffset + 7] = offsetY;
  20377. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20378. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20379. var offset = (sprite.cellIndex / rowSize) >> 0;
  20380. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20381. this._vertices[arrayOffset + 11] = offset;
  20382. // Color
  20383. this._vertices[arrayOffset + 12] = sprite.color.r;
  20384. this._vertices[arrayOffset + 13] = sprite.color.g;
  20385. this._vertices[arrayOffset + 14] = sprite.color.b;
  20386. this._vertices[arrayOffset + 15] = sprite.color.a;
  20387. };
  20388. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20389. var count = Math.min(this._capacity, this.sprites.length);
  20390. var min = BABYLON.Vector3.Zero();
  20391. var max = BABYLON.Vector3.Zero();
  20392. var distance = Number.MAX_VALUE;
  20393. var currentSprite;
  20394. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20395. var cameraView = camera.getViewMatrix();
  20396. for (var index = 0; index < count; index++) {
  20397. var sprite = this.sprites[index];
  20398. if (!sprite) {
  20399. continue;
  20400. }
  20401. if (predicate) {
  20402. if (!predicate(sprite)) {
  20403. continue;
  20404. }
  20405. }
  20406. else if (!sprite.isPickable) {
  20407. continue;
  20408. }
  20409. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20410. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20411. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20412. if (ray.intersectsBoxMinMax(min, max)) {
  20413. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20414. if (distance > currentDistance) {
  20415. distance = currentDistance;
  20416. currentSprite = sprite;
  20417. if (fastCheck) {
  20418. break;
  20419. }
  20420. }
  20421. }
  20422. }
  20423. if (currentSprite) {
  20424. var result = new BABYLON.PickingInfo();
  20425. result.hit = true;
  20426. result.pickedSprite = currentSprite;
  20427. result.distance = distance;
  20428. return result;
  20429. }
  20430. return null;
  20431. };
  20432. SpriteManager.prototype.render = function () {
  20433. // Check
  20434. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20435. return;
  20436. var engine = this._scene.getEngine();
  20437. var baseSize = this._spriteTexture.getBaseSize();
  20438. // Sprites
  20439. var deltaTime = engine.getDeltaTime();
  20440. var max = Math.min(this._capacity, this.sprites.length);
  20441. var rowSize = baseSize.width / this.cellSize;
  20442. var offset = 0;
  20443. for (var index = 0; index < max; index++) {
  20444. var sprite = this.sprites[index];
  20445. if (!sprite) {
  20446. continue;
  20447. }
  20448. sprite._animate(deltaTime);
  20449. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20450. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20451. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20452. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20453. }
  20454. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20455. // Render
  20456. var effect = this._effectBase;
  20457. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20458. effect = this._effectFog;
  20459. }
  20460. engine.enableEffect(effect);
  20461. var viewMatrix = this._scene.getViewMatrix();
  20462. effect.setTexture("diffuseSampler", this._spriteTexture);
  20463. effect.setMatrix("view", viewMatrix);
  20464. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20465. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20466. // Fog
  20467. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20468. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20469. effect.setColor3("vFogColor", this._scene.fogColor);
  20470. }
  20471. // VBOs
  20472. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20473. // Draw order
  20474. engine.setDepthFunctionToLessOrEqual();
  20475. effect.setBool("alphaTest", true);
  20476. engine.setColorWrite(false);
  20477. engine.draw(true, 0, max * 6);
  20478. engine.setColorWrite(true);
  20479. effect.setBool("alphaTest", false);
  20480. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20481. engine.draw(true, 0, max * 6);
  20482. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20483. };
  20484. SpriteManager.prototype.dispose = function () {
  20485. if (this._vertexBuffer) {
  20486. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20487. this._vertexBuffer = null;
  20488. }
  20489. if (this._indexBuffer) {
  20490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20491. this._indexBuffer = null;
  20492. }
  20493. if (this._spriteTexture) {
  20494. this._spriteTexture.dispose();
  20495. this._spriteTexture = null;
  20496. }
  20497. // Remove from scene
  20498. var index = this._scene.spriteManagers.indexOf(this);
  20499. this._scene.spriteManagers.splice(index, 1);
  20500. // Callback
  20501. if (this.onDispose) {
  20502. this.onDispose();
  20503. }
  20504. };
  20505. return SpriteManager;
  20506. })();
  20507. BABYLON.SpriteManager = SpriteManager;
  20508. })(BABYLON || (BABYLON = {}));
  20509. var BABYLON;
  20510. (function (BABYLON) {
  20511. var Sprite = (function () {
  20512. function Sprite(name, manager) {
  20513. this.name = name;
  20514. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20515. this.width = 1.0;
  20516. this.height = 1.0;
  20517. this.angle = 0;
  20518. this.cellIndex = 0;
  20519. this.invertU = 0;
  20520. this.invertV = 0;
  20521. this.animations = new Array();
  20522. this.isPickable = false;
  20523. this._animationStarted = false;
  20524. this._loopAnimation = false;
  20525. this._fromIndex = 0;
  20526. this._toIndex = 0;
  20527. this._delay = 0;
  20528. this._direction = 1;
  20529. this._frameCount = 0;
  20530. this._time = 0;
  20531. this._manager = manager;
  20532. this._manager.sprites.push(this);
  20533. this.position = BABYLON.Vector3.Zero();
  20534. }
  20535. Object.defineProperty(Sprite.prototype, "size", {
  20536. get: function () {
  20537. return this.width;
  20538. },
  20539. set: function (value) {
  20540. this.width = value;
  20541. this.height = value;
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20547. this._fromIndex = from;
  20548. this._toIndex = to;
  20549. this._loopAnimation = loop;
  20550. this._delay = delay;
  20551. this._animationStarted = true;
  20552. this._direction = from < to ? 1 : -1;
  20553. this.cellIndex = from;
  20554. this._time = 0;
  20555. };
  20556. Sprite.prototype.stopAnimation = function () {
  20557. this._animationStarted = false;
  20558. };
  20559. Sprite.prototype._animate = function (deltaTime) {
  20560. if (!this._animationStarted)
  20561. return;
  20562. this._time += deltaTime;
  20563. if (this._time > this._delay) {
  20564. this._time = this._time % this._delay;
  20565. this.cellIndex += this._direction;
  20566. if (this.cellIndex == this._toIndex) {
  20567. if (this._loopAnimation) {
  20568. this.cellIndex = this._fromIndex;
  20569. }
  20570. else {
  20571. this._animationStarted = false;
  20572. if (this.disposeWhenFinishedAnimating) {
  20573. this.dispose();
  20574. }
  20575. }
  20576. }
  20577. }
  20578. };
  20579. Sprite.prototype.dispose = function () {
  20580. for (var i = 0; i < this._manager.sprites.length; i++) {
  20581. if (this._manager.sprites[i] == this) {
  20582. this._manager.sprites.splice(i, 1);
  20583. }
  20584. }
  20585. };
  20586. return Sprite;
  20587. })();
  20588. BABYLON.Sprite = Sprite;
  20589. })(BABYLON || (BABYLON = {}));
  20590. var BABYLON;
  20591. (function (BABYLON) {
  20592. var Layer = (function () {
  20593. function Layer(name, imgUrl, scene, isBackground, color) {
  20594. this.name = name;
  20595. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20596. this._vertexDeclaration = [2];
  20597. this._vertexStrideSize = 2 * 4;
  20598. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20599. this.isBackground = isBackground === undefined ? true : isBackground;
  20600. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20601. this._scene = scene;
  20602. this._scene.layers.push(this);
  20603. // VBO
  20604. var vertices = [];
  20605. vertices.push(1, 1);
  20606. vertices.push(-1, 1);
  20607. vertices.push(-1, -1);
  20608. vertices.push(1, -1);
  20609. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20610. // Indices
  20611. var indices = [];
  20612. indices.push(0);
  20613. indices.push(1);
  20614. indices.push(2);
  20615. indices.push(0);
  20616. indices.push(2);
  20617. indices.push(3);
  20618. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20619. // Effects
  20620. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20621. }
  20622. Layer.prototype.render = function () {
  20623. // Check
  20624. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20625. return;
  20626. var engine = this._scene.getEngine();
  20627. // Render
  20628. engine.enableEffect(this._effect);
  20629. engine.setState(false);
  20630. // Texture
  20631. this._effect.setTexture("textureSampler", this.texture);
  20632. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20633. // Color
  20634. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20635. // VBOs
  20636. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20637. // Draw order
  20638. engine.setAlphaMode(this.alphaBlendingMode);
  20639. engine.draw(true, 0, 6);
  20640. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20641. };
  20642. Layer.prototype.dispose = function () {
  20643. if (this._vertexBuffer) {
  20644. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20645. this._vertexBuffer = null;
  20646. }
  20647. if (this._indexBuffer) {
  20648. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20649. this._indexBuffer = null;
  20650. }
  20651. if (this.texture) {
  20652. this.texture.dispose();
  20653. this.texture = null;
  20654. }
  20655. // Remove from scene
  20656. var index = this._scene.layers.indexOf(this);
  20657. this._scene.layers.splice(index, 1);
  20658. // Callback
  20659. if (this.onDispose) {
  20660. this.onDispose();
  20661. }
  20662. };
  20663. return Layer;
  20664. })();
  20665. BABYLON.Layer = Layer;
  20666. })(BABYLON || (BABYLON = {}));
  20667. var BABYLON;
  20668. (function (BABYLON) {
  20669. var Particle = (function () {
  20670. function Particle() {
  20671. this.position = BABYLON.Vector3.Zero();
  20672. this.direction = BABYLON.Vector3.Zero();
  20673. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20674. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20675. this.lifeTime = 1.0;
  20676. this.age = 0;
  20677. this.size = 0;
  20678. this.angle = 0;
  20679. this.angularSpeed = 0;
  20680. }
  20681. Particle.prototype.copyTo = function (other) {
  20682. other.position.copyFrom(this.position);
  20683. other.direction.copyFrom(this.direction);
  20684. other.color.copyFrom(this.color);
  20685. other.colorStep.copyFrom(this.colorStep);
  20686. other.lifeTime = this.lifeTime;
  20687. other.age = this.age;
  20688. other.size = this.size;
  20689. other.angle = this.angle;
  20690. other.angularSpeed = this.angularSpeed;
  20691. };
  20692. return Particle;
  20693. })();
  20694. BABYLON.Particle = Particle;
  20695. })(BABYLON || (BABYLON = {}));
  20696. var BABYLON;
  20697. (function (BABYLON) {
  20698. var randomNumber = function (min, max) {
  20699. if (min === max) {
  20700. return (min);
  20701. }
  20702. var random = Math.random();
  20703. return ((random * (max - min)) + min);
  20704. };
  20705. var ParticleSystem = (function () {
  20706. function ParticleSystem(name, capacity, scene, customEffect) {
  20707. var _this = this;
  20708. this.name = name;
  20709. this.renderingGroupId = 0;
  20710. this.emitter = null;
  20711. this.emitRate = 10;
  20712. this.manualEmitCount = -1;
  20713. this.updateSpeed = 0.01;
  20714. this.targetStopDuration = 0;
  20715. this.disposeOnStop = false;
  20716. this.minEmitPower = 1;
  20717. this.maxEmitPower = 1;
  20718. this.minLifeTime = 1;
  20719. this.maxLifeTime = 1;
  20720. this.minSize = 1;
  20721. this.maxSize = 1;
  20722. this.minAngularSpeed = 0;
  20723. this.maxAngularSpeed = 0;
  20724. this.layerMask = 0x0FFFFFFF;
  20725. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20726. this.forceDepthWrite = false;
  20727. this.gravity = BABYLON.Vector3.Zero();
  20728. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20729. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20730. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20731. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20732. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20733. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20734. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20735. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20736. this.particles = new Array();
  20737. this._vertexDeclaration = [3, 4, 4];
  20738. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20739. this._stockParticles = new Array();
  20740. this._newPartsExcess = 0;
  20741. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20742. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20743. this._scaledDirection = BABYLON.Vector3.Zero();
  20744. this._scaledGravity = BABYLON.Vector3.Zero();
  20745. this._currentRenderId = -1;
  20746. this._started = false;
  20747. this._stopped = false;
  20748. this._actualFrame = 0;
  20749. this.id = name;
  20750. this._capacity = capacity;
  20751. this._scene = scene;
  20752. this._customEffect = customEffect;
  20753. scene.particleSystems.push(this);
  20754. // VBO
  20755. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20756. var indices = [];
  20757. var index = 0;
  20758. for (var count = 0; count < capacity; count++) {
  20759. indices.push(index);
  20760. indices.push(index + 1);
  20761. indices.push(index + 2);
  20762. indices.push(index);
  20763. indices.push(index + 2);
  20764. indices.push(index + 3);
  20765. index += 4;
  20766. }
  20767. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20768. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20769. // Default behaviors
  20770. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  20771. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20772. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20773. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20774. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20775. };
  20776. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  20777. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20778. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20779. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20780. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20781. };
  20782. this.updateFunction = function (particles) {
  20783. for (var index = 0; index < particles.length; index++) {
  20784. var particle = particles[index];
  20785. particle.age += _this._scaledUpdateSpeed;
  20786. if (particle.age >= particle.lifeTime) {
  20787. _this.recycleParticle(particle);
  20788. index--;
  20789. continue;
  20790. }
  20791. else {
  20792. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20793. particle.color.addInPlace(_this._scaledColorStep);
  20794. if (particle.color.a < 0)
  20795. particle.color.a = 0;
  20796. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20797. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20798. particle.position.addInPlace(_this._scaledDirection);
  20799. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20800. particle.direction.addInPlace(_this._scaledGravity);
  20801. }
  20802. }
  20803. };
  20804. }
  20805. ParticleSystem.prototype.recycleParticle = function (particle) {
  20806. var lastParticle = this.particles.pop();
  20807. if (lastParticle !== particle) {
  20808. lastParticle.copyTo(particle);
  20809. this._stockParticles.push(lastParticle);
  20810. }
  20811. };
  20812. ParticleSystem.prototype.getCapacity = function () {
  20813. return this._capacity;
  20814. };
  20815. ParticleSystem.prototype.isAlive = function () {
  20816. return this._alive;
  20817. };
  20818. ParticleSystem.prototype.isStarted = function () {
  20819. return this._started;
  20820. };
  20821. ParticleSystem.prototype.start = function () {
  20822. this._started = true;
  20823. this._stopped = false;
  20824. this._actualFrame = 0;
  20825. };
  20826. ParticleSystem.prototype.stop = function () {
  20827. this._stopped = true;
  20828. };
  20829. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20830. var offset = index * 11;
  20831. this._vertices[offset] = particle.position.x;
  20832. this._vertices[offset + 1] = particle.position.y;
  20833. this._vertices[offset + 2] = particle.position.z;
  20834. this._vertices[offset + 3] = particle.color.r;
  20835. this._vertices[offset + 4] = particle.color.g;
  20836. this._vertices[offset + 5] = particle.color.b;
  20837. this._vertices[offset + 6] = particle.color.a;
  20838. this._vertices[offset + 7] = particle.angle;
  20839. this._vertices[offset + 8] = particle.size;
  20840. this._vertices[offset + 9] = offsetX;
  20841. this._vertices[offset + 10] = offsetY;
  20842. };
  20843. ParticleSystem.prototype._update = function (newParticles) {
  20844. // Update current
  20845. this._alive = this.particles.length > 0;
  20846. this.updateFunction(this.particles);
  20847. // Add new ones
  20848. var worldMatrix;
  20849. if (this.emitter.position) {
  20850. worldMatrix = this.emitter.getWorldMatrix();
  20851. }
  20852. else {
  20853. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20854. }
  20855. var particle;
  20856. for (var index = 0; index < newParticles; index++) {
  20857. if (this.particles.length === this._capacity) {
  20858. break;
  20859. }
  20860. if (this._stockParticles.length !== 0) {
  20861. particle = this._stockParticles.pop();
  20862. particle.age = 0;
  20863. }
  20864. else {
  20865. particle = new BABYLON.Particle();
  20866. }
  20867. this.particles.push(particle);
  20868. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20869. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  20870. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20871. particle.size = randomNumber(this.minSize, this.maxSize);
  20872. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20873. this.startPositionFunction(worldMatrix, particle.position, particle);
  20874. var step = randomNumber(0, 1.0);
  20875. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20876. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20877. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20878. }
  20879. };
  20880. ParticleSystem.prototype._getEffect = function () {
  20881. if (this._customEffect) {
  20882. return this._customEffect;
  20883. }
  20884. ;
  20885. var defines = [];
  20886. if (this._scene.clipPlane) {
  20887. defines.push("#define CLIPPLANE");
  20888. }
  20889. // Effect
  20890. var join = defines.join("\n");
  20891. if (this._cachedDefines !== join) {
  20892. this._cachedDefines = join;
  20893. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20894. }
  20895. return this._effect;
  20896. };
  20897. ParticleSystem.prototype.animate = function () {
  20898. if (!this._started)
  20899. return;
  20900. var effect = this._getEffect();
  20901. // Check
  20902. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20903. return;
  20904. if (this._currentRenderId === this._scene.getRenderId()) {
  20905. return;
  20906. }
  20907. this._currentRenderId = this._scene.getRenderId();
  20908. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20909. // determine the number of particles we need to create
  20910. var emitCout;
  20911. if (this.manualEmitCount > -1) {
  20912. emitCout = this.manualEmitCount;
  20913. this.manualEmitCount = 0;
  20914. }
  20915. else {
  20916. emitCout = this.emitRate;
  20917. }
  20918. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20919. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20920. if (this._newPartsExcess > 1.0) {
  20921. newParticles += this._newPartsExcess >> 0;
  20922. this._newPartsExcess -= this._newPartsExcess >> 0;
  20923. }
  20924. this._alive = false;
  20925. if (!this._stopped) {
  20926. this._actualFrame += this._scaledUpdateSpeed;
  20927. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20928. this.stop();
  20929. }
  20930. else {
  20931. newParticles = 0;
  20932. }
  20933. this._update(newParticles);
  20934. // Stopped?
  20935. if (this._stopped) {
  20936. if (!this._alive) {
  20937. this._started = false;
  20938. if (this.disposeOnStop) {
  20939. this._scene._toBeDisposed.push(this);
  20940. }
  20941. }
  20942. }
  20943. // Update VBO
  20944. var offset = 0;
  20945. for (var index = 0; index < this.particles.length; index++) {
  20946. var particle = this.particles[index];
  20947. this._appendParticleVertex(offset++, particle, 0, 0);
  20948. this._appendParticleVertex(offset++, particle, 1, 0);
  20949. this._appendParticleVertex(offset++, particle, 1, 1);
  20950. this._appendParticleVertex(offset++, particle, 0, 1);
  20951. }
  20952. var engine = this._scene.getEngine();
  20953. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20954. };
  20955. ParticleSystem.prototype.render = function () {
  20956. var effect = this._getEffect();
  20957. // Check
  20958. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20959. return 0;
  20960. var engine = this._scene.getEngine();
  20961. // Render
  20962. engine.enableEffect(effect);
  20963. engine.setState(false);
  20964. var viewMatrix = this._scene.getViewMatrix();
  20965. effect.setTexture("diffuseSampler", this.particleTexture);
  20966. effect.setMatrix("view", viewMatrix);
  20967. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20968. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20969. if (this._scene.clipPlane) {
  20970. var clipPlane = this._scene.clipPlane;
  20971. var invView = viewMatrix.clone();
  20972. invView.invert();
  20973. effect.setMatrix("invView", invView);
  20974. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20975. }
  20976. // VBOs
  20977. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20978. // Draw order
  20979. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20980. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  20981. }
  20982. else {
  20983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20984. }
  20985. if (this.forceDepthWrite) {
  20986. engine.setDepthWrite(true);
  20987. }
  20988. engine.draw(true, 0, this.particles.length * 6);
  20989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20990. return this.particles.length;
  20991. };
  20992. ParticleSystem.prototype.dispose = function () {
  20993. if (this._vertexBuffer) {
  20994. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20995. this._vertexBuffer = null;
  20996. }
  20997. if (this._indexBuffer) {
  20998. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20999. this._indexBuffer = null;
  21000. }
  21001. if (this.particleTexture) {
  21002. this.particleTexture.dispose();
  21003. this.particleTexture = null;
  21004. }
  21005. // Remove from scene
  21006. var index = this._scene.particleSystems.indexOf(this);
  21007. this._scene.particleSystems.splice(index, 1);
  21008. // Callback
  21009. if (this.onDispose) {
  21010. this.onDispose();
  21011. }
  21012. };
  21013. // Clone
  21014. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21015. var result = new ParticleSystem(name, this._capacity, this._scene);
  21016. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21017. if (newEmitter === undefined) {
  21018. newEmitter = this.emitter;
  21019. }
  21020. result.emitter = newEmitter;
  21021. if (this.particleTexture) {
  21022. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21023. }
  21024. result.start();
  21025. return result;
  21026. };
  21027. ParticleSystem.prototype.serialize = function () {
  21028. var serializationObject = {};
  21029. serializationObject.emitterId = this.emitter.id;
  21030. serializationObject.capacity = this.getCapacity();
  21031. if (this.particleTexture) {
  21032. serializationObject.textureName = this.particleTexture.name;
  21033. }
  21034. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21035. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21036. serializationObject.minSize = this.minSize;
  21037. serializationObject.maxSize = this.maxSize;
  21038. serializationObject.minLifeTime = this.minLifeTime;
  21039. serializationObject.maxLifeTime = this.maxLifeTime;
  21040. serializationObject.emitRate = this.emitRate;
  21041. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21042. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21043. serializationObject.gravity = this.gravity.asArray();
  21044. serializationObject.direction1 = this.direction1.asArray();
  21045. serializationObject.direction2 = this.direction2.asArray();
  21046. serializationObject.color1 = this.color1.asArray();
  21047. serializationObject.color2 = this.color2.asArray();
  21048. serializationObject.colorDead = this.colorDead.asArray();
  21049. serializationObject.updateSpeed = this.updateSpeed;
  21050. serializationObject.targetStopDuration = this.targetStopDuration;
  21051. serializationObject.textureMask = this.textureMask.asArray();
  21052. serializationObject.blendMode = this.blendMode;
  21053. return serializationObject;
  21054. };
  21055. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21056. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21057. var particleSystem = new ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  21058. if (parsedParticleSystem.textureName) {
  21059. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21060. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21061. }
  21062. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21063. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21064. particleSystem.minSize = parsedParticleSystem.minSize;
  21065. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21066. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21067. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21068. particleSystem.emitter = emitter;
  21069. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21070. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21071. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21072. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21073. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21074. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21075. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21076. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21077. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21078. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21079. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  21080. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21081. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21082. particleSystem.start();
  21083. return particleSystem;
  21084. };
  21085. // Statics
  21086. ParticleSystem.BLENDMODE_ONEONE = 0;
  21087. ParticleSystem.BLENDMODE_STANDARD = 1;
  21088. return ParticleSystem;
  21089. })();
  21090. BABYLON.ParticleSystem = ParticleSystem;
  21091. })(BABYLON || (BABYLON = {}));
  21092. var BABYLON;
  21093. (function (BABYLON) {
  21094. var AnimationRange = (function () {
  21095. function AnimationRange(name, from, to) {
  21096. this.name = name;
  21097. this.from = from;
  21098. this.to = to;
  21099. }
  21100. return AnimationRange;
  21101. })();
  21102. BABYLON.AnimationRange = AnimationRange;
  21103. /**
  21104. * Composed of a frame, and an action function
  21105. */
  21106. var AnimationEvent = (function () {
  21107. function AnimationEvent(frame, action, onlyOnce) {
  21108. this.frame = frame;
  21109. this.action = action;
  21110. this.onlyOnce = onlyOnce;
  21111. this.isDone = false;
  21112. }
  21113. return AnimationEvent;
  21114. })();
  21115. BABYLON.AnimationEvent = AnimationEvent;
  21116. var Animation = (function () {
  21117. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21118. this.name = name;
  21119. this.targetProperty = targetProperty;
  21120. this.framePerSecond = framePerSecond;
  21121. this.dataType = dataType;
  21122. this.loopMode = loopMode;
  21123. this._offsetsCache = {};
  21124. this._highLimitsCache = {};
  21125. this._stopped = false;
  21126. // The set of event that will be linked to this animation
  21127. this._events = new Array();
  21128. this.allowMatricesInterpolation = false;
  21129. this._ranges = new Array();
  21130. this.targetPropertyPath = targetProperty.split(".");
  21131. this.dataType = dataType;
  21132. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21133. }
  21134. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21135. var dataType = undefined;
  21136. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21137. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21138. }
  21139. else if (from instanceof BABYLON.Quaternion) {
  21140. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21141. }
  21142. else if (from instanceof BABYLON.Vector3) {
  21143. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21144. }
  21145. else if (from instanceof BABYLON.Vector2) {
  21146. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21147. }
  21148. else if (from instanceof BABYLON.Color3) {
  21149. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21150. }
  21151. if (dataType == undefined) {
  21152. return null;
  21153. }
  21154. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21155. var keys = [];
  21156. keys.push({ frame: 0, value: from });
  21157. keys.push({ frame: totalFrame, value: to });
  21158. animation.setKeys(keys);
  21159. if (easingFunction !== undefined) {
  21160. animation.setEasingFunction(easingFunction);
  21161. }
  21162. return animation;
  21163. };
  21164. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21165. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21166. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21167. };
  21168. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21169. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21170. node.animations.push(animation);
  21171. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21172. };
  21173. // Methods
  21174. /**
  21175. * Add an event to this animation.
  21176. */
  21177. Animation.prototype.addEvent = function (event) {
  21178. this._events.push(event);
  21179. };
  21180. /**
  21181. * Remove all events found at the given frame
  21182. * @param frame
  21183. */
  21184. Animation.prototype.removeEvents = function (frame) {
  21185. for (var index = 0; index < this._events.length; index++) {
  21186. if (this._events[index].frame === frame) {
  21187. this._events.splice(index, 1);
  21188. index--;
  21189. }
  21190. }
  21191. };
  21192. Animation.prototype.createRange = function (name, from, to) {
  21193. this._ranges.push(new AnimationRange(name, from, to));
  21194. };
  21195. Animation.prototype.deleteRange = function (name) {
  21196. for (var index = 0; index < this._ranges.length; index++) {
  21197. if (this._ranges[index].name === name) {
  21198. this._ranges.splice(index, 1);
  21199. return;
  21200. }
  21201. }
  21202. };
  21203. Animation.prototype.getRange = function (name) {
  21204. for (var index = 0; index < this._ranges.length; index++) {
  21205. if (this._ranges[index].name === name) {
  21206. return this._ranges[index];
  21207. }
  21208. }
  21209. return null;
  21210. };
  21211. Animation.prototype.reset = function () {
  21212. this._offsetsCache = {};
  21213. this._highLimitsCache = {};
  21214. this.currentFrame = 0;
  21215. };
  21216. Animation.prototype.isStopped = function () {
  21217. return this._stopped;
  21218. };
  21219. Animation.prototype.getKeys = function () {
  21220. return this._keys;
  21221. };
  21222. Animation.prototype.getEasingFunction = function () {
  21223. return this._easingFunction;
  21224. };
  21225. Animation.prototype.setEasingFunction = function (easingFunction) {
  21226. this._easingFunction = easingFunction;
  21227. };
  21228. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21229. return startValue + (endValue - startValue) * gradient;
  21230. };
  21231. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21232. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21233. };
  21234. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21235. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21236. };
  21237. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21238. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21239. };
  21240. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21241. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21242. };
  21243. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21244. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21245. };
  21246. Animation.prototype.clone = function () {
  21247. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21248. if (this._keys) {
  21249. clone.setKeys(this._keys);
  21250. }
  21251. return clone;
  21252. };
  21253. Animation.prototype.setKeys = function (values) {
  21254. this._keys = values.slice(0);
  21255. this._offsetsCache = {};
  21256. this._highLimitsCache = {};
  21257. };
  21258. Animation.prototype._getKeyValue = function (value) {
  21259. if (typeof value === "function") {
  21260. return value();
  21261. }
  21262. return value;
  21263. };
  21264. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21265. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21266. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21267. }
  21268. this.currentFrame = currentFrame;
  21269. // Try to get a hash to find the right key
  21270. 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));
  21271. if (this._keys[startKey].frame >= currentFrame) {
  21272. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21273. startKey--;
  21274. }
  21275. }
  21276. for (var key = startKey; key < this._keys.length; key++) {
  21277. if (this._keys[key + 1].frame >= currentFrame) {
  21278. var startValue = this._getKeyValue(this._keys[key].value);
  21279. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21280. // gradient : percent of currentFrame between the frame inf and the frame sup
  21281. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21282. // check for easingFunction and correction of gradient
  21283. if (this._easingFunction != null) {
  21284. gradient = this._easingFunction.ease(gradient);
  21285. }
  21286. switch (this.dataType) {
  21287. // Float
  21288. case Animation.ANIMATIONTYPE_FLOAT:
  21289. switch (loopMode) {
  21290. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21291. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21292. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21293. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21294. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21295. }
  21296. break;
  21297. // Quaternion
  21298. case Animation.ANIMATIONTYPE_QUATERNION:
  21299. var quaternion = null;
  21300. switch (loopMode) {
  21301. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21302. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21303. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21304. break;
  21305. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21306. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21307. break;
  21308. }
  21309. return quaternion;
  21310. // Vector3
  21311. case Animation.ANIMATIONTYPE_VECTOR3:
  21312. switch (loopMode) {
  21313. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21314. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21315. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21316. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21317. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21318. }
  21319. // Vector2
  21320. case Animation.ANIMATIONTYPE_VECTOR2:
  21321. switch (loopMode) {
  21322. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21323. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21324. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21325. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21326. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21327. }
  21328. // Color3
  21329. case Animation.ANIMATIONTYPE_COLOR3:
  21330. switch (loopMode) {
  21331. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21332. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21333. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21334. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21335. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21336. }
  21337. // Matrix
  21338. case Animation.ANIMATIONTYPE_MATRIX:
  21339. switch (loopMode) {
  21340. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21341. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21342. if (this.allowMatricesInterpolation) {
  21343. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21344. }
  21345. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21346. return startValue;
  21347. }
  21348. default:
  21349. break;
  21350. }
  21351. break;
  21352. }
  21353. }
  21354. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21355. };
  21356. Animation.prototype.setValue = function (currentValue) {
  21357. // Set value
  21358. if (this.targetPropertyPath.length > 1) {
  21359. var property = this._target[this.targetPropertyPath[0]];
  21360. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21361. property = property[this.targetPropertyPath[index]];
  21362. }
  21363. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21364. }
  21365. else {
  21366. this._target[this.targetPropertyPath[0]] = currentValue;
  21367. }
  21368. if (this._target.markAsDirty) {
  21369. this._target.markAsDirty(this.targetProperty);
  21370. }
  21371. };
  21372. Animation.prototype.goToFrame = function (frame) {
  21373. if (frame < this._keys[0].frame) {
  21374. frame = this._keys[0].frame;
  21375. }
  21376. else if (frame > this._keys[this._keys.length - 1].frame) {
  21377. frame = this._keys[this._keys.length - 1].frame;
  21378. }
  21379. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21380. this.setValue(currentValue);
  21381. };
  21382. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21383. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21384. this._stopped = true;
  21385. return false;
  21386. }
  21387. var returnValue = true;
  21388. // Adding a start key at frame 0 if missing
  21389. if (this._keys[0].frame !== 0) {
  21390. var newKey = { frame: 0, value: this._keys[0].value };
  21391. this._keys.splice(0, 0, newKey);
  21392. }
  21393. // Check limits
  21394. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21395. from = this._keys[0].frame;
  21396. }
  21397. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21398. to = this._keys[this._keys.length - 1].frame;
  21399. }
  21400. // Compute ratio
  21401. var range = to - from;
  21402. var offsetValue;
  21403. // ratio represents the frame delta between from and to
  21404. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21405. var highLimitValue = 0;
  21406. if (ratio > range && !loop) {
  21407. returnValue = false;
  21408. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21409. }
  21410. else {
  21411. // Get max value if required
  21412. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21413. var keyOffset = to.toString() + from.toString();
  21414. if (!this._offsetsCache[keyOffset]) {
  21415. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21416. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21417. switch (this.dataType) {
  21418. // Float
  21419. case Animation.ANIMATIONTYPE_FLOAT:
  21420. this._offsetsCache[keyOffset] = toValue - fromValue;
  21421. break;
  21422. // Quaternion
  21423. case Animation.ANIMATIONTYPE_QUATERNION:
  21424. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21425. break;
  21426. // Vector3
  21427. case Animation.ANIMATIONTYPE_VECTOR3:
  21428. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21429. // Vector2
  21430. case Animation.ANIMATIONTYPE_VECTOR2:
  21431. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21432. // Color3
  21433. case Animation.ANIMATIONTYPE_COLOR3:
  21434. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21435. default:
  21436. break;
  21437. }
  21438. this._highLimitsCache[keyOffset] = toValue;
  21439. }
  21440. highLimitValue = this._highLimitsCache[keyOffset];
  21441. offsetValue = this._offsetsCache[keyOffset];
  21442. }
  21443. }
  21444. if (offsetValue === undefined) {
  21445. switch (this.dataType) {
  21446. // Float
  21447. case Animation.ANIMATIONTYPE_FLOAT:
  21448. offsetValue = 0;
  21449. break;
  21450. // Quaternion
  21451. case Animation.ANIMATIONTYPE_QUATERNION:
  21452. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21453. break;
  21454. // Vector3
  21455. case Animation.ANIMATIONTYPE_VECTOR3:
  21456. offsetValue = BABYLON.Vector3.Zero();
  21457. break;
  21458. // Vector2
  21459. case Animation.ANIMATIONTYPE_VECTOR2:
  21460. offsetValue = BABYLON.Vector2.Zero();
  21461. break;
  21462. // Color3
  21463. case Animation.ANIMATIONTYPE_COLOR3:
  21464. offsetValue = BABYLON.Color3.Black();
  21465. }
  21466. }
  21467. // Compute value
  21468. var repeatCount = (ratio / range) >> 0;
  21469. var currentFrame = returnValue ? from + ratio % range : to;
  21470. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21471. // Check events
  21472. for (var index = 0; index < this._events.length; index++) {
  21473. if (currentFrame >= this._events[index].frame) {
  21474. var event = this._events[index];
  21475. if (!event.isDone) {
  21476. // If event should be done only once, remove it.
  21477. if (event.onlyOnce) {
  21478. this._events.splice(index, 1);
  21479. index--;
  21480. }
  21481. event.isDone = true;
  21482. event.action();
  21483. } // Don't do anything if the event has already be done.
  21484. }
  21485. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21486. // reset event, the animation is looping
  21487. this._events[index].isDone = false;
  21488. }
  21489. }
  21490. // Set value
  21491. this.setValue(currentValue);
  21492. if (!returnValue) {
  21493. this._stopped = true;
  21494. }
  21495. return returnValue;
  21496. };
  21497. Animation.prototype.serialize = function () {
  21498. var serializationObject = {};
  21499. serializationObject.name = this.name;
  21500. serializationObject.property = this.targetProperty;
  21501. serializationObject.framePerSecond = this.framePerSecond;
  21502. serializationObject.dataType = this.dataType;
  21503. serializationObject.loopBehavior = this.loopMode;
  21504. var dataType = this.dataType;
  21505. serializationObject.keys = [];
  21506. var keys = this.getKeys();
  21507. for (var index = 0; index < keys.length; index++) {
  21508. var animationKey = keys[index];
  21509. var key = {};
  21510. key.frame = animationKey.frame;
  21511. switch (dataType) {
  21512. case Animation.ANIMATIONTYPE_FLOAT:
  21513. key.values = [animationKey.value];
  21514. break;
  21515. case Animation.ANIMATIONTYPE_QUATERNION:
  21516. case Animation.ANIMATIONTYPE_MATRIX:
  21517. case Animation.ANIMATIONTYPE_VECTOR3:
  21518. key.values = animationKey.value.asArray();
  21519. break;
  21520. }
  21521. serializationObject.keys.push(key);
  21522. }
  21523. return serializationObject;
  21524. };
  21525. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21526. get: function () {
  21527. return Animation._ANIMATIONTYPE_FLOAT;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21533. get: function () {
  21534. return Animation._ANIMATIONTYPE_VECTOR3;
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21540. get: function () {
  21541. return Animation._ANIMATIONTYPE_VECTOR2;
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21547. get: function () {
  21548. return Animation._ANIMATIONTYPE_QUATERNION;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21554. get: function () {
  21555. return Animation._ANIMATIONTYPE_MATRIX;
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21561. get: function () {
  21562. return Animation._ANIMATIONTYPE_COLOR3;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21568. get: function () {
  21569. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21575. get: function () {
  21576. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21582. get: function () {
  21583. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21584. },
  21585. enumerable: true,
  21586. configurable: true
  21587. });
  21588. Animation.Parse = function (parsedAnimation) {
  21589. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21590. var dataType = parsedAnimation.dataType;
  21591. var keys = [];
  21592. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21593. var key = parsedAnimation.keys[index];
  21594. var data;
  21595. switch (dataType) {
  21596. case Animation.ANIMATIONTYPE_FLOAT:
  21597. data = key.values[0];
  21598. break;
  21599. case Animation.ANIMATIONTYPE_QUATERNION:
  21600. data = BABYLON.Quaternion.FromArray(key.values);
  21601. break;
  21602. case Animation.ANIMATIONTYPE_MATRIX:
  21603. data = BABYLON.Matrix.FromArray(key.values);
  21604. break;
  21605. case Animation.ANIMATIONTYPE_VECTOR3:
  21606. default:
  21607. data = BABYLON.Vector3.FromArray(key.values);
  21608. break;
  21609. }
  21610. keys.push({
  21611. frame: key.frame,
  21612. value: data
  21613. });
  21614. }
  21615. animation.setKeys(keys);
  21616. return animation;
  21617. };
  21618. Animation.AppendSerializedAnimations = function (source, destination) {
  21619. if (source.animations) {
  21620. destination.animations = [];
  21621. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  21622. var animation = source.animations[animationIndex];
  21623. destination.animations.push(animation.serialize());
  21624. }
  21625. }
  21626. };
  21627. // Statics
  21628. Animation._ANIMATIONTYPE_FLOAT = 0;
  21629. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21630. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21631. Animation._ANIMATIONTYPE_MATRIX = 3;
  21632. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21633. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21634. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21635. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21636. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21637. return Animation;
  21638. })();
  21639. BABYLON.Animation = Animation;
  21640. })(BABYLON || (BABYLON = {}));
  21641. var BABYLON;
  21642. (function (BABYLON) {
  21643. var Animatable = (function () {
  21644. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21645. if (fromFrame === void 0) { fromFrame = 0; }
  21646. if (toFrame === void 0) { toFrame = 100; }
  21647. if (loopAnimation === void 0) { loopAnimation = false; }
  21648. if (speedRatio === void 0) { speedRatio = 1.0; }
  21649. this.target = target;
  21650. this.fromFrame = fromFrame;
  21651. this.toFrame = toFrame;
  21652. this.loopAnimation = loopAnimation;
  21653. this.speedRatio = speedRatio;
  21654. this.onAnimationEnd = onAnimationEnd;
  21655. this._animations = new Array();
  21656. this._paused = false;
  21657. this.animationStarted = false;
  21658. if (animations) {
  21659. this.appendAnimations(target, animations);
  21660. }
  21661. this._scene = scene;
  21662. scene._activeAnimatables.push(this);
  21663. }
  21664. // Methods
  21665. Animatable.prototype.getAnimations = function () {
  21666. return this._animations;
  21667. };
  21668. Animatable.prototype.appendAnimations = function (target, animations) {
  21669. for (var index = 0; index < animations.length; index++) {
  21670. var animation = animations[index];
  21671. animation._target = target;
  21672. this._animations.push(animation);
  21673. }
  21674. };
  21675. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21676. var animations = this._animations;
  21677. for (var index = 0; index < animations.length; index++) {
  21678. if (animations[index].targetProperty === property) {
  21679. return animations[index];
  21680. }
  21681. }
  21682. return null;
  21683. };
  21684. Animatable.prototype.reset = function () {
  21685. var animations = this._animations;
  21686. for (var index = 0; index < animations.length; index++) {
  21687. animations[index].reset();
  21688. }
  21689. this._localDelayOffset = null;
  21690. this._pausedDelay = null;
  21691. };
  21692. Animatable.prototype.goToFrame = function (frame) {
  21693. var animations = this._animations;
  21694. for (var index = 0; index < animations.length; index++) {
  21695. animations[index].goToFrame(frame);
  21696. }
  21697. };
  21698. Animatable.prototype.pause = function () {
  21699. if (this._paused) {
  21700. return;
  21701. }
  21702. this._paused = true;
  21703. };
  21704. Animatable.prototype.restart = function () {
  21705. this._paused = false;
  21706. };
  21707. Animatable.prototype.stop = function () {
  21708. var index = this._scene._activeAnimatables.indexOf(this);
  21709. if (index > -1) {
  21710. this._scene._activeAnimatables.splice(index, 1);
  21711. }
  21712. if (this.onAnimationEnd) {
  21713. this.onAnimationEnd();
  21714. }
  21715. };
  21716. Animatable.prototype._animate = function (delay) {
  21717. if (this._paused) {
  21718. this.animationStarted = false;
  21719. if (!this._pausedDelay) {
  21720. this._pausedDelay = delay;
  21721. }
  21722. return true;
  21723. }
  21724. if (!this._localDelayOffset) {
  21725. this._localDelayOffset = delay;
  21726. }
  21727. else if (this._pausedDelay) {
  21728. this._localDelayOffset += delay - this._pausedDelay;
  21729. this._pausedDelay = null;
  21730. }
  21731. // Animating
  21732. var running = false;
  21733. var animations = this._animations;
  21734. var index;
  21735. for (index = 0; index < animations.length; index++) {
  21736. var animation = animations[index];
  21737. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21738. running = running || isRunning;
  21739. }
  21740. this.animationStarted = running;
  21741. if (!running) {
  21742. // Remove from active animatables
  21743. index = this._scene._activeAnimatables.indexOf(this);
  21744. this._scene._activeAnimatables.splice(index, 1);
  21745. }
  21746. if (!running && this.onAnimationEnd) {
  21747. this.onAnimationEnd();
  21748. }
  21749. return running;
  21750. };
  21751. return Animatable;
  21752. })();
  21753. BABYLON.Animatable = Animatable;
  21754. })(BABYLON || (BABYLON = {}));
  21755. var BABYLON;
  21756. (function (BABYLON) {
  21757. var EasingFunction = (function () {
  21758. function EasingFunction() {
  21759. // Properties
  21760. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21761. }
  21762. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21763. get: function () {
  21764. return EasingFunction._EASINGMODE_EASEIN;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21770. get: function () {
  21771. return EasingFunction._EASINGMODE_EASEOUT;
  21772. },
  21773. enumerable: true,
  21774. configurable: true
  21775. });
  21776. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21777. get: function () {
  21778. return EasingFunction._EASINGMODE_EASEINOUT;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21784. var n = Math.min(Math.max(easingMode, 0), 2);
  21785. this._easingMode = n;
  21786. };
  21787. EasingFunction.prototype.getEasingMode = function () {
  21788. return this._easingMode;
  21789. };
  21790. EasingFunction.prototype.easeInCore = function (gradient) {
  21791. throw new Error('You must implement this method');
  21792. };
  21793. EasingFunction.prototype.ease = function (gradient) {
  21794. switch (this._easingMode) {
  21795. case EasingFunction.EASINGMODE_EASEIN:
  21796. return this.easeInCore(gradient);
  21797. case EasingFunction.EASINGMODE_EASEOUT:
  21798. return (1 - this.easeInCore(1 - gradient));
  21799. }
  21800. if (gradient >= 0.5) {
  21801. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21802. }
  21803. return (this.easeInCore(gradient * 2) * 0.5);
  21804. };
  21805. //Statics
  21806. EasingFunction._EASINGMODE_EASEIN = 0;
  21807. EasingFunction._EASINGMODE_EASEOUT = 1;
  21808. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21809. return EasingFunction;
  21810. })();
  21811. BABYLON.EasingFunction = EasingFunction;
  21812. var CircleEase = (function (_super) {
  21813. __extends(CircleEase, _super);
  21814. function CircleEase() {
  21815. _super.apply(this, arguments);
  21816. }
  21817. CircleEase.prototype.easeInCore = function (gradient) {
  21818. gradient = Math.max(0, Math.min(1, gradient));
  21819. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21820. };
  21821. return CircleEase;
  21822. })(EasingFunction);
  21823. BABYLON.CircleEase = CircleEase;
  21824. var BackEase = (function (_super) {
  21825. __extends(BackEase, _super);
  21826. function BackEase(amplitude) {
  21827. if (amplitude === void 0) { amplitude = 1; }
  21828. _super.call(this);
  21829. this.amplitude = amplitude;
  21830. }
  21831. BackEase.prototype.easeInCore = function (gradient) {
  21832. var num = Math.max(0, this.amplitude);
  21833. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21834. };
  21835. return BackEase;
  21836. })(EasingFunction);
  21837. BABYLON.BackEase = BackEase;
  21838. var BounceEase = (function (_super) {
  21839. __extends(BounceEase, _super);
  21840. function BounceEase(bounces, bounciness) {
  21841. if (bounces === void 0) { bounces = 3; }
  21842. if (bounciness === void 0) { bounciness = 2; }
  21843. _super.call(this);
  21844. this.bounces = bounces;
  21845. this.bounciness = bounciness;
  21846. }
  21847. BounceEase.prototype.easeInCore = function (gradient) {
  21848. var y = Math.max(0.0, this.bounces);
  21849. var bounciness = this.bounciness;
  21850. if (bounciness <= 1.0) {
  21851. bounciness = 1.001;
  21852. }
  21853. var num9 = Math.pow(bounciness, y);
  21854. var num5 = 1.0 - bounciness;
  21855. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21856. var num15 = gradient * num4;
  21857. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21858. var num3 = Math.floor(num65);
  21859. var num13 = num3 + 1.0;
  21860. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21861. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21862. var num7 = (num8 + num12) * 0.5;
  21863. var num6 = gradient - num7;
  21864. var num2 = num7 - num8;
  21865. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21866. };
  21867. return BounceEase;
  21868. })(EasingFunction);
  21869. BABYLON.BounceEase = BounceEase;
  21870. var CubicEase = (function (_super) {
  21871. __extends(CubicEase, _super);
  21872. function CubicEase() {
  21873. _super.apply(this, arguments);
  21874. }
  21875. CubicEase.prototype.easeInCore = function (gradient) {
  21876. return (gradient * gradient * gradient);
  21877. };
  21878. return CubicEase;
  21879. })(EasingFunction);
  21880. BABYLON.CubicEase = CubicEase;
  21881. var ElasticEase = (function (_super) {
  21882. __extends(ElasticEase, _super);
  21883. function ElasticEase(oscillations, springiness) {
  21884. if (oscillations === void 0) { oscillations = 3; }
  21885. if (springiness === void 0) { springiness = 3; }
  21886. _super.call(this);
  21887. this.oscillations = oscillations;
  21888. this.springiness = springiness;
  21889. }
  21890. ElasticEase.prototype.easeInCore = function (gradient) {
  21891. var num2;
  21892. var num3 = Math.max(0.0, this.oscillations);
  21893. var num = Math.max(0.0, this.springiness);
  21894. if (num == 0) {
  21895. num2 = gradient;
  21896. }
  21897. else {
  21898. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21899. }
  21900. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21901. };
  21902. return ElasticEase;
  21903. })(EasingFunction);
  21904. BABYLON.ElasticEase = ElasticEase;
  21905. var ExponentialEase = (function (_super) {
  21906. __extends(ExponentialEase, _super);
  21907. function ExponentialEase(exponent) {
  21908. if (exponent === void 0) { exponent = 2; }
  21909. _super.call(this);
  21910. this.exponent = exponent;
  21911. }
  21912. ExponentialEase.prototype.easeInCore = function (gradient) {
  21913. if (this.exponent <= 0) {
  21914. return gradient;
  21915. }
  21916. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21917. };
  21918. return ExponentialEase;
  21919. })(EasingFunction);
  21920. BABYLON.ExponentialEase = ExponentialEase;
  21921. var PowerEase = (function (_super) {
  21922. __extends(PowerEase, _super);
  21923. function PowerEase(power) {
  21924. if (power === void 0) { power = 2; }
  21925. _super.call(this);
  21926. this.power = power;
  21927. }
  21928. PowerEase.prototype.easeInCore = function (gradient) {
  21929. var y = Math.max(0.0, this.power);
  21930. return Math.pow(gradient, y);
  21931. };
  21932. return PowerEase;
  21933. })(EasingFunction);
  21934. BABYLON.PowerEase = PowerEase;
  21935. var QuadraticEase = (function (_super) {
  21936. __extends(QuadraticEase, _super);
  21937. function QuadraticEase() {
  21938. _super.apply(this, arguments);
  21939. }
  21940. QuadraticEase.prototype.easeInCore = function (gradient) {
  21941. return (gradient * gradient);
  21942. };
  21943. return QuadraticEase;
  21944. })(EasingFunction);
  21945. BABYLON.QuadraticEase = QuadraticEase;
  21946. var QuarticEase = (function (_super) {
  21947. __extends(QuarticEase, _super);
  21948. function QuarticEase() {
  21949. _super.apply(this, arguments);
  21950. }
  21951. QuarticEase.prototype.easeInCore = function (gradient) {
  21952. return (gradient * gradient * gradient * gradient);
  21953. };
  21954. return QuarticEase;
  21955. })(EasingFunction);
  21956. BABYLON.QuarticEase = QuarticEase;
  21957. var QuinticEase = (function (_super) {
  21958. __extends(QuinticEase, _super);
  21959. function QuinticEase() {
  21960. _super.apply(this, arguments);
  21961. }
  21962. QuinticEase.prototype.easeInCore = function (gradient) {
  21963. return (gradient * gradient * gradient * gradient * gradient);
  21964. };
  21965. return QuinticEase;
  21966. })(EasingFunction);
  21967. BABYLON.QuinticEase = QuinticEase;
  21968. var SineEase = (function (_super) {
  21969. __extends(SineEase, _super);
  21970. function SineEase() {
  21971. _super.apply(this, arguments);
  21972. }
  21973. SineEase.prototype.easeInCore = function (gradient) {
  21974. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21975. };
  21976. return SineEase;
  21977. })(EasingFunction);
  21978. BABYLON.SineEase = SineEase;
  21979. var BezierCurveEase = (function (_super) {
  21980. __extends(BezierCurveEase, _super);
  21981. function BezierCurveEase(x1, y1, x2, y2) {
  21982. if (x1 === void 0) { x1 = 0; }
  21983. if (y1 === void 0) { y1 = 0; }
  21984. if (x2 === void 0) { x2 = 1; }
  21985. if (y2 === void 0) { y2 = 1; }
  21986. _super.call(this);
  21987. this.x1 = x1;
  21988. this.y1 = y1;
  21989. this.x2 = x2;
  21990. this.y2 = y2;
  21991. }
  21992. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21993. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21994. };
  21995. return BezierCurveEase;
  21996. })(EasingFunction);
  21997. BABYLON.BezierCurveEase = BezierCurveEase;
  21998. })(BABYLON || (BABYLON = {}));
  21999. var BABYLON;
  22000. (function (BABYLON) {
  22001. var Bone = (function (_super) {
  22002. __extends(Bone, _super);
  22003. function Bone(name, skeleton, parentBone, matrix) {
  22004. _super.call(this, name, skeleton.getScene());
  22005. this.name = name;
  22006. this.children = new Array();
  22007. this.animations = new Array();
  22008. this._worldTransform = new BABYLON.Matrix();
  22009. this._absoluteTransform = new BABYLON.Matrix();
  22010. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22011. this._skeleton = skeleton;
  22012. this._matrix = matrix;
  22013. this._baseMatrix = matrix;
  22014. skeleton.bones.push(this);
  22015. if (parentBone) {
  22016. this._parent = parentBone;
  22017. parentBone.children.push(this);
  22018. }
  22019. else {
  22020. this._parent = null;
  22021. }
  22022. this._updateDifferenceMatrix();
  22023. }
  22024. // Members
  22025. Bone.prototype.getParent = function () {
  22026. return this._parent;
  22027. };
  22028. Bone.prototype.getLocalMatrix = function () {
  22029. return this._matrix;
  22030. };
  22031. Bone.prototype.getBaseMatrix = function () {
  22032. return this._baseMatrix;
  22033. };
  22034. Bone.prototype.getWorldMatrix = function () {
  22035. return this._worldTransform;
  22036. };
  22037. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22038. return this._invertedAbsoluteTransform;
  22039. };
  22040. Bone.prototype.getAbsoluteMatrix = function () {
  22041. var matrix = this._matrix.clone();
  22042. var parent = this._parent;
  22043. while (parent) {
  22044. matrix = matrix.multiply(parent.getLocalMatrix());
  22045. parent = parent.getParent();
  22046. }
  22047. return matrix;
  22048. };
  22049. // Methods
  22050. Bone.prototype.updateMatrix = function (matrix) {
  22051. this._matrix = matrix;
  22052. this._skeleton._markAsDirty();
  22053. this._updateDifferenceMatrix();
  22054. };
  22055. Bone.prototype._updateDifferenceMatrix = function () {
  22056. if (this._parent) {
  22057. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22058. }
  22059. else {
  22060. this._absoluteTransform.copyFrom(this._matrix);
  22061. }
  22062. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22063. for (var index = 0; index < this.children.length; index++) {
  22064. this.children[index]._updateDifferenceMatrix();
  22065. }
  22066. };
  22067. Bone.prototype.markAsDirty = function () {
  22068. this._currentRenderId++;
  22069. this._skeleton._markAsDirty();
  22070. };
  22071. return Bone;
  22072. })(BABYLON.Node);
  22073. BABYLON.Bone = Bone;
  22074. })(BABYLON || (BABYLON = {}));
  22075. var BABYLON;
  22076. (function (BABYLON) {
  22077. var Skeleton = (function () {
  22078. function Skeleton(name, id, scene) {
  22079. this.name = name;
  22080. this.id = id;
  22081. this.bones = new Array();
  22082. this._isDirty = true;
  22083. this._identity = BABYLON.Matrix.Identity();
  22084. this._ranges = new Array();
  22085. this.bones = [];
  22086. this._scene = scene;
  22087. scene.skeletons.push(this);
  22088. this.prepare();
  22089. //make sure it will recalculate the matrix next time prepare is called.
  22090. this._isDirty = true;
  22091. }
  22092. // Members
  22093. Skeleton.prototype.getTransformMatrices = function () {
  22094. return this._transformMatrices;
  22095. };
  22096. Skeleton.prototype.getScene = function () {
  22097. return this._scene;
  22098. };
  22099. // Methods
  22100. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22101. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22102. };
  22103. Skeleton.prototype.deleteAnimationRange = function (name) {
  22104. for (var index = 0; index < this._ranges.length; index++) {
  22105. if (this._ranges[index].name === name) {
  22106. this._ranges.splice(index, 1);
  22107. return;
  22108. }
  22109. }
  22110. };
  22111. Skeleton.prototype.getAnimationRange = function (name) {
  22112. for (var index = 0; index < this._ranges.length; index++) {
  22113. if (this._ranges[index].name === name) {
  22114. return this._ranges[index];
  22115. }
  22116. }
  22117. return null;
  22118. };
  22119. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22120. var range = this.getAnimationRange(name);
  22121. if (!range) {
  22122. return null;
  22123. }
  22124. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22125. };
  22126. Skeleton.prototype._markAsDirty = function () {
  22127. this._isDirty = true;
  22128. };
  22129. Skeleton.prototype.prepare = function () {
  22130. if (!this._isDirty) {
  22131. return;
  22132. }
  22133. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22134. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22135. }
  22136. for (var index = 0; index < this.bones.length; index++) {
  22137. var bone = this.bones[index];
  22138. var parentBone = bone.getParent();
  22139. if (parentBone) {
  22140. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22141. }
  22142. else {
  22143. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22144. }
  22145. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22146. }
  22147. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22148. this._isDirty = false;
  22149. this._scene._activeBones += this.bones.length;
  22150. };
  22151. Skeleton.prototype.getAnimatables = function () {
  22152. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22153. this._animatables = [];
  22154. for (var index = 0; index < this.bones.length; index++) {
  22155. this._animatables.push(this.bones[index]);
  22156. }
  22157. }
  22158. return this._animatables;
  22159. };
  22160. Skeleton.prototype.clone = function (name, id) {
  22161. var result = new Skeleton(name, id || name, this._scene);
  22162. for (var index = 0; index < this.bones.length; index++) {
  22163. var source = this.bones[index];
  22164. var parentBone = null;
  22165. if (source.getParent()) {
  22166. var parentIndex = this.bones.indexOf(source.getParent());
  22167. parentBone = result.bones[parentIndex];
  22168. }
  22169. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22170. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22171. }
  22172. return result;
  22173. };
  22174. Skeleton.prototype.dispose = function () {
  22175. // Animations
  22176. this.getScene().stopAnimation(this);
  22177. // Remove from scene
  22178. this.getScene().removeSkeleton(this);
  22179. };
  22180. Skeleton.prototype.serialize = function () {
  22181. var serializationObject = {};
  22182. serializationObject.name = this.name;
  22183. serializationObject.id = this.id;
  22184. serializationObject.bones = [];
  22185. for (var index = 0; index < this.bones.length; index++) {
  22186. var bone = this.bones[index];
  22187. var serializedBone = {
  22188. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22189. name: bone.name,
  22190. matrix: bone.getLocalMatrix().toArray()
  22191. };
  22192. serializationObject.bones.push(serializedBone);
  22193. if (bone.animations && bone.animations.length > 0) {
  22194. serializedBone.animation = bone.animations[0].serialize();
  22195. }
  22196. }
  22197. return serializationObject;
  22198. };
  22199. Skeleton.Parse = function (parsedSkeleton, scene) {
  22200. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22201. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22202. var parsedBone = parsedSkeleton.bones[index];
  22203. var parentBone = null;
  22204. if (parsedBone.parentBoneIndex > -1) {
  22205. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22206. }
  22207. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  22208. if (parsedBone.animation) {
  22209. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22210. }
  22211. }
  22212. return skeleton;
  22213. };
  22214. return Skeleton;
  22215. })();
  22216. BABYLON.Skeleton = Skeleton;
  22217. })(BABYLON || (BABYLON = {}));
  22218. var BABYLON;
  22219. (function (BABYLON) {
  22220. var PostProcess = (function () {
  22221. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22224. this.name = name;
  22225. this.width = -1;
  22226. this.height = -1;
  22227. this._reusable = false;
  22228. this._textures = new BABYLON.SmartArray(2);
  22229. this._currentRenderTextureInd = 0;
  22230. if (camera != null) {
  22231. this._camera = camera;
  22232. this._scene = camera.getScene();
  22233. camera.attachPostProcess(this);
  22234. this._engine = this._scene.getEngine();
  22235. }
  22236. else {
  22237. this._engine = engine;
  22238. }
  22239. this._renderRatio = ratio;
  22240. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22241. this._reusable = reusable || false;
  22242. this._textureType = textureType;
  22243. this._samplers = samplers || [];
  22244. this._samplers.push("textureSampler");
  22245. this._fragmentUrl = fragmentUrl;
  22246. this._parameters = parameters || [];
  22247. this.updateEffect(defines);
  22248. }
  22249. PostProcess.prototype.updateEffect = function (defines) {
  22250. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22251. };
  22252. PostProcess.prototype.isReusable = function () {
  22253. return this._reusable;
  22254. };
  22255. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22256. camera = camera || this._camera;
  22257. var scene = camera.getScene();
  22258. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22259. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22260. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22261. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22262. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22263. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22264. if (this._textures.length > 0) {
  22265. for (var i = 0; i < this._textures.length; i++) {
  22266. this._engine._releaseTexture(this._textures.data[i]);
  22267. }
  22268. this._textures.reset();
  22269. }
  22270. this.width = desiredWidth;
  22271. this.height = desiredHeight;
  22272. 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 }));
  22273. if (this._reusable) {
  22274. 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 }));
  22275. }
  22276. if (this.onSizeChanged) {
  22277. this.onSizeChanged();
  22278. }
  22279. }
  22280. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22281. if (this.onActivate) {
  22282. this.onActivate(camera);
  22283. }
  22284. // Clear
  22285. if (this.clearColor) {
  22286. this._engine.clear(this.clearColor, true, true);
  22287. }
  22288. else {
  22289. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22290. }
  22291. if (this._reusable) {
  22292. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22293. }
  22294. };
  22295. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22296. get: function () {
  22297. return this._effect.isSupported;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. PostProcess.prototype.apply = function () {
  22303. // Check
  22304. if (!this._effect.isReady())
  22305. return null;
  22306. // States
  22307. this._engine.enableEffect(this._effect);
  22308. this._engine.setState(false);
  22309. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22310. this._engine.setDepthBuffer(false);
  22311. this._engine.setDepthWrite(false);
  22312. // Texture
  22313. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22314. // Parameters
  22315. if (this.onApply) {
  22316. this.onApply(this._effect);
  22317. }
  22318. return this._effect;
  22319. };
  22320. PostProcess.prototype.dispose = function (camera) {
  22321. camera = camera || this._camera;
  22322. if (this._textures.length > 0) {
  22323. for (var i = 0; i < this._textures.length; i++) {
  22324. this._engine._releaseTexture(this._textures.data[i]);
  22325. }
  22326. this._textures.reset();
  22327. }
  22328. if (!camera) {
  22329. return;
  22330. }
  22331. camera.detachPostProcess(this);
  22332. var index = camera._postProcesses.indexOf(this);
  22333. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22334. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22335. }
  22336. };
  22337. return PostProcess;
  22338. })();
  22339. BABYLON.PostProcess = PostProcess;
  22340. })(BABYLON || (BABYLON = {}));
  22341. var BABYLON;
  22342. (function (BABYLON) {
  22343. var PostProcessManager = (function () {
  22344. function PostProcessManager(scene) {
  22345. this._vertexDeclaration = [2];
  22346. this._vertexStrideSize = 2 * 4;
  22347. this._scene = scene;
  22348. }
  22349. PostProcessManager.prototype._prepareBuffers = function () {
  22350. if (this._vertexBuffer) {
  22351. return;
  22352. }
  22353. // VBO
  22354. var vertices = [];
  22355. vertices.push(1, 1);
  22356. vertices.push(-1, 1);
  22357. vertices.push(-1, -1);
  22358. vertices.push(1, -1);
  22359. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22360. // Indices
  22361. var indices = [];
  22362. indices.push(0);
  22363. indices.push(1);
  22364. indices.push(2);
  22365. indices.push(0);
  22366. indices.push(2);
  22367. indices.push(3);
  22368. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22369. };
  22370. // Methods
  22371. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22372. var postProcesses = this._scene.activeCamera._postProcesses;
  22373. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22374. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22375. return false;
  22376. }
  22377. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22378. return true;
  22379. };
  22380. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22381. var engine = this._scene.getEngine();
  22382. for (var index = 0; index < postProcesses.length; index++) {
  22383. if (index < postProcesses.length - 1) {
  22384. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22385. }
  22386. else {
  22387. if (targetTexture) {
  22388. engine.bindFramebuffer(targetTexture);
  22389. }
  22390. else {
  22391. engine.restoreDefaultFramebuffer();
  22392. }
  22393. }
  22394. var pp = postProcesses[index];
  22395. var effect = pp.apply();
  22396. if (effect) {
  22397. if (pp.onBeforeRender) {
  22398. pp.onBeforeRender(effect);
  22399. }
  22400. // VBOs
  22401. this._prepareBuffers();
  22402. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22403. // Draw order
  22404. engine.draw(true, 0, 6);
  22405. if (pp.onAfterRender) {
  22406. pp.onAfterRender(effect);
  22407. }
  22408. }
  22409. }
  22410. // Restore depth buffer
  22411. engine.setDepthBuffer(true);
  22412. engine.setDepthWrite(true);
  22413. };
  22414. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22415. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22416. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22417. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22418. return;
  22419. }
  22420. var engine = this._scene.getEngine();
  22421. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22422. if (index < postProcessesTakenIndices.length - 1) {
  22423. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22424. }
  22425. else {
  22426. if (targetTexture) {
  22427. engine.bindFramebuffer(targetTexture, faceIndex);
  22428. }
  22429. else {
  22430. engine.restoreDefaultFramebuffer();
  22431. }
  22432. }
  22433. if (doNotPresent) {
  22434. break;
  22435. }
  22436. var pp = postProcesses[postProcessesTakenIndices[index]];
  22437. var effect = pp.apply();
  22438. if (effect) {
  22439. if (pp.onBeforeRender) {
  22440. pp.onBeforeRender(effect);
  22441. }
  22442. // VBOs
  22443. this._prepareBuffers();
  22444. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22445. // Draw order
  22446. engine.draw(true, 0, 6);
  22447. if (pp.onAfterRender) {
  22448. pp.onAfterRender(effect);
  22449. }
  22450. }
  22451. }
  22452. // Restore depth buffer
  22453. engine.setDepthBuffer(true);
  22454. engine.setDepthWrite(true);
  22455. };
  22456. PostProcessManager.prototype.dispose = function () {
  22457. if (this._vertexBuffer) {
  22458. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22459. this._vertexBuffer = null;
  22460. }
  22461. if (this._indexBuffer) {
  22462. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22463. this._indexBuffer = null;
  22464. }
  22465. };
  22466. return PostProcessManager;
  22467. })();
  22468. BABYLON.PostProcessManager = PostProcessManager;
  22469. })(BABYLON || (BABYLON = {}));
  22470. var BABYLON;
  22471. (function (BABYLON) {
  22472. var PassPostProcess = (function (_super) {
  22473. __extends(PassPostProcess, _super);
  22474. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22475. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22476. }
  22477. return PassPostProcess;
  22478. })(BABYLON.PostProcess);
  22479. BABYLON.PassPostProcess = PassPostProcess;
  22480. })(BABYLON || (BABYLON = {}));
  22481. var BABYLON;
  22482. (function (BABYLON) {
  22483. var PhysicsEngine = (function () {
  22484. function PhysicsEngine(plugin) {
  22485. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22486. }
  22487. PhysicsEngine.prototype._initialize = function (gravity) {
  22488. this._currentPlugin.initialize();
  22489. this._setGravity(gravity);
  22490. };
  22491. PhysicsEngine.prototype._runOneStep = function (delta) {
  22492. if (delta > 0.1) {
  22493. delta = 0.1;
  22494. }
  22495. else if (delta <= 0) {
  22496. delta = 1.0 / 60.0;
  22497. }
  22498. this._currentPlugin.runOneStep(delta);
  22499. };
  22500. PhysicsEngine.prototype._setGravity = function (gravity) {
  22501. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22502. this._currentPlugin.setGravity(this.gravity);
  22503. };
  22504. PhysicsEngine.prototype._getGravity = function () {
  22505. return this._currentPlugin.getGravity();
  22506. };
  22507. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22508. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22509. };
  22510. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22511. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22512. };
  22513. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22514. this._currentPlugin.unregisterMesh(mesh);
  22515. };
  22516. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22517. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22518. };
  22519. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22520. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22521. };
  22522. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22523. this._currentPlugin.updateBodyPosition(mesh);
  22524. };
  22525. PhysicsEngine.prototype.dispose = function () {
  22526. this._currentPlugin.dispose();
  22527. };
  22528. PhysicsEngine.prototype.isSupported = function () {
  22529. return this._currentPlugin.isSupported();
  22530. };
  22531. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22532. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22533. };
  22534. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22535. return this._currentPlugin.name;
  22536. };
  22537. // Statics
  22538. PhysicsEngine.NoImpostor = 0;
  22539. PhysicsEngine.SphereImpostor = 1;
  22540. PhysicsEngine.BoxImpostor = 2;
  22541. PhysicsEngine.PlaneImpostor = 3;
  22542. PhysicsEngine.MeshImpostor = 4;
  22543. PhysicsEngine.CapsuleImpostor = 5;
  22544. PhysicsEngine.ConeImpostor = 6;
  22545. PhysicsEngine.CylinderImpostor = 7;
  22546. PhysicsEngine.ConvexHullImpostor = 8;
  22547. PhysicsEngine.HeightmapImpostor = 9;
  22548. PhysicsEngine.Epsilon = 0.001;
  22549. return PhysicsEngine;
  22550. })();
  22551. BABYLON.PhysicsEngine = PhysicsEngine;
  22552. })(BABYLON || (BABYLON = {}));
  22553. var BABYLON;
  22554. (function (BABYLON) {
  22555. var VertexData = (function () {
  22556. function VertexData() {
  22557. }
  22558. VertexData.prototype.set = function (data, kind) {
  22559. switch (kind) {
  22560. case BABYLON.VertexBuffer.PositionKind:
  22561. this.positions = data;
  22562. break;
  22563. case BABYLON.VertexBuffer.NormalKind:
  22564. this.normals = data;
  22565. break;
  22566. case BABYLON.VertexBuffer.UVKind:
  22567. this.uvs = data;
  22568. break;
  22569. case BABYLON.VertexBuffer.UV2Kind:
  22570. this.uvs2 = data;
  22571. break;
  22572. case BABYLON.VertexBuffer.UV3Kind:
  22573. this.uvs3 = data;
  22574. break;
  22575. case BABYLON.VertexBuffer.UV4Kind:
  22576. this.uvs4 = data;
  22577. break;
  22578. case BABYLON.VertexBuffer.UV5Kind:
  22579. this.uvs5 = data;
  22580. break;
  22581. case BABYLON.VertexBuffer.UV6Kind:
  22582. this.uvs6 = data;
  22583. break;
  22584. case BABYLON.VertexBuffer.ColorKind:
  22585. this.colors = data;
  22586. break;
  22587. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22588. this.matricesIndices = data;
  22589. break;
  22590. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22591. this.matricesWeights = data;
  22592. break;
  22593. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22594. this.matricesIndicesExtra = data;
  22595. break;
  22596. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22597. this.matricesWeightsExtra = data;
  22598. break;
  22599. }
  22600. };
  22601. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22602. this._applyTo(mesh, updatable);
  22603. };
  22604. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22605. this._applyTo(geometry, updatable);
  22606. };
  22607. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22608. this._update(mesh);
  22609. };
  22610. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22611. this._update(geometry);
  22612. };
  22613. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22614. if (this.positions) {
  22615. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22616. }
  22617. if (this.normals) {
  22618. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22619. }
  22620. if (this.uvs) {
  22621. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22622. }
  22623. if (this.uvs2) {
  22624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22625. }
  22626. if (this.uvs3) {
  22627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22628. }
  22629. if (this.uvs4) {
  22630. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22631. }
  22632. if (this.uvs5) {
  22633. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22634. }
  22635. if (this.uvs6) {
  22636. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22637. }
  22638. if (this.colors) {
  22639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22640. }
  22641. if (this.matricesIndices) {
  22642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22643. }
  22644. if (this.matricesWeights) {
  22645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22646. }
  22647. if (this.matricesIndicesExtra) {
  22648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22649. }
  22650. if (this.matricesWeightsExtra) {
  22651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22652. }
  22653. if (this.indices) {
  22654. meshOrGeometry.setIndices(this.indices);
  22655. }
  22656. };
  22657. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22658. if (this.positions) {
  22659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22660. }
  22661. if (this.normals) {
  22662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22663. }
  22664. if (this.uvs) {
  22665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22666. }
  22667. if (this.uvs2) {
  22668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22669. }
  22670. if (this.uvs3) {
  22671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22672. }
  22673. if (this.uvs4) {
  22674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22675. }
  22676. if (this.uvs5) {
  22677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22678. }
  22679. if (this.uvs6) {
  22680. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22681. }
  22682. if (this.colors) {
  22683. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22684. }
  22685. if (this.matricesIndices) {
  22686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22687. }
  22688. if (this.matricesWeights) {
  22689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22690. }
  22691. if (this.matricesIndicesExtra) {
  22692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22693. }
  22694. if (this.matricesWeightsExtra) {
  22695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22696. }
  22697. if (this.indices) {
  22698. meshOrGeometry.setIndices(this.indices);
  22699. }
  22700. };
  22701. VertexData.prototype.transform = function (matrix) {
  22702. var transformed = BABYLON.Vector3.Zero();
  22703. var index;
  22704. if (this.positions) {
  22705. var position = BABYLON.Vector3.Zero();
  22706. for (index = 0; index < this.positions.length; index += 3) {
  22707. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22708. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22709. this.positions[index] = transformed.x;
  22710. this.positions[index + 1] = transformed.y;
  22711. this.positions[index + 2] = transformed.z;
  22712. }
  22713. }
  22714. if (this.normals) {
  22715. var normal = BABYLON.Vector3.Zero();
  22716. for (index = 0; index < this.normals.length; index += 3) {
  22717. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22718. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22719. this.normals[index] = transformed.x;
  22720. this.normals[index + 1] = transformed.y;
  22721. this.normals[index + 2] = transformed.z;
  22722. }
  22723. }
  22724. };
  22725. VertexData.prototype.merge = function (other) {
  22726. var index;
  22727. if (other.indices) {
  22728. if (!this.indices) {
  22729. this.indices = [];
  22730. }
  22731. var offset = this.positions ? this.positions.length / 3 : 0;
  22732. for (index = 0; index < other.indices.length; index++) {
  22733. //TODO check type - if Int32Array!
  22734. this.indices.push(other.indices[index] + offset);
  22735. }
  22736. }
  22737. if (other.positions) {
  22738. if (!this.positions) {
  22739. this.positions = [];
  22740. }
  22741. for (index = 0; index < other.positions.length; index++) {
  22742. this.positions.push(other.positions[index]);
  22743. }
  22744. }
  22745. if (other.normals) {
  22746. if (!this.normals) {
  22747. this.normals = [];
  22748. }
  22749. for (index = 0; index < other.normals.length; index++) {
  22750. this.normals.push(other.normals[index]);
  22751. }
  22752. }
  22753. if (other.uvs) {
  22754. if (!this.uvs) {
  22755. this.uvs = [];
  22756. }
  22757. for (index = 0; index < other.uvs.length; index++) {
  22758. this.uvs.push(other.uvs[index]);
  22759. }
  22760. }
  22761. if (other.uvs2) {
  22762. if (!this.uvs2) {
  22763. this.uvs2 = [];
  22764. }
  22765. for (index = 0; index < other.uvs2.length; index++) {
  22766. this.uvs2.push(other.uvs2[index]);
  22767. }
  22768. }
  22769. if (other.uvs3) {
  22770. if (!this.uvs3) {
  22771. this.uvs3 = [];
  22772. }
  22773. for (index = 0; index < other.uvs3.length; index++) {
  22774. this.uvs3.push(other.uvs3[index]);
  22775. }
  22776. }
  22777. if (other.uvs4) {
  22778. if (!this.uvs4) {
  22779. this.uvs4 = [];
  22780. }
  22781. for (index = 0; index < other.uvs4.length; index++) {
  22782. this.uvs4.push(other.uvs4[index]);
  22783. }
  22784. }
  22785. if (other.uvs5) {
  22786. if (!this.uvs5) {
  22787. this.uvs5 = [];
  22788. }
  22789. for (index = 0; index < other.uvs5.length; index++) {
  22790. this.uvs5.push(other.uvs5[index]);
  22791. }
  22792. }
  22793. if (other.uvs6) {
  22794. if (!this.uvs6) {
  22795. this.uvs6 = [];
  22796. }
  22797. for (index = 0; index < other.uvs6.length; index++) {
  22798. this.uvs6.push(other.uvs6[index]);
  22799. }
  22800. }
  22801. if (other.matricesIndices) {
  22802. if (!this.matricesIndices) {
  22803. this.matricesIndices = [];
  22804. }
  22805. for (index = 0; index < other.matricesIndices.length; index++) {
  22806. this.matricesIndices.push(other.matricesIndices[index]);
  22807. }
  22808. }
  22809. if (other.matricesWeights) {
  22810. if (!this.matricesWeights) {
  22811. this.matricesWeights = [];
  22812. }
  22813. for (index = 0; index < other.matricesWeights.length; index++) {
  22814. this.matricesWeights.push(other.matricesWeights[index]);
  22815. }
  22816. }
  22817. if (other.matricesIndicesExtra) {
  22818. if (!this.matricesIndicesExtra) {
  22819. this.matricesIndicesExtra = [];
  22820. }
  22821. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  22822. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  22823. }
  22824. }
  22825. if (other.matricesWeightsExtra) {
  22826. if (!this.matricesWeightsExtra) {
  22827. this.matricesWeightsExtra = [];
  22828. }
  22829. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  22830. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  22831. }
  22832. }
  22833. if (other.colors) {
  22834. if (!this.colors) {
  22835. this.colors = [];
  22836. }
  22837. for (index = 0; index < other.colors.length; index++) {
  22838. this.colors.push(other.colors[index]);
  22839. }
  22840. }
  22841. };
  22842. VertexData.prototype.serialize = function () {
  22843. var serializationObject = this.serialize();
  22844. if (this.positions) {
  22845. serializationObject.positions = this.positions;
  22846. }
  22847. if (this.normals) {
  22848. serializationObject.normals = this.normals;
  22849. }
  22850. if (this.uvs) {
  22851. serializationObject.uvs = this.uvs;
  22852. }
  22853. if (this.uvs2) {
  22854. serializationObject.uvs2 = this.uvs2;
  22855. }
  22856. if (this.uvs3) {
  22857. serializationObject.uvs3 = this.uvs3;
  22858. }
  22859. if (this.uvs4) {
  22860. serializationObject.uvs4 = this.uvs4;
  22861. }
  22862. if (this.uvs5) {
  22863. serializationObject.uvs5 = this.uvs5;
  22864. }
  22865. if (this.uvs6) {
  22866. serializationObject.uvs6 = this.uvs6;
  22867. }
  22868. if (this.colors) {
  22869. serializationObject.colors = this.colors;
  22870. }
  22871. if (this.matricesIndices) {
  22872. serializationObject.matricesIndices = this.matricesIndices;
  22873. serializationObject.matricesIndices._isExpanded = true;
  22874. }
  22875. if (this.matricesWeights) {
  22876. serializationObject.matricesWeights = this.matricesWeights;
  22877. }
  22878. serializationObject.indices = this.indices;
  22879. return serializationObject;
  22880. };
  22881. // Statics
  22882. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22883. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22884. };
  22885. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22886. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22887. };
  22888. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22889. var result = new VertexData();
  22890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22891. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22892. }
  22893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22894. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22895. }
  22896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22897. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22898. }
  22899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22900. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22901. }
  22902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22903. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22904. }
  22905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22906. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22907. }
  22908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22909. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22910. }
  22911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22912. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22913. }
  22914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22915. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22916. }
  22917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22918. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22919. }
  22920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22921. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22922. }
  22923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22924. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22925. }
  22926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22927. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22928. }
  22929. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22930. return result;
  22931. };
  22932. VertexData.CreateRibbon = function (options) {
  22933. var pathArray = options.pathArray;
  22934. var closeArray = options.closeArray || false;
  22935. var closePath = options.closePath || false;
  22936. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22937. var offset = options.offset || defaultOffset;
  22938. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22939. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22940. var positions = [];
  22941. var indices = [];
  22942. var normals = [];
  22943. var uvs = [];
  22944. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22945. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22946. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22947. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22948. var minlg; // minimal length among all paths from pathArray
  22949. var lg = []; // array of path lengths : nb of vertex per path
  22950. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22951. var p; // path iterator
  22952. var i; // point iterator
  22953. var j; // point iterator
  22954. // if single path in pathArray
  22955. if (pathArray.length < 2) {
  22956. var ar1 = [];
  22957. var ar2 = [];
  22958. for (i = 0; i < pathArray[0].length - offset; i++) {
  22959. ar1.push(pathArray[0][i]);
  22960. ar2.push(pathArray[0][i + offset]);
  22961. }
  22962. pathArray = [ar1, ar2];
  22963. }
  22964. // positions and horizontal distances (u)
  22965. var idc = 0;
  22966. var closePathCorr = (closePath) ? 1 : 0;
  22967. var path;
  22968. var l;
  22969. minlg = pathArray[0].length;
  22970. var vectlg;
  22971. var dist;
  22972. for (p = 0; p < pathArray.length; p++) {
  22973. uTotalDistance[p] = 0;
  22974. us[p] = [0];
  22975. path = pathArray[p];
  22976. l = path.length;
  22977. minlg = (minlg < l) ? minlg : l;
  22978. j = 0;
  22979. while (j < l) {
  22980. positions.push(path[j].x, path[j].y, path[j].z);
  22981. if (j > 0) {
  22982. vectlg = path[j].subtract(path[j - 1]).length();
  22983. dist = vectlg + uTotalDistance[p];
  22984. us[p].push(dist);
  22985. uTotalDistance[p] = dist;
  22986. }
  22987. j++;
  22988. }
  22989. if (closePath) {
  22990. j--;
  22991. positions.push(path[0].x, path[0].y, path[0].z);
  22992. vectlg = path[j].subtract(path[0]).length();
  22993. dist = vectlg + uTotalDistance[p];
  22994. us[p].push(dist);
  22995. uTotalDistance[p] = dist;
  22996. }
  22997. lg[p] = l + closePathCorr;
  22998. idx[p] = idc;
  22999. idc += (l + closePathCorr);
  23000. }
  23001. // vertical distances (v)
  23002. var path1;
  23003. var path2;
  23004. var vertex1;
  23005. var vertex2;
  23006. for (i = 0; i < minlg + closePathCorr; i++) {
  23007. vTotalDistance[i] = 0;
  23008. vs[i] = [0];
  23009. for (p = 0; p < pathArray.length - 1; p++) {
  23010. path1 = pathArray[p];
  23011. path2 = pathArray[p + 1];
  23012. if (i === minlg) {
  23013. vertex1 = path1[0];
  23014. vertex2 = path2[0];
  23015. }
  23016. else {
  23017. vertex1 = path1[i];
  23018. vertex2 = path2[i];
  23019. }
  23020. vectlg = vertex2.subtract(vertex1).length();
  23021. dist = vectlg + vTotalDistance[i];
  23022. vs[i].push(dist);
  23023. vTotalDistance[i] = dist;
  23024. }
  23025. if (closeArray) {
  23026. path1 = pathArray[p];
  23027. path2 = pathArray[0];
  23028. if (i === minlg) {
  23029. vertex2 = path2[0];
  23030. }
  23031. vectlg = vertex2.subtract(vertex1).length();
  23032. dist = vectlg + vTotalDistance[i];
  23033. vTotalDistance[i] = dist;
  23034. }
  23035. }
  23036. // uvs
  23037. var u;
  23038. var v;
  23039. for (p = 0; p < pathArray.length; p++) {
  23040. for (i = 0; i < minlg + closePathCorr; i++) {
  23041. u = us[p][i] / uTotalDistance[p];
  23042. v = vs[i][p] / vTotalDistance[i];
  23043. uvs.push(u, v);
  23044. }
  23045. }
  23046. // indices
  23047. p = 0; // path index
  23048. var pi = 0; // positions array index
  23049. var l1 = lg[p] - 1; // path1 length
  23050. var l2 = lg[p + 1] - 1; // path2 length
  23051. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23052. var shft = idx[1] - idx[0]; // shift
  23053. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23054. while (pi <= min && p < path1nb) {
  23055. // 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
  23056. indices.push(pi, pi + shft, pi + 1);
  23057. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23058. pi += 1;
  23059. if (pi === min) {
  23060. p++;
  23061. if (p === lg.length - 1) {
  23062. shft = idx[0] - idx[p];
  23063. l1 = lg[p] - 1;
  23064. l2 = lg[0] - 1;
  23065. }
  23066. else {
  23067. shft = idx[p + 1] - idx[p];
  23068. l1 = lg[p] - 1;
  23069. l2 = lg[p + 1] - 1;
  23070. }
  23071. pi = idx[p];
  23072. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23073. }
  23074. }
  23075. // normals
  23076. VertexData.ComputeNormals(positions, indices, normals);
  23077. if (closePath) {
  23078. var indexFirst = 0;
  23079. var indexLast = 0;
  23080. for (p = 0; p < pathArray.length; p++) {
  23081. indexFirst = idx[p] * 3;
  23082. if (p + 1 < pathArray.length) {
  23083. indexLast = (idx[p + 1] - 1) * 3;
  23084. }
  23085. else {
  23086. indexLast = normals.length - 3;
  23087. }
  23088. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23089. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23090. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23091. normals[indexLast] = normals[indexFirst];
  23092. normals[indexLast + 1] = normals[indexFirst + 1];
  23093. normals[indexLast + 2] = normals[indexFirst + 2];
  23094. }
  23095. }
  23096. // sides
  23097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23098. // Result
  23099. var vertexData = new VertexData();
  23100. vertexData.indices = indices;
  23101. vertexData.positions = positions;
  23102. vertexData.normals = normals;
  23103. vertexData.uvs = uvs;
  23104. if (closePath) {
  23105. vertexData._idx = idx;
  23106. }
  23107. return vertexData;
  23108. };
  23109. VertexData.CreateBox = function (options) {
  23110. var normalsSource = [
  23111. new BABYLON.Vector3(0, 0, 1),
  23112. new BABYLON.Vector3(0, 0, -1),
  23113. new BABYLON.Vector3(1, 0, 0),
  23114. new BABYLON.Vector3(-1, 0, 0),
  23115. new BABYLON.Vector3(0, 1, 0),
  23116. new BABYLON.Vector3(0, -1, 0)
  23117. ];
  23118. var indices = [];
  23119. var positions = [];
  23120. var normals = [];
  23121. var uvs = [];
  23122. var width = options.width || options.size || 1;
  23123. var height = options.height || options.size || 1;
  23124. var depth = options.depth || options.size || 1;
  23125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23126. var faceUV = options.faceUV || new Array(6);
  23127. var faceColors = options.faceColors;
  23128. var colors = [];
  23129. // default face colors and UV if undefined
  23130. for (var f = 0; f < 6; f++) {
  23131. if (faceUV[f] === undefined) {
  23132. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23133. }
  23134. if (faceColors && faceColors[f] === undefined) {
  23135. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23136. }
  23137. }
  23138. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23139. // Create each face in turn.
  23140. for (var index = 0; index < normalsSource.length; index++) {
  23141. var normal = normalsSource[index];
  23142. // Get two vectors perpendicular to the face normal and to each other.
  23143. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23144. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23145. // Six indices (two triangles) per face.
  23146. var verticesLength = positions.length / 3;
  23147. indices.push(verticesLength);
  23148. indices.push(verticesLength + 1);
  23149. indices.push(verticesLength + 2);
  23150. indices.push(verticesLength);
  23151. indices.push(verticesLength + 2);
  23152. indices.push(verticesLength + 3);
  23153. // Four vertices per face.
  23154. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23155. positions.push(vertex.x, vertex.y, vertex.z);
  23156. normals.push(normal.x, normal.y, normal.z);
  23157. uvs.push(faceUV[index].z, faceUV[index].w);
  23158. if (faceColors) {
  23159. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23160. }
  23161. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23162. positions.push(vertex.x, vertex.y, vertex.z);
  23163. normals.push(normal.x, normal.y, normal.z);
  23164. uvs.push(faceUV[index].x, faceUV[index].w);
  23165. if (faceColors) {
  23166. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23167. }
  23168. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23169. positions.push(vertex.x, vertex.y, vertex.z);
  23170. normals.push(normal.x, normal.y, normal.z);
  23171. uvs.push(faceUV[index].x, faceUV[index].y);
  23172. if (faceColors) {
  23173. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23174. }
  23175. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23176. positions.push(vertex.x, vertex.y, vertex.z);
  23177. normals.push(normal.x, normal.y, normal.z);
  23178. uvs.push(faceUV[index].z, faceUV[index].y);
  23179. if (faceColors) {
  23180. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23181. }
  23182. }
  23183. // sides
  23184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23185. // Result
  23186. var vertexData = new VertexData();
  23187. vertexData.indices = indices;
  23188. vertexData.positions = positions;
  23189. vertexData.normals = normals;
  23190. vertexData.uvs = uvs;
  23191. if (faceColors) {
  23192. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23193. vertexData.colors = totalColors;
  23194. }
  23195. return vertexData;
  23196. };
  23197. VertexData.CreateSphere = function (options) {
  23198. var segments = options.segments || 32;
  23199. var diameterX = options.diameterX || options.diameter || 1;
  23200. var diameterY = options.diameterY || options.diameter || 1;
  23201. var diameterZ = options.diameterZ || options.diameter || 1;
  23202. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23203. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23204. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23205. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23206. var totalZRotationSteps = 2 + segments;
  23207. var totalYRotationSteps = 2 * totalZRotationSteps;
  23208. var indices = [];
  23209. var positions = [];
  23210. var normals = [];
  23211. var uvs = [];
  23212. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23213. var normalizedZ = zRotationStep / totalZRotationSteps;
  23214. var angleZ = normalizedZ * Math.PI * slice;
  23215. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23216. var normalizedY = yRotationStep / totalYRotationSteps;
  23217. var angleY = normalizedY * Math.PI * 2 * arc;
  23218. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23219. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23220. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23221. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23222. var vertex = complete.multiply(radius);
  23223. var normal = complete.divide(radius).normalize();
  23224. positions.push(vertex.x, vertex.y, vertex.z);
  23225. normals.push(normal.x, normal.y, normal.z);
  23226. uvs.push(normalizedY, normalizedZ);
  23227. }
  23228. if (zRotationStep > 0) {
  23229. var verticesCount = positions.length / 3;
  23230. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23231. indices.push((firstIndex));
  23232. indices.push((firstIndex + 1));
  23233. indices.push(firstIndex + totalYRotationSteps + 1);
  23234. indices.push((firstIndex + totalYRotationSteps + 1));
  23235. indices.push((firstIndex + 1));
  23236. indices.push((firstIndex + totalYRotationSteps + 2));
  23237. }
  23238. }
  23239. }
  23240. // Sides
  23241. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23242. // Result
  23243. var vertexData = new VertexData();
  23244. vertexData.indices = indices;
  23245. vertexData.positions = positions;
  23246. vertexData.normals = normals;
  23247. vertexData.uvs = uvs;
  23248. return vertexData;
  23249. };
  23250. // Cylinder and cone
  23251. VertexData.CreateCylinder = function (options) {
  23252. var height = options.height || 2;
  23253. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23254. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23255. var tessellation = options.tessellation || 24;
  23256. var subdivisions = options.subdivisions || 1;
  23257. var hasRings = options.hasRings;
  23258. var enclose = options.enclose;
  23259. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23260. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23261. var faceUV = options.faceUV || new Array(3);
  23262. var faceColors = options.faceColors;
  23263. // default face colors and UV if undefined
  23264. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23265. var ringNb = (hasRings) ? subdivisions : 1;
  23266. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23267. var f;
  23268. for (f = 0; f < surfaceNb; f++) {
  23269. if (faceColors && faceColors[f] === undefined) {
  23270. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23271. }
  23272. }
  23273. for (f = 0; f < surfaceNb; f++) {
  23274. if (faceUV && faceUV[f] === undefined) {
  23275. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23276. }
  23277. }
  23278. var indices = [];
  23279. var positions = [];
  23280. var normals = [];
  23281. var uvs = [];
  23282. var colors = [];
  23283. var angle_step = Math.PI * 2 * arc / tessellation;
  23284. var angle;
  23285. var h;
  23286. var radius;
  23287. var tan = (diameterBottom - diameterTop) / 2 / height;
  23288. var ringVertex = BABYLON.Vector3.Zero();
  23289. var ringNormal = BABYLON.Vector3.Zero();
  23290. var ringFirstVertex = BABYLON.Vector3.Zero();
  23291. var ringFirstNormal = BABYLON.Vector3.Zero();
  23292. var quadNormal = BABYLON.Vector3.Zero();
  23293. var Y = BABYLON.Axis.Y;
  23294. // positions, normals, uvs
  23295. var i;
  23296. var j;
  23297. var r;
  23298. var ringIdx = 1;
  23299. var s = 1; // surface index
  23300. var cs = 0;
  23301. var v = 0;
  23302. for (i = 0; i <= subdivisions; i++) {
  23303. h = i / subdivisions;
  23304. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23305. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23306. for (r = 0; r < ringIdx; r++) {
  23307. if (hasRings) {
  23308. s += r;
  23309. }
  23310. if (enclose) {
  23311. s += 2 * r;
  23312. }
  23313. for (j = 0; j <= tessellation; j++) {
  23314. angle = j * angle_step;
  23315. // position
  23316. ringVertex.x = Math.cos(-angle) * radius;
  23317. ringVertex.y = -height / 2 + h * height;
  23318. ringVertex.z = Math.sin(-angle) * radius;
  23319. // normal
  23320. if (diameterTop === 0 && i === subdivisions) {
  23321. // if no top cap, reuse former normals
  23322. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23323. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23324. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23325. }
  23326. else {
  23327. ringNormal.x = ringVertex.x;
  23328. ringNormal.z = ringVertex.z;
  23329. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23330. ringNormal.normalize();
  23331. }
  23332. // keep first ring vertex values for enclose
  23333. if (j === 0) {
  23334. ringFirstVertex.copyFrom(ringVertex);
  23335. ringFirstNormal.copyFrom(ringNormal);
  23336. }
  23337. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23338. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23339. if (hasRings) {
  23340. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23341. }
  23342. else {
  23343. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23344. }
  23345. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23346. if (faceColors) {
  23347. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23348. }
  23349. }
  23350. // if enclose, add four vertices and their dedicated normals
  23351. if (arc !== 1 && enclose) {
  23352. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23353. positions.push(0, ringVertex.y, 0);
  23354. positions.push(0, ringVertex.y, 0);
  23355. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23356. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23357. quadNormal.normalize();
  23358. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23359. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23360. quadNormal.normalize();
  23361. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23362. if (hasRings) {
  23363. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23364. }
  23365. else {
  23366. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23367. }
  23368. uvs.push(faceUV[s + 1].x, v);
  23369. uvs.push(faceUV[s + 1].z, v);
  23370. if (hasRings) {
  23371. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23372. }
  23373. else {
  23374. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23375. }
  23376. uvs.push(faceUV[s + 2].x, v);
  23377. uvs.push(faceUV[s + 2].z, v);
  23378. if (faceColors) {
  23379. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23380. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23381. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23382. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23383. }
  23384. }
  23385. if (cs !== s) {
  23386. cs = s;
  23387. }
  23388. }
  23389. }
  23390. // indices
  23391. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23392. var s;
  23393. i = 0;
  23394. for (s = 0; s < subdivisions; s++) {
  23395. for (j = 0; j < tessellation; j++) {
  23396. var i0 = i * (e + 1) + j;
  23397. var i1 = (i + 1) * (e + 1) + j;
  23398. var i2 = i * (e + 1) + (j + 1);
  23399. var i3 = (i + 1) * (e + 1) + (j + 1);
  23400. indices.push(i0, i1, i2);
  23401. indices.push(i3, i2, i1);
  23402. }
  23403. if (arc !== 1 && enclose) {
  23404. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23405. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23406. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23407. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23408. }
  23409. i = (hasRings) ? (i + 2) : (i + 1);
  23410. }
  23411. // Caps
  23412. var createCylinderCap = function (isTop) {
  23413. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23414. if (radius === 0) {
  23415. return;
  23416. }
  23417. // Cap positions, normals & uvs
  23418. var angle;
  23419. var circleVector;
  23420. var i;
  23421. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23422. var c;
  23423. if (faceColors) {
  23424. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23425. }
  23426. // cap center
  23427. var vbase = positions.length / 3;
  23428. var offset = isTop ? height / 2 : -height / 2;
  23429. var center = new BABYLON.Vector3(0, offset, 0);
  23430. positions.push(center.x, center.y, center.z);
  23431. normals.push(0, isTop ? 1 : -1, 0);
  23432. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23433. if (faceColors) {
  23434. colors.push(c.r, c.g, c.b, c.a);
  23435. }
  23436. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23437. for (i = 0; i <= tessellation; i++) {
  23438. angle = Math.PI * 2 * i * arc / tessellation;
  23439. var cos = Math.cos(-angle);
  23440. var sin = Math.sin(-angle);
  23441. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23442. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23443. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23444. normals.push(0, isTop ? 1 : -1, 0);
  23445. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23446. if (faceColors) {
  23447. colors.push(c.r, c.g, c.b, c.a);
  23448. }
  23449. }
  23450. // Cap indices
  23451. for (i = 0; i < tessellation; i++) {
  23452. if (!isTop) {
  23453. indices.push(vbase);
  23454. indices.push(vbase + (i + 1));
  23455. indices.push(vbase + (i + 2));
  23456. }
  23457. else {
  23458. indices.push(vbase);
  23459. indices.push(vbase + (i + 2));
  23460. indices.push(vbase + (i + 1));
  23461. }
  23462. }
  23463. };
  23464. // add caps to geometry
  23465. createCylinderCap(false);
  23466. createCylinderCap(true);
  23467. // Sides
  23468. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23469. var vertexData = new VertexData();
  23470. vertexData.indices = indices;
  23471. vertexData.positions = positions;
  23472. vertexData.normals = normals;
  23473. vertexData.uvs = uvs;
  23474. if (faceColors) {
  23475. vertexData.colors = colors;
  23476. }
  23477. return vertexData;
  23478. };
  23479. VertexData.CreateTorus = function (options) {
  23480. var indices = [];
  23481. var positions = [];
  23482. var normals = [];
  23483. var uvs = [];
  23484. var diameter = options.diameter || 1;
  23485. var thickness = options.thickness || 0.5;
  23486. var tessellation = options.tessellation || 16;
  23487. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23488. var stride = tessellation + 1;
  23489. for (var i = 0; i <= tessellation; i++) {
  23490. var u = i / tessellation;
  23491. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23492. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23493. for (var j = 0; j <= tessellation; j++) {
  23494. var v = 1 - j / tessellation;
  23495. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23496. var dx = Math.cos(innerAngle);
  23497. var dy = Math.sin(innerAngle);
  23498. // Create a vertex.
  23499. var normal = new BABYLON.Vector3(dx, dy, 0);
  23500. var position = normal.scale(thickness / 2);
  23501. var textureCoordinate = new BABYLON.Vector2(u, v);
  23502. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23503. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23504. positions.push(position.x, position.y, position.z);
  23505. normals.push(normal.x, normal.y, normal.z);
  23506. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23507. // And create indices for two triangles.
  23508. var nextI = (i + 1) % stride;
  23509. var nextJ = (j + 1) % stride;
  23510. indices.push(i * stride + j);
  23511. indices.push(i * stride + nextJ);
  23512. indices.push(nextI * stride + j);
  23513. indices.push(i * stride + nextJ);
  23514. indices.push(nextI * stride + nextJ);
  23515. indices.push(nextI * stride + j);
  23516. }
  23517. }
  23518. // Sides
  23519. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23520. // Result
  23521. var vertexData = new VertexData();
  23522. vertexData.indices = indices;
  23523. vertexData.positions = positions;
  23524. vertexData.normals = normals;
  23525. vertexData.uvs = uvs;
  23526. return vertexData;
  23527. };
  23528. VertexData.CreateLines = function (options) {
  23529. var indices = [];
  23530. var positions = [];
  23531. var points = options.points;
  23532. for (var index = 0; index < points.length; index++) {
  23533. positions.push(points[index].x, points[index].y, points[index].z);
  23534. if (index > 0) {
  23535. indices.push(index - 1);
  23536. indices.push(index);
  23537. }
  23538. }
  23539. // Result
  23540. var vertexData = new VertexData();
  23541. vertexData.indices = indices;
  23542. vertexData.positions = positions;
  23543. return vertexData;
  23544. };
  23545. VertexData.CreateDashedLines = function (options) {
  23546. var dashSize = options.dashSize || 3;
  23547. var gapSize = options.gapSize || 1;
  23548. var dashNb = options.dashNb || 200;
  23549. var points = options.points;
  23550. var positions = new Array();
  23551. var indices = new Array();
  23552. var curvect = BABYLON.Vector3.Zero();
  23553. var lg = 0;
  23554. var nb = 0;
  23555. var shft = 0;
  23556. var dashshft = 0;
  23557. var curshft = 0;
  23558. var idx = 0;
  23559. var i = 0;
  23560. for (i = 0; i < points.length - 1; i++) {
  23561. points[i + 1].subtractToRef(points[i], curvect);
  23562. lg += curvect.length();
  23563. }
  23564. shft = lg / dashNb;
  23565. dashshft = dashSize * shft / (dashSize + gapSize);
  23566. for (i = 0; i < points.length - 1; i++) {
  23567. points[i + 1].subtractToRef(points[i], curvect);
  23568. nb = Math.floor(curvect.length() / shft);
  23569. curvect.normalize();
  23570. for (var j = 0; j < nb; j++) {
  23571. curshft = shft * j;
  23572. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23573. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23574. indices.push(idx, idx + 1);
  23575. idx += 2;
  23576. }
  23577. }
  23578. // Result
  23579. var vertexData = new VertexData();
  23580. vertexData.positions = positions;
  23581. vertexData.indices = indices;
  23582. return vertexData;
  23583. };
  23584. VertexData.CreateGround = function (options) {
  23585. var indices = [];
  23586. var positions = [];
  23587. var normals = [];
  23588. var uvs = [];
  23589. var row, col;
  23590. var width = options.width || 1;
  23591. var height = options.height || 1;
  23592. var subdivisions = options.subdivisions || 1;
  23593. for (row = 0; row <= subdivisions; row++) {
  23594. for (col = 0; col <= subdivisions; col++) {
  23595. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23596. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23597. positions.push(position.x, position.y, position.z);
  23598. normals.push(normal.x, normal.y, normal.z);
  23599. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23600. }
  23601. }
  23602. for (row = 0; row < subdivisions; row++) {
  23603. for (col = 0; col < subdivisions; col++) {
  23604. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23605. indices.push(col + 1 + row * (subdivisions + 1));
  23606. indices.push(col + row * (subdivisions + 1));
  23607. indices.push(col + (row + 1) * (subdivisions + 1));
  23608. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23609. indices.push(col + row * (subdivisions + 1));
  23610. }
  23611. }
  23612. // Result
  23613. var vertexData = new VertexData();
  23614. vertexData.indices = indices;
  23615. vertexData.positions = positions;
  23616. vertexData.normals = normals;
  23617. vertexData.uvs = uvs;
  23618. return vertexData;
  23619. };
  23620. VertexData.CreateTiledGround = function (options) {
  23621. var xmin = options.xmin;
  23622. var zmin = options.zmin;
  23623. var xmax = options.xmax;
  23624. var zmax = options.zmax;
  23625. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23626. var precision = options.precision || { w: 1, h: 1 };
  23627. var indices = [];
  23628. var positions = [];
  23629. var normals = [];
  23630. var uvs = [];
  23631. var row, col, tileRow, tileCol;
  23632. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23633. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23634. precision.w = (precision.w < 1) ? 1 : precision.w;
  23635. precision.h = (precision.h < 1) ? 1 : precision.h;
  23636. var tileSize = {
  23637. 'w': (xmax - xmin) / subdivisions.w,
  23638. 'h': (zmax - zmin) / subdivisions.h
  23639. };
  23640. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23641. // Indices
  23642. var base = positions.length / 3;
  23643. var rowLength = precision.w + 1;
  23644. for (row = 0; row < precision.h; row++) {
  23645. for (col = 0; col < precision.w; col++) {
  23646. var square = [
  23647. base + col + row * rowLength,
  23648. base + (col + 1) + row * rowLength,
  23649. base + (col + 1) + (row + 1) * rowLength,
  23650. base + col + (row + 1) * rowLength
  23651. ];
  23652. indices.push(square[1]);
  23653. indices.push(square[2]);
  23654. indices.push(square[3]);
  23655. indices.push(square[0]);
  23656. indices.push(square[1]);
  23657. indices.push(square[3]);
  23658. }
  23659. }
  23660. // Position, normals and uvs
  23661. var position = BABYLON.Vector3.Zero();
  23662. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23663. for (row = 0; row <= precision.h; row++) {
  23664. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23665. for (col = 0; col <= precision.w; col++) {
  23666. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23667. position.y = 0;
  23668. positions.push(position.x, position.y, position.z);
  23669. normals.push(normal.x, normal.y, normal.z);
  23670. uvs.push(col / precision.w, row / precision.h);
  23671. }
  23672. }
  23673. }
  23674. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23675. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23676. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23677. }
  23678. }
  23679. // Result
  23680. var vertexData = new VertexData();
  23681. vertexData.indices = indices;
  23682. vertexData.positions = positions;
  23683. vertexData.normals = normals;
  23684. vertexData.uvs = uvs;
  23685. return vertexData;
  23686. };
  23687. VertexData.CreateGroundFromHeightMap = function (options) {
  23688. var indices = [];
  23689. var positions = [];
  23690. var normals = [];
  23691. var uvs = [];
  23692. var row, col;
  23693. // Vertices
  23694. for (row = 0; row <= options.subdivisions; row++) {
  23695. for (col = 0; col <= options.subdivisions; col++) {
  23696. 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));
  23697. // Compute height
  23698. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23699. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23700. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23701. var r = options.buffer[pos] / 255.0;
  23702. var g = options.buffer[pos + 1] / 255.0;
  23703. var b = options.buffer[pos + 2] / 255.0;
  23704. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23705. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23706. // Add vertex
  23707. positions.push(position.x, position.y, position.z);
  23708. normals.push(0, 0, 0);
  23709. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23710. }
  23711. }
  23712. // Indices
  23713. for (row = 0; row < options.subdivisions; row++) {
  23714. for (col = 0; col < options.subdivisions; col++) {
  23715. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23716. indices.push(col + 1 + row * (options.subdivisions + 1));
  23717. indices.push(col + row * (options.subdivisions + 1));
  23718. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23719. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23720. indices.push(col + row * (options.subdivisions + 1));
  23721. }
  23722. }
  23723. // Normals
  23724. VertexData.ComputeNormals(positions, indices, normals);
  23725. // Result
  23726. var vertexData = new VertexData();
  23727. vertexData.indices = indices;
  23728. vertexData.positions = positions;
  23729. vertexData.normals = normals;
  23730. vertexData.uvs = uvs;
  23731. return vertexData;
  23732. };
  23733. VertexData.CreatePlane = function (options) {
  23734. var indices = [];
  23735. var positions = [];
  23736. var normals = [];
  23737. var uvs = [];
  23738. var width = options.width || options.size || 1;
  23739. var height = options.height || options.size || 1;
  23740. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23741. // Vertices
  23742. var halfWidth = width / 2.0;
  23743. var halfHeight = height / 2.0;
  23744. positions.push(-halfWidth, -halfHeight, 0);
  23745. normals.push(0, 0, -1.0);
  23746. uvs.push(0.0, 0.0);
  23747. positions.push(halfWidth, -halfHeight, 0);
  23748. normals.push(0, 0, -1.0);
  23749. uvs.push(1.0, 0.0);
  23750. positions.push(halfWidth, halfHeight, 0);
  23751. normals.push(0, 0, -1.0);
  23752. uvs.push(1.0, 1.0);
  23753. positions.push(-halfWidth, halfHeight, 0);
  23754. normals.push(0, 0, -1.0);
  23755. uvs.push(0.0, 1.0);
  23756. // Indices
  23757. indices.push(0);
  23758. indices.push(1);
  23759. indices.push(2);
  23760. indices.push(0);
  23761. indices.push(2);
  23762. indices.push(3);
  23763. // Sides
  23764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23765. // Result
  23766. var vertexData = new VertexData();
  23767. vertexData.indices = indices;
  23768. vertexData.positions = positions;
  23769. vertexData.normals = normals;
  23770. vertexData.uvs = uvs;
  23771. return vertexData;
  23772. };
  23773. VertexData.CreateDisc = function (options) {
  23774. var positions = [];
  23775. var indices = [];
  23776. var normals = [];
  23777. var uvs = [];
  23778. var radius = options.radius || 0.5;
  23779. var tessellation = options.tessellation || 64;
  23780. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23782. // positions and uvs
  23783. positions.push(0, 0, 0); // disc center first
  23784. uvs.push(0.5, 0.5);
  23785. var theta = Math.PI * 2 * arc;
  23786. var step = theta / tessellation;
  23787. for (var a = 0; a < theta; a += step) {
  23788. var x = Math.cos(a);
  23789. var y = Math.sin(a);
  23790. var u = (x + 1) / 2;
  23791. var v = (1 - y) / 2;
  23792. positions.push(radius * x, radius * y, 0);
  23793. uvs.push(u, v);
  23794. }
  23795. if (arc === 1) {
  23796. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23797. uvs.push(uvs[2], uvs[3]);
  23798. }
  23799. //indices
  23800. var vertexNb = positions.length / 3;
  23801. for (var i = 1; i < vertexNb - 1; i++) {
  23802. indices.push(i + 1, 0, i);
  23803. }
  23804. // result
  23805. VertexData.ComputeNormals(positions, indices, normals);
  23806. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  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.CreateIcoSphere = function (options) {
  23815. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23816. var radius = options.radius || 1;
  23817. var flat = (options.flat === undefined) ? true : options.flat;
  23818. var subdivisions = options.subdivisions || 4;
  23819. var radiusX = options.radiusX || radius;
  23820. var radiusY = options.radiusY || radius;
  23821. var radiusZ = options.radiusZ || radius;
  23822. var t = (1 + Math.sqrt(5)) / 2;
  23823. // 12 vertex x,y,z
  23824. var ico_vertices = [
  23825. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23826. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23827. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23828. ];
  23829. // index of 3 vertex makes a face of icopshere
  23830. var ico_indices = [
  23831. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23832. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23833. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23834. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23835. ];
  23836. // vertex for uv have aliased position, not for UV
  23837. var vertices_unalias_id = [
  23838. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23839. // vertex alias
  23840. 0,
  23841. 2,
  23842. 3,
  23843. 3,
  23844. 3,
  23845. 4,
  23846. 7,
  23847. 8,
  23848. 9,
  23849. 9,
  23850. 10,
  23851. 11 // 23: B + 12
  23852. ];
  23853. // uv as integer step (not pixels !)
  23854. var ico_vertexuv = [
  23855. 5, 1, 3, 1, 6, 4, 0, 0,
  23856. 5, 3, 4, 2, 2, 2, 4, 0,
  23857. 2, 0, 1, 1, 6, 0, 6, 2,
  23858. // vertex alias (for same vertex on different faces)
  23859. 0, 4,
  23860. 3, 3,
  23861. 4, 4,
  23862. 3, 1,
  23863. 4, 2,
  23864. 4, 4,
  23865. 0, 2,
  23866. 1, 1,
  23867. 2, 2,
  23868. 3, 3,
  23869. 1, 3,
  23870. 2, 4 // 23: B + 12
  23871. ];
  23872. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23873. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23874. // First island of uv mapping
  23875. // v = 4h 3+ 2
  23876. // v = 3h 9+ 4
  23877. // v = 2h 9+ 5 B
  23878. // v = 1h 9 1 0
  23879. // v = 0h 3 8 7 A
  23880. // u = 0 1 2 3 4 5 6 *a
  23881. // Second island of uv mapping
  23882. // v = 4h 0+ B+ 4+
  23883. // v = 3h A+ 2+
  23884. // v = 2h 7+ 6 3+
  23885. // v = 1h 8+ 3+
  23886. // v = 0h
  23887. // u = 0 1 2 3 4 5 6 *a
  23888. // Face layout on texture UV mapping
  23889. // ============
  23890. // \ 4 /\ 16 / ======
  23891. // \ / \ / /\ 11 /
  23892. // \/ 7 \/ / \ /
  23893. // ======= / 10 \/
  23894. // /\ 17 /\ =======
  23895. // / \ / \ \ 15 /\
  23896. // / 8 \/ 12 \ \ / \
  23897. // ============ \/ 6 \
  23898. // \ 18 /\ ============
  23899. // \ / \ \ 5 /\ 0 /
  23900. // \/ 13 \ \ / \ /
  23901. // ======= \/ 1 \/
  23902. // =============
  23903. // /\ 19 /\ 2 /\
  23904. // / \ / \ / \
  23905. // / 14 \/ 9 \/ 3 \
  23906. // ===================
  23907. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23908. var ustep = 138 / 1024;
  23909. var vstep = 239 / 1024;
  23910. var uoffset = 60 / 1024;
  23911. var voffset = 26 / 1024;
  23912. // Second island should have margin, not to touch the first island
  23913. // avoid any borderline artefact in pixel rounding
  23914. var island_u_offset = -40 / 1024;
  23915. var island_v_offset = +20 / 1024;
  23916. // face is either island 0 or 1 :
  23917. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23918. var island = [
  23919. 0, 0, 0, 0, 1,
  23920. 0, 0, 1, 1, 0,
  23921. 0, 0, 1, 1, 0,
  23922. 0, 1, 1, 1, 0 // 15 - 19
  23923. ];
  23924. var indices = [];
  23925. var positions = [];
  23926. var normals = [];
  23927. var uvs = [];
  23928. var current_indice = 0;
  23929. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23930. var face_vertex_pos = new Array(3);
  23931. var face_vertex_uv = new Array(3);
  23932. var v012;
  23933. for (v012 = 0; v012 < 3; v012++) {
  23934. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23935. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23936. }
  23937. // create all with normals
  23938. for (var face = 0; face < 20; face++) {
  23939. // 3 vertex per face
  23940. for (v012 = 0; v012 < 3; v012++) {
  23941. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23942. var v_id = ico_indices[3 * face + v012];
  23943. // vertex have 3D position (x,y,z)
  23944. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  23945. // Normalize to get normal, then scale to radius
  23946. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23947. // uv Coordinates from vertex ID
  23948. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  23949. }
  23950. // Subdivide the face (interpolate pos, norm, uv)
  23951. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23952. // - norm is linear interpolation of vertex corner normal
  23953. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23954. // - uv is linear interpolation
  23955. //
  23956. // Topology is as below for sub-divide by 2
  23957. // vertex shown as v0,v1,v2
  23958. // interp index is i1 to progress in range [v0,v1[
  23959. // interp index is i2 to progress in range [v0,v2[
  23960. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23961. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23962. //
  23963. //
  23964. // i2 v2
  23965. // ^ ^
  23966. // / / \
  23967. // / / \
  23968. // / / \
  23969. // / / (0,1) \
  23970. // / #---------\
  23971. // / / \ (0,0)'/ \
  23972. // / / \ / \
  23973. // / / \ / \
  23974. // / / (0,0) \ / (1,0) \
  23975. // / #---------#---------\
  23976. // v0 v1
  23977. //
  23978. // --------------------> i1
  23979. //
  23980. // interp of (i1,i2):
  23981. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  23982. // along i1 : lerp(x0,x1, i1/(S-i2))
  23983. //
  23984. // centroid of triangle is needed to get help normal computation
  23985. // (c1,c2) are used for centroid location
  23986. var interp_vertex = function (i1, i2, c1, c2) {
  23987. // vertex is interpolated from
  23988. // - face_vertex_pos[0..2]
  23989. // - face_vertex_uv[0..2]
  23990. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  23991. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  23992. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  23993. pos_interp.normalize();
  23994. var vertex_normal;
  23995. if (flat) {
  23996. // in flat mode, recalculate normal as face centroid normal
  23997. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  23998. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  23999. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24000. }
  24001. else {
  24002. // in smooth mode, recalculate normal from each single vertex position
  24003. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24004. }
  24005. // Vertex normal need correction due to X,Y,Z radius scaling
  24006. vertex_normal.x /= radiusX;
  24007. vertex_normal.y /= radiusY;
  24008. vertex_normal.z /= radiusZ;
  24009. vertex_normal.normalize();
  24010. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24011. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24012. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24013. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24014. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24015. uvs.push(uv_interp.x, uv_interp.y);
  24016. // push each vertex has member of a face
  24017. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24018. indices.push(current_indice);
  24019. current_indice++;
  24020. };
  24021. for (var i2 = 0; i2 < subdivisions; i2++) {
  24022. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24023. // face : (i1,i2) for /\ :
  24024. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24025. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24026. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24027. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24028. if (i1 + i2 + 1 < subdivisions) {
  24029. // face : (i1,i2)' for \/ :
  24030. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24031. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24032. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24033. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24034. }
  24035. }
  24036. }
  24037. }
  24038. // Sides
  24039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24040. // Result
  24041. var vertexData = new VertexData();
  24042. vertexData.indices = indices;
  24043. vertexData.positions = positions;
  24044. vertexData.normals = normals;
  24045. vertexData.uvs = uvs;
  24046. return vertexData;
  24047. };
  24048. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24049. VertexData.CreatePolyhedron = function (options) {
  24050. // provided polyhedron types :
  24051. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24052. // 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)
  24053. var polyhedra = [];
  24054. 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]] };
  24055. 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]] };
  24056. polyhedra[2] = {
  24057. 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]],
  24058. 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]]
  24059. };
  24060. polyhedra[3] = {
  24061. 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]],
  24062. 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]]
  24063. };
  24064. polyhedra[4] = {
  24065. 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]],
  24066. 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]]
  24067. };
  24068. 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]] };
  24069. 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]] };
  24070. 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]] };
  24071. 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]] };
  24072. 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]] };
  24073. 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]] };
  24074. 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]] };
  24075. 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]] };
  24076. 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]] };
  24077. polyhedra[14] = {
  24078. 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]],
  24079. 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]]
  24080. };
  24081. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24082. var size = options.size;
  24083. var sizeX = options.sizeX || size || 1;
  24084. var sizeY = options.sizeY || size || 1;
  24085. var sizeZ = options.sizeZ || size || 1;
  24086. var data = options.custom || polyhedra[type];
  24087. var nbfaces = data.face.length;
  24088. var faceUV = options.faceUV || new Array(nbfaces);
  24089. var faceColors = options.faceColors;
  24090. var flat = (options.flat === undefined) ? true : options.flat;
  24091. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24092. var positions = [];
  24093. var indices = [];
  24094. var normals = [];
  24095. var uvs = [];
  24096. var colors = [];
  24097. var index = 0;
  24098. var faceIdx = 0; // face cursor in the array "indexes"
  24099. var indexes = [];
  24100. var i = 0;
  24101. var f = 0;
  24102. var u, v, ang, x, y, tmp;
  24103. // default face colors and UV if undefined
  24104. if (flat) {
  24105. for (f = 0; f < nbfaces; f++) {
  24106. if (faceColors && faceColors[f] === undefined) {
  24107. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24108. }
  24109. if (faceUV && faceUV[f] === undefined) {
  24110. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24111. }
  24112. }
  24113. }
  24114. if (!flat) {
  24115. for (i = 0; i < data.vertex.length; i++) {
  24116. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24117. uvs.push(0, 0);
  24118. }
  24119. for (f = 0; f < nbfaces; f++) {
  24120. for (i = 0; i < data.face[f].length - 2; i++) {
  24121. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24122. }
  24123. }
  24124. }
  24125. else {
  24126. for (f = 0; f < nbfaces; f++) {
  24127. var fl = data.face[f].length; // number of vertices of the current face
  24128. ang = 2 * Math.PI / fl;
  24129. x = 0.5 * Math.tan(ang / 2);
  24130. y = 0.5;
  24131. // positions, uvs, colors
  24132. for (i = 0; i < fl; i++) {
  24133. // positions
  24134. 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);
  24135. indexes.push(index);
  24136. index++;
  24137. // uvs
  24138. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24139. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24140. uvs.push(u, v);
  24141. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24142. y = x * Math.sin(ang) + y * Math.cos(ang);
  24143. x = tmp;
  24144. // colors
  24145. if (faceColors) {
  24146. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24147. }
  24148. }
  24149. // indices from indexes
  24150. for (i = 0; i < fl - 2; i++) {
  24151. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24152. }
  24153. faceIdx += fl;
  24154. }
  24155. }
  24156. VertexData.ComputeNormals(positions, indices, normals);
  24157. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24158. var vertexData = new VertexData();
  24159. vertexData.positions = positions;
  24160. vertexData.indices = indices;
  24161. vertexData.normals = normals;
  24162. vertexData.uvs = uvs;
  24163. if (faceColors && flat) {
  24164. vertexData.colors = colors;
  24165. }
  24166. return vertexData;
  24167. };
  24168. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24169. VertexData.CreateTorusKnot = function (options) {
  24170. var indices = [];
  24171. var positions = [];
  24172. var normals = [];
  24173. var uvs = [];
  24174. var radius = options.radius || 2;
  24175. var tube = options.tube || 0.5;
  24176. var radialSegments = options.radialSegments || 32;
  24177. var tubularSegments = options.tubularSegments || 32;
  24178. var p = options.p || 2;
  24179. var q = options.q || 3;
  24180. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24181. // Helper
  24182. var getPos = function (angle) {
  24183. var cu = Math.cos(angle);
  24184. var su = Math.sin(angle);
  24185. var quOverP = q / p * angle;
  24186. var cs = Math.cos(quOverP);
  24187. var tx = radius * (2 + cs) * 0.5 * cu;
  24188. var ty = radius * (2 + cs) * su * 0.5;
  24189. var tz = radius * Math.sin(quOverP) * 0.5;
  24190. return new BABYLON.Vector3(tx, ty, tz);
  24191. };
  24192. // Vertices
  24193. var i;
  24194. var j;
  24195. for (i = 0; i <= radialSegments; i++) {
  24196. var modI = i % radialSegments;
  24197. var u = modI / radialSegments * 2 * p * Math.PI;
  24198. var p1 = getPos(u);
  24199. var p2 = getPos(u + 0.01);
  24200. var tang = p2.subtract(p1);
  24201. var n = p2.add(p1);
  24202. var bitan = BABYLON.Vector3.Cross(tang, n);
  24203. n = BABYLON.Vector3.Cross(bitan, tang);
  24204. bitan.normalize();
  24205. n.normalize();
  24206. for (j = 0; j < tubularSegments; j++) {
  24207. var modJ = j % tubularSegments;
  24208. var v = modJ / tubularSegments * 2 * Math.PI;
  24209. var cx = -tube * Math.cos(v);
  24210. var cy = tube * Math.sin(v);
  24211. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24212. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24213. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24214. uvs.push(i / radialSegments);
  24215. uvs.push(j / tubularSegments);
  24216. }
  24217. }
  24218. for (i = 0; i < radialSegments; i++) {
  24219. for (j = 0; j < tubularSegments; j++) {
  24220. var jNext = (j + 1) % tubularSegments;
  24221. var a = i * tubularSegments + j;
  24222. var b = (i + 1) * tubularSegments + j;
  24223. var c = (i + 1) * tubularSegments + jNext;
  24224. var d = i * tubularSegments + jNext;
  24225. indices.push(d);
  24226. indices.push(b);
  24227. indices.push(a);
  24228. indices.push(d);
  24229. indices.push(c);
  24230. indices.push(b);
  24231. }
  24232. }
  24233. // Normals
  24234. VertexData.ComputeNormals(positions, indices, normals);
  24235. // Sides
  24236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24237. // Result
  24238. var vertexData = new VertexData();
  24239. vertexData.indices = indices;
  24240. vertexData.positions = positions;
  24241. vertexData.normals = normals;
  24242. vertexData.uvs = uvs;
  24243. return vertexData;
  24244. };
  24245. // Tools
  24246. /**
  24247. * @param {any} - positions (number[] or Float32Array)
  24248. * @param {any} - indices (number[] or Uint16Array)
  24249. * @param {any} - normals (number[] or Float32Array)
  24250. */
  24251. VertexData.ComputeNormals = function (positions, indices, normals) {
  24252. var index = 0;
  24253. var p1p2x = 0.0;
  24254. var p1p2y = 0.0;
  24255. var p1p2z = 0.0;
  24256. var p3p2x = 0.0;
  24257. var p3p2y = 0.0;
  24258. var p3p2z = 0.0;
  24259. var faceNormalx = 0.0;
  24260. var faceNormaly = 0.0;
  24261. var faceNormalz = 0.0;
  24262. var length = 0.0;
  24263. var i1 = 0;
  24264. var i2 = 0;
  24265. var i3 = 0;
  24266. for (index = 0; index < positions.length; index++) {
  24267. normals[index] = 0.0;
  24268. }
  24269. // indice triplet = 1 face
  24270. var nbFaces = indices.length / 3;
  24271. for (index = 0; index < nbFaces; index++) {
  24272. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24273. i2 = indices[index * 3 + 1];
  24274. i3 = indices[index * 3 + 2];
  24275. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24276. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24277. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24278. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24279. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24280. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24281. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24282. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24283. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24284. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24285. length = (length === 0) ? 1.0 : length;
  24286. faceNormalx /= length; // normalize this normal
  24287. faceNormaly /= length;
  24288. faceNormalz /= length;
  24289. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24290. normals[i1 * 3 + 1] += faceNormaly;
  24291. normals[i1 * 3 + 2] += faceNormalz;
  24292. normals[i2 * 3] += faceNormalx;
  24293. normals[i2 * 3 + 1] += faceNormaly;
  24294. normals[i2 * 3 + 2] += faceNormalz;
  24295. normals[i3 * 3] += faceNormalx;
  24296. normals[i3 * 3 + 1] += faceNormaly;
  24297. normals[i3 * 3 + 2] += faceNormalz;
  24298. }
  24299. // last normalization of each normal
  24300. for (index = 0; index < normals.length / 3; index++) {
  24301. faceNormalx = normals[index * 3];
  24302. faceNormaly = normals[index * 3 + 1];
  24303. faceNormalz = normals[index * 3 + 2];
  24304. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24305. length = (length === 0) ? 1.0 : length;
  24306. faceNormalx /= length;
  24307. faceNormaly /= length;
  24308. faceNormalz /= length;
  24309. normals[index * 3] = faceNormalx;
  24310. normals[index * 3 + 1] = faceNormaly;
  24311. normals[index * 3 + 2] = faceNormalz;
  24312. }
  24313. };
  24314. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24315. var li = indices.length;
  24316. var ln = normals.length;
  24317. var i;
  24318. var n;
  24319. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24320. switch (sideOrientation) {
  24321. case BABYLON.Mesh.FRONTSIDE:
  24322. // nothing changed
  24323. break;
  24324. case BABYLON.Mesh.BACKSIDE:
  24325. var tmp;
  24326. // indices
  24327. for (i = 0; i < li; i += 3) {
  24328. tmp = indices[i];
  24329. indices[i] = indices[i + 2];
  24330. indices[i + 2] = tmp;
  24331. }
  24332. // normals
  24333. for (n = 0; n < ln; n++) {
  24334. normals[n] = -normals[n];
  24335. }
  24336. break;
  24337. case BABYLON.Mesh.DOUBLESIDE:
  24338. // positions
  24339. var lp = positions.length;
  24340. var l = lp / 3;
  24341. for (var p = 0; p < lp; p++) {
  24342. positions[lp + p] = positions[p];
  24343. }
  24344. // indices
  24345. for (i = 0; i < li; i += 3) {
  24346. indices[i + li] = indices[i + 2] + l;
  24347. indices[i + 1 + li] = indices[i + 1] + l;
  24348. indices[i + 2 + li] = indices[i] + l;
  24349. }
  24350. // normals
  24351. for (n = 0; n < ln; n++) {
  24352. normals[ln + n] = -normals[n];
  24353. }
  24354. // uvs
  24355. var lu = uvs.length;
  24356. for (var u = 0; u < lu; u++) {
  24357. uvs[u + lu] = uvs[u];
  24358. }
  24359. break;
  24360. }
  24361. };
  24362. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24363. var vertexData = new VertexData();
  24364. // positions
  24365. var positions = parsedVertexData.positions;
  24366. if (positions) {
  24367. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24368. }
  24369. // normals
  24370. var normals = parsedVertexData.normals;
  24371. if (normals) {
  24372. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24373. }
  24374. // uvs
  24375. var uvs = parsedVertexData.uvs;
  24376. if (uvs) {
  24377. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24378. }
  24379. // uv2s
  24380. var uv2s = parsedVertexData.uv2s;
  24381. if (uv2s) {
  24382. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24383. }
  24384. // uv3s
  24385. var uv3s = parsedVertexData.uv3s;
  24386. if (uv3s) {
  24387. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24388. }
  24389. // uv4s
  24390. var uv4s = parsedVertexData.uv4s;
  24391. if (uv4s) {
  24392. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24393. }
  24394. // uv5s
  24395. var uv5s = parsedVertexData.uv5s;
  24396. if (uv5s) {
  24397. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24398. }
  24399. // uv6s
  24400. var uv6s = parsedVertexData.uv6s;
  24401. if (uv6s) {
  24402. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24403. }
  24404. // colors
  24405. var colors = parsedVertexData.colors;
  24406. if (colors) {
  24407. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24408. }
  24409. // matricesIndices
  24410. var matricesIndices = parsedVertexData.matricesIndices;
  24411. if (matricesIndices) {
  24412. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24413. }
  24414. // matricesWeights
  24415. var matricesWeights = parsedVertexData.matricesWeights;
  24416. if (matricesWeights) {
  24417. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24418. }
  24419. // indices
  24420. var indices = parsedVertexData.indices;
  24421. if (indices) {
  24422. vertexData.indices = indices;
  24423. }
  24424. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24425. };
  24426. return VertexData;
  24427. })();
  24428. BABYLON.VertexData = VertexData;
  24429. })(BABYLON || (BABYLON = {}));
  24430. var BABYLON;
  24431. (function (BABYLON) {
  24432. var Tags = (function () {
  24433. function Tags() {
  24434. }
  24435. Tags.EnableFor = function (obj) {
  24436. obj._tags = obj._tags || {};
  24437. obj.hasTags = function () {
  24438. return Tags.HasTags(obj);
  24439. };
  24440. obj.addTags = function (tagsString) {
  24441. return Tags.AddTagsTo(obj, tagsString);
  24442. };
  24443. obj.removeTags = function (tagsString) {
  24444. return Tags.RemoveTagsFrom(obj, tagsString);
  24445. };
  24446. obj.matchesTagsQuery = function (tagsQuery) {
  24447. return Tags.MatchesQuery(obj, tagsQuery);
  24448. };
  24449. };
  24450. Tags.DisableFor = function (obj) {
  24451. delete obj._tags;
  24452. delete obj.hasTags;
  24453. delete obj.addTags;
  24454. delete obj.removeTags;
  24455. delete obj.matchesTagsQuery;
  24456. };
  24457. Tags.HasTags = function (obj) {
  24458. if (!obj._tags) {
  24459. return false;
  24460. }
  24461. return !BABYLON.Tools.IsEmpty(obj._tags);
  24462. };
  24463. Tags.GetTags = function (obj) {
  24464. if (!obj._tags) {
  24465. return null;
  24466. }
  24467. return obj._tags;
  24468. };
  24469. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24470. // a tag cannot start with '||', '&&', and '!'
  24471. // it cannot contain whitespaces
  24472. Tags.AddTagsTo = function (obj, tagsString) {
  24473. if (!tagsString) {
  24474. return;
  24475. }
  24476. if (typeof tagsString !== "string") {
  24477. return;
  24478. }
  24479. var tags = tagsString.split(" ");
  24480. for (var t in tags) {
  24481. Tags._AddTagTo(obj, tags[t]);
  24482. }
  24483. };
  24484. Tags._AddTagTo = function (obj, tag) {
  24485. tag = tag.trim();
  24486. if (tag === "" || tag === "true" || tag === "false") {
  24487. return;
  24488. }
  24489. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24490. return;
  24491. }
  24492. Tags.EnableFor(obj);
  24493. obj._tags[tag] = true;
  24494. };
  24495. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24496. if (!Tags.HasTags(obj)) {
  24497. return;
  24498. }
  24499. var tags = tagsString.split(" ");
  24500. for (var t in tags) {
  24501. Tags._RemoveTagFrom(obj, tags[t]);
  24502. }
  24503. };
  24504. Tags._RemoveTagFrom = function (obj, tag) {
  24505. delete obj._tags[tag];
  24506. };
  24507. Tags.MatchesQuery = function (obj, tagsQuery) {
  24508. if (tagsQuery === undefined) {
  24509. return true;
  24510. }
  24511. if (tagsQuery === "") {
  24512. return Tags.HasTags(obj);
  24513. }
  24514. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24515. };
  24516. return Tags;
  24517. })();
  24518. BABYLON.Tags = Tags;
  24519. })(BABYLON || (BABYLON = {}));
  24520. var BABYLON;
  24521. (function (BABYLON) {
  24522. var Internals;
  24523. (function (Internals) {
  24524. var AndOrNotEvaluator = (function () {
  24525. function AndOrNotEvaluator() {
  24526. }
  24527. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24528. if (!query.match(/\([^\(\)]*\)/g)) {
  24529. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24530. }
  24531. else {
  24532. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24533. // remove parenthesis
  24534. r = r.slice(1, r.length - 1);
  24535. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24536. });
  24537. }
  24538. if (query === "true") {
  24539. return true;
  24540. }
  24541. if (query === "false") {
  24542. return false;
  24543. }
  24544. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24545. };
  24546. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24547. evaluateCallback = evaluateCallback || (function (r) {
  24548. return r === "true" ? true : false;
  24549. });
  24550. var result;
  24551. var or = parenthesisContent.split("||");
  24552. for (var i in or) {
  24553. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24554. var and = ori.split("&&");
  24555. if (and.length > 1) {
  24556. for (var j = 0; j < and.length; ++j) {
  24557. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24558. if (andj !== "true" && andj !== "false") {
  24559. if (andj[0] === "!") {
  24560. result = !evaluateCallback(andj.substring(1));
  24561. }
  24562. else {
  24563. result = evaluateCallback(andj);
  24564. }
  24565. }
  24566. else {
  24567. result = andj === "true" ? true : false;
  24568. }
  24569. if (!result) {
  24570. ori = "false";
  24571. break;
  24572. }
  24573. }
  24574. }
  24575. if (result || ori === "true") {
  24576. result = true;
  24577. break;
  24578. }
  24579. // result equals false (or undefined)
  24580. if (ori !== "true" && ori !== "false") {
  24581. if (ori[0] === "!") {
  24582. result = !evaluateCallback(ori.substring(1));
  24583. }
  24584. else {
  24585. result = evaluateCallback(ori);
  24586. }
  24587. }
  24588. else {
  24589. result = ori === "true" ? true : false;
  24590. }
  24591. }
  24592. // the whole parenthesis scope is replaced by 'true' or 'false'
  24593. return result ? "true" : "false";
  24594. };
  24595. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24596. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24597. // remove whitespaces
  24598. r = r.replace(/[\s]/g, function () { return ""; });
  24599. return r.length % 2 ? "!" : "";
  24600. });
  24601. booleanString = booleanString.trim();
  24602. if (booleanString === "!true") {
  24603. booleanString = "false";
  24604. }
  24605. else if (booleanString === "!false") {
  24606. booleanString = "true";
  24607. }
  24608. return booleanString;
  24609. };
  24610. return AndOrNotEvaluator;
  24611. })();
  24612. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24613. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24614. })(BABYLON || (BABYLON = {}));
  24615. var BABYLON;
  24616. (function (BABYLON) {
  24617. var PostProcessRenderPass = (function () {
  24618. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24619. this._enabled = true;
  24620. this._refCount = 0;
  24621. this._name = name;
  24622. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24623. this.setRenderList(renderList);
  24624. this._renderTexture.onBeforeRender = beforeRender;
  24625. this._renderTexture.onAfterRender = afterRender;
  24626. this._scene = scene;
  24627. this._renderList = renderList;
  24628. }
  24629. // private
  24630. PostProcessRenderPass.prototype._incRefCount = function () {
  24631. if (this._refCount === 0) {
  24632. this._scene.customRenderTargets.push(this._renderTexture);
  24633. }
  24634. return ++this._refCount;
  24635. };
  24636. PostProcessRenderPass.prototype._decRefCount = function () {
  24637. this._refCount--;
  24638. if (this._refCount <= 0) {
  24639. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24640. }
  24641. return this._refCount;
  24642. };
  24643. PostProcessRenderPass.prototype._update = function () {
  24644. this.setRenderList(this._renderList);
  24645. };
  24646. // public
  24647. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24648. this._renderTexture.renderList = renderList;
  24649. };
  24650. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24651. return this._renderTexture;
  24652. };
  24653. return PostProcessRenderPass;
  24654. })();
  24655. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24656. })(BABYLON || (BABYLON = {}));
  24657. var BABYLON;
  24658. (function (BABYLON) {
  24659. var PostProcessRenderEffect = (function () {
  24660. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24661. this._engine = engine;
  24662. this._name = name;
  24663. this._singleInstance = singleInstance || true;
  24664. this._getPostProcess = getPostProcess;
  24665. this._cameras = [];
  24666. this._indicesForCamera = [];
  24667. this._postProcesses = {};
  24668. this._renderPasses = {};
  24669. this._renderEffectAsPasses = {};
  24670. }
  24671. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24672. get: function () {
  24673. for (var index in this._postProcesses) {
  24674. if (!this._postProcesses[index].isSupported) {
  24675. return false;
  24676. }
  24677. }
  24678. return true;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. PostProcessRenderEffect.prototype._update = function () {
  24684. for (var renderPassName in this._renderPasses) {
  24685. this._renderPasses[renderPassName]._update();
  24686. }
  24687. };
  24688. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24689. this._renderPasses[renderPass._name] = renderPass;
  24690. this._linkParameters();
  24691. };
  24692. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24693. delete this._renderPasses[renderPass._name];
  24694. this._linkParameters();
  24695. };
  24696. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24697. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24698. this._linkParameters();
  24699. };
  24700. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24701. for (var renderPassName in this._renderPasses) {
  24702. if (renderPassName === passName) {
  24703. return this._renderPasses[passName];
  24704. }
  24705. }
  24706. };
  24707. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24708. this._renderPasses = {};
  24709. this._linkParameters();
  24710. };
  24711. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24712. var cameraKey;
  24713. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24714. for (var i = 0; i < _cam.length; i++) {
  24715. var camera = _cam[i];
  24716. var cameraName = camera.name;
  24717. if (this._singleInstance) {
  24718. cameraKey = 0;
  24719. }
  24720. else {
  24721. cameraKey = cameraName;
  24722. }
  24723. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24724. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24725. if (!this._indicesForCamera[cameraName]) {
  24726. this._indicesForCamera[cameraName] = [];
  24727. }
  24728. this._indicesForCamera[cameraName].push(index);
  24729. if (this._cameras.indexOf(camera) === -1) {
  24730. this._cameras[cameraName] = camera;
  24731. }
  24732. for (var passName in this._renderPasses) {
  24733. this._renderPasses[passName]._incRefCount();
  24734. }
  24735. }
  24736. this._linkParameters();
  24737. };
  24738. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24739. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24740. for (var i = 0; i < _cam.length; i++) {
  24741. var camera = _cam[i];
  24742. var cameraName = camera.name;
  24743. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24744. var index = this._cameras.indexOf(cameraName);
  24745. this._indicesForCamera.splice(index, 1);
  24746. this._cameras.splice(index, 1);
  24747. for (var passName in this._renderPasses) {
  24748. this._renderPasses[passName]._decRefCount();
  24749. }
  24750. }
  24751. };
  24752. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24753. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24754. for (var i = 0; i < _cam.length; i++) {
  24755. var camera = _cam[i];
  24756. var cameraName = camera.name;
  24757. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24758. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24759. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24760. }
  24761. }
  24762. for (var passName in this._renderPasses) {
  24763. this._renderPasses[passName]._incRefCount();
  24764. }
  24765. }
  24766. };
  24767. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24768. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24769. for (var i = 0; i < _cam.length; i++) {
  24770. var camera = _cam[i];
  24771. var cameraName = camera.Name;
  24772. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24773. for (var passName in this._renderPasses) {
  24774. this._renderPasses[passName]._decRefCount();
  24775. }
  24776. }
  24777. };
  24778. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24779. if (this._singleInstance) {
  24780. return this._postProcesses[0];
  24781. }
  24782. else {
  24783. return this._postProcesses[camera.name];
  24784. }
  24785. };
  24786. PostProcessRenderEffect.prototype._linkParameters = function () {
  24787. var _this = this;
  24788. for (var index in this._postProcesses) {
  24789. if (this.applyParameters) {
  24790. this.applyParameters(this._postProcesses[index]);
  24791. }
  24792. this._postProcesses[index].onBeforeRender = function (effect) {
  24793. _this._linkTextures(effect);
  24794. };
  24795. }
  24796. };
  24797. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24798. for (var renderPassName in this._renderPasses) {
  24799. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24800. }
  24801. for (var renderEffectName in this._renderEffectAsPasses) {
  24802. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24803. }
  24804. };
  24805. return PostProcessRenderEffect;
  24806. })();
  24807. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24808. })(BABYLON || (BABYLON = {}));
  24809. var BABYLON;
  24810. (function (BABYLON) {
  24811. var PostProcessRenderPipeline = (function () {
  24812. function PostProcessRenderPipeline(engine, name) {
  24813. this._engine = engine;
  24814. this._name = name;
  24815. this._renderEffects = {};
  24816. this._renderEffectsForIsolatedPass = {};
  24817. this._cameras = [];
  24818. }
  24819. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24820. get: function () {
  24821. for (var renderEffectName in this._renderEffects) {
  24822. if (!this._renderEffects[renderEffectName].isSupported) {
  24823. return false;
  24824. }
  24825. }
  24826. return true;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24832. this._renderEffects[renderEffect._name] = renderEffect;
  24833. };
  24834. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24835. var renderEffects = this._renderEffects[renderEffectName];
  24836. if (!renderEffects) {
  24837. return;
  24838. }
  24839. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24840. };
  24841. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24842. var renderEffects = this._renderEffects[renderEffectName];
  24843. if (!renderEffects) {
  24844. return;
  24845. }
  24846. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24847. };
  24848. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24849. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24850. var indicesToDelete = [];
  24851. var i;
  24852. for (i = 0; i < _cam.length; i++) {
  24853. var camera = _cam[i];
  24854. var cameraName = camera.name;
  24855. if (this._cameras.indexOf(camera) === -1) {
  24856. this._cameras[cameraName] = camera;
  24857. }
  24858. else if (unique) {
  24859. indicesToDelete.push(i);
  24860. }
  24861. }
  24862. for (i = 0; i < indicesToDelete.length; i++) {
  24863. cameras.splice(indicesToDelete[i], 1);
  24864. }
  24865. for (var renderEffectName in this._renderEffects) {
  24866. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24867. }
  24868. };
  24869. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24870. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24871. for (var renderEffectName in this._renderEffects) {
  24872. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24873. }
  24874. for (var i = 0; i < _cam.length; i++) {
  24875. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24876. }
  24877. };
  24878. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24879. var _this = this;
  24880. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24881. var pass = null;
  24882. var renderEffectName;
  24883. for (renderEffectName in this._renderEffects) {
  24884. pass = this._renderEffects[renderEffectName].getPass(passName);
  24885. if (pass != null) {
  24886. break;
  24887. }
  24888. }
  24889. if (pass === null) {
  24890. return;
  24891. }
  24892. for (renderEffectName in this._renderEffects) {
  24893. this._renderEffects[renderEffectName]._disable(_cam);
  24894. }
  24895. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24896. for (var i = 0; i < _cam.length; i++) {
  24897. var camera = _cam[i];
  24898. var cameraName = camera.name;
  24899. 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); });
  24900. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24901. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24902. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24903. }
  24904. };
  24905. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24906. var _this = this;
  24907. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24908. for (var i = 0; i < _cam.length; i++) {
  24909. var camera = _cam[i];
  24910. var cameraName = camera.name;
  24911. 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); });
  24912. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24913. }
  24914. for (var renderEffectName in this._renderEffects) {
  24915. this._renderEffects[renderEffectName]._enable(_cam);
  24916. }
  24917. };
  24918. PostProcessRenderPipeline.prototype._update = function () {
  24919. for (var renderEffectName in this._renderEffects) {
  24920. this._renderEffects[renderEffectName]._update();
  24921. }
  24922. for (var i = 0; i < this._cameras.length; i++) {
  24923. var cameraName = this._cameras[i].name;
  24924. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24925. this._renderEffectsForIsolatedPass[cameraName]._update();
  24926. }
  24927. }
  24928. };
  24929. PostProcessRenderPipeline.prototype.dispose = function () {
  24930. // Must be implemented by children
  24931. };
  24932. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24933. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24934. return PostProcessRenderPipeline;
  24935. })();
  24936. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24937. })(BABYLON || (BABYLON = {}));
  24938. var BABYLON;
  24939. (function (BABYLON) {
  24940. var PostProcessRenderPipelineManager = (function () {
  24941. function PostProcessRenderPipelineManager() {
  24942. this._renderPipelines = {};
  24943. }
  24944. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24945. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24946. };
  24947. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24948. var renderPipeline = this._renderPipelines[renderPipelineName];
  24949. if (!renderPipeline) {
  24950. return;
  24951. }
  24952. renderPipeline._attachCameras(cameras, unique);
  24953. };
  24954. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24955. var renderPipeline = this._renderPipelines[renderPipelineName];
  24956. if (!renderPipeline) {
  24957. return;
  24958. }
  24959. renderPipeline._detachCameras(cameras);
  24960. };
  24961. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24962. var renderPipeline = this._renderPipelines[renderPipelineName];
  24963. if (!renderPipeline) {
  24964. return;
  24965. }
  24966. renderPipeline._enableEffect(renderEffectName, cameras);
  24967. };
  24968. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24969. var renderPipeline = this._renderPipelines[renderPipelineName];
  24970. if (!renderPipeline) {
  24971. return;
  24972. }
  24973. renderPipeline._disableEffect(renderEffectName, cameras);
  24974. };
  24975. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24976. var renderPipeline = this._renderPipelines[renderPipelineName];
  24977. if (!renderPipeline) {
  24978. return;
  24979. }
  24980. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24981. };
  24982. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24983. var renderPipeline = this._renderPipelines[renderPipelineName];
  24984. if (!renderPipeline) {
  24985. return;
  24986. }
  24987. renderPipeline._disableDisplayOnlyPass(cameras);
  24988. };
  24989. PostProcessRenderPipelineManager.prototype.update = function () {
  24990. for (var renderPipelineName in this._renderPipelines) {
  24991. var pipeline = this._renderPipelines[renderPipelineName];
  24992. if (!pipeline.isSupported) {
  24993. pipeline.dispose();
  24994. delete this._renderPipelines[renderPipelineName];
  24995. }
  24996. else {
  24997. pipeline._update();
  24998. }
  24999. }
  25000. };
  25001. return PostProcessRenderPipelineManager;
  25002. })();
  25003. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25004. })(BABYLON || (BABYLON = {}));
  25005. var BABYLON;
  25006. (function (BABYLON) {
  25007. var BoundingBoxRenderer = (function () {
  25008. function BoundingBoxRenderer(scene) {
  25009. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25010. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25011. this.showBackLines = true;
  25012. this.renderList = new BABYLON.SmartArray(32);
  25013. this._scene = scene;
  25014. }
  25015. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25016. if (this._colorShader) {
  25017. return;
  25018. }
  25019. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25020. attributes: ["position"],
  25021. uniforms: ["worldViewProjection", "color"]
  25022. });
  25023. var engine = this._scene.getEngine();
  25024. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25025. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25026. 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]);
  25027. };
  25028. BoundingBoxRenderer.prototype.reset = function () {
  25029. this.renderList.reset();
  25030. };
  25031. BoundingBoxRenderer.prototype.render = function () {
  25032. if (this.renderList.length === 0) {
  25033. return;
  25034. }
  25035. this._prepareRessources();
  25036. if (!this._colorShader.isReady()) {
  25037. return;
  25038. }
  25039. var engine = this._scene.getEngine();
  25040. engine.setDepthWrite(false);
  25041. this._colorShader._preBind();
  25042. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25043. var boundingBox = this.renderList.data[boundingBoxIndex];
  25044. var min = boundingBox.minimum;
  25045. var max = boundingBox.maximum;
  25046. var diff = max.subtract(min);
  25047. var median = min.add(diff.scale(0.5));
  25048. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25049. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25050. .multiply(boundingBox.getWorldMatrix());
  25051. // VBOs
  25052. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25053. if (this.showBackLines) {
  25054. // Back
  25055. engine.setDepthFunctionToGreaterOrEqual();
  25056. this._scene.resetCachedMaterial();
  25057. this._colorShader.setColor4("color", this.backColor.toColor4());
  25058. this._colorShader.bind(worldMatrix);
  25059. // Draw order
  25060. engine.draw(false, 0, 24);
  25061. }
  25062. // Front
  25063. engine.setDepthFunctionToLess();
  25064. this._scene.resetCachedMaterial();
  25065. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25066. this._colorShader.bind(worldMatrix);
  25067. // Draw order
  25068. engine.draw(false, 0, 24);
  25069. }
  25070. this._colorShader.unbind();
  25071. engine.setDepthFunctionToLessOrEqual();
  25072. engine.setDepthWrite(true);
  25073. };
  25074. BoundingBoxRenderer.prototype.dispose = function () {
  25075. if (!this._colorShader) {
  25076. return;
  25077. }
  25078. this._colorShader.dispose();
  25079. this._vb.dispose();
  25080. this._scene.getEngine()._releaseBuffer(this._ib);
  25081. };
  25082. return BoundingBoxRenderer;
  25083. })();
  25084. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25085. })(BABYLON || (BABYLON = {}));
  25086. var BABYLON;
  25087. (function (BABYLON) {
  25088. var Condition = (function () {
  25089. function Condition(actionManager) {
  25090. this._actionManager = actionManager;
  25091. }
  25092. Condition.prototype.isValid = function () {
  25093. return true;
  25094. };
  25095. Condition.prototype._getProperty = function (propertyPath) {
  25096. return this._actionManager._getProperty(propertyPath);
  25097. };
  25098. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25099. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25100. };
  25101. return Condition;
  25102. })();
  25103. BABYLON.Condition = Condition;
  25104. var ValueCondition = (function (_super) {
  25105. __extends(ValueCondition, _super);
  25106. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25107. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25108. _super.call(this, actionManager);
  25109. this.propertyPath = propertyPath;
  25110. this.value = value;
  25111. this.operator = operator;
  25112. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25113. this._property = this._getProperty(this.propertyPath);
  25114. }
  25115. Object.defineProperty(ValueCondition, "IsEqual", {
  25116. get: function () {
  25117. return ValueCondition._IsEqual;
  25118. },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. Object.defineProperty(ValueCondition, "IsDifferent", {
  25123. get: function () {
  25124. return ValueCondition._IsDifferent;
  25125. },
  25126. enumerable: true,
  25127. configurable: true
  25128. });
  25129. Object.defineProperty(ValueCondition, "IsGreater", {
  25130. get: function () {
  25131. return ValueCondition._IsGreater;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. Object.defineProperty(ValueCondition, "IsLesser", {
  25137. get: function () {
  25138. return ValueCondition._IsLesser;
  25139. },
  25140. enumerable: true,
  25141. configurable: true
  25142. });
  25143. // Methods
  25144. ValueCondition.prototype.isValid = function () {
  25145. switch (this.operator) {
  25146. case ValueCondition.IsGreater:
  25147. return this._target[this._property] > this.value;
  25148. case ValueCondition.IsLesser:
  25149. return this._target[this._property] < this.value;
  25150. case ValueCondition.IsEqual:
  25151. case ValueCondition.IsDifferent:
  25152. var check;
  25153. if (this.value.equals) {
  25154. check = this.value.equals(this._target[this._property]);
  25155. }
  25156. else {
  25157. check = this.value === this._target[this._property];
  25158. }
  25159. return this.operator === ValueCondition.IsEqual ? check : !check;
  25160. }
  25161. return false;
  25162. };
  25163. // Statics
  25164. ValueCondition._IsEqual = 0;
  25165. ValueCondition._IsDifferent = 1;
  25166. ValueCondition._IsGreater = 2;
  25167. ValueCondition._IsLesser = 3;
  25168. return ValueCondition;
  25169. })(Condition);
  25170. BABYLON.ValueCondition = ValueCondition;
  25171. var PredicateCondition = (function (_super) {
  25172. __extends(PredicateCondition, _super);
  25173. function PredicateCondition(actionManager, predicate) {
  25174. _super.call(this, actionManager);
  25175. this.predicate = predicate;
  25176. }
  25177. PredicateCondition.prototype.isValid = function () {
  25178. return this.predicate();
  25179. };
  25180. return PredicateCondition;
  25181. })(Condition);
  25182. BABYLON.PredicateCondition = PredicateCondition;
  25183. var StateCondition = (function (_super) {
  25184. __extends(StateCondition, _super);
  25185. function StateCondition(actionManager, target, value) {
  25186. _super.call(this, actionManager);
  25187. this.value = value;
  25188. this._target = target;
  25189. }
  25190. // Methods
  25191. StateCondition.prototype.isValid = function () {
  25192. return this._target.state === this.value;
  25193. };
  25194. return StateCondition;
  25195. })(Condition);
  25196. BABYLON.StateCondition = StateCondition;
  25197. })(BABYLON || (BABYLON = {}));
  25198. var BABYLON;
  25199. (function (BABYLON) {
  25200. var Action = (function () {
  25201. function Action(triggerOptions, condition) {
  25202. this.triggerOptions = triggerOptions;
  25203. if (triggerOptions.parameter) {
  25204. this.trigger = triggerOptions.trigger;
  25205. this._triggerParameter = triggerOptions.parameter;
  25206. }
  25207. else {
  25208. this.trigger = triggerOptions;
  25209. }
  25210. this._nextActiveAction = this;
  25211. this._condition = condition;
  25212. }
  25213. // Methods
  25214. Action.prototype._prepare = function () {
  25215. };
  25216. Action.prototype.getTriggerParameter = function () {
  25217. return this._triggerParameter;
  25218. };
  25219. Action.prototype._executeCurrent = function (evt) {
  25220. if (this._nextActiveAction._condition) {
  25221. var condition = this._nextActiveAction._condition;
  25222. var currentRenderId = this._actionManager.getScene().getRenderId();
  25223. // We cache the current evaluation for the current frame
  25224. if (condition._evaluationId === currentRenderId) {
  25225. if (!condition._currentResult) {
  25226. return;
  25227. }
  25228. }
  25229. else {
  25230. condition._evaluationId = currentRenderId;
  25231. if (!condition.isValid()) {
  25232. condition._currentResult = false;
  25233. return;
  25234. }
  25235. condition._currentResult = true;
  25236. }
  25237. }
  25238. this._nextActiveAction.execute(evt);
  25239. if (this._nextActiveAction._child) {
  25240. if (!this._nextActiveAction._child._actionManager) {
  25241. this._nextActiveAction._child._actionManager = this._actionManager;
  25242. }
  25243. this._nextActiveAction = this._nextActiveAction._child;
  25244. }
  25245. else {
  25246. this._nextActiveAction = this;
  25247. }
  25248. };
  25249. Action.prototype.execute = function (evt) {
  25250. };
  25251. Action.prototype.then = function (action) {
  25252. this._child = action;
  25253. action._actionManager = this._actionManager;
  25254. action._prepare();
  25255. return action;
  25256. };
  25257. Action.prototype._getProperty = function (propertyPath) {
  25258. return this._actionManager._getProperty(propertyPath);
  25259. };
  25260. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25261. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25262. };
  25263. return Action;
  25264. })();
  25265. BABYLON.Action = Action;
  25266. })(BABYLON || (BABYLON = {}));
  25267. var BABYLON;
  25268. (function (BABYLON) {
  25269. /**
  25270. * ActionEvent is the event beint sent when an action is triggered.
  25271. */
  25272. var ActionEvent = (function () {
  25273. /**
  25274. * @constructor
  25275. * @param source The mesh or sprite that triggered the action.
  25276. * @param pointerX The X mouse cursor position at the time of the event
  25277. * @param pointerY The Y mouse cursor position at the time of the event
  25278. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25279. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25280. */
  25281. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25282. this.source = source;
  25283. this.pointerX = pointerX;
  25284. this.pointerY = pointerY;
  25285. this.meshUnderPointer = meshUnderPointer;
  25286. this.sourceEvent = sourceEvent;
  25287. this.additionalData = additionalData;
  25288. }
  25289. /**
  25290. * Helper function to auto-create an ActionEvent from a source mesh.
  25291. * @param source The source mesh that triggered the event
  25292. * @param evt {Event} The original (browser) event
  25293. */
  25294. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25295. var scene = source.getScene();
  25296. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25297. };
  25298. /**
  25299. * Helper function to auto-create an ActionEvent from a source mesh.
  25300. * @param source The source sprite that triggered the event
  25301. * @param scene Scene associated with the sprite
  25302. * @param evt {Event} The original (browser) event
  25303. */
  25304. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25305. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25306. };
  25307. /**
  25308. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25309. * @param scene the scene where the event occurred
  25310. * @param evt {Event} The original (browser) event
  25311. */
  25312. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25313. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25314. };
  25315. return ActionEvent;
  25316. })();
  25317. BABYLON.ActionEvent = ActionEvent;
  25318. /**
  25319. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25320. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25321. */
  25322. var ActionManager = (function () {
  25323. function ActionManager(scene) {
  25324. // Members
  25325. this.actions = new Array();
  25326. this._scene = scene;
  25327. scene._actionManagers.push(this);
  25328. }
  25329. Object.defineProperty(ActionManager, "NothingTrigger", {
  25330. get: function () {
  25331. return ActionManager._NothingTrigger;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25337. get: function () {
  25338. return ActionManager._OnPickTrigger;
  25339. },
  25340. enumerable: true,
  25341. configurable: true
  25342. });
  25343. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25344. get: function () {
  25345. return ActionManager._OnLeftPickTrigger;
  25346. },
  25347. enumerable: true,
  25348. configurable: true
  25349. });
  25350. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25351. get: function () {
  25352. return ActionManager._OnRightPickTrigger;
  25353. },
  25354. enumerable: true,
  25355. configurable: true
  25356. });
  25357. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25358. get: function () {
  25359. return ActionManager._OnCenterPickTrigger;
  25360. },
  25361. enumerable: true,
  25362. configurable: true
  25363. });
  25364. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25365. get: function () {
  25366. return ActionManager._OnPointerOverTrigger;
  25367. },
  25368. enumerable: true,
  25369. configurable: true
  25370. });
  25371. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25372. get: function () {
  25373. return ActionManager._OnPointerOutTrigger;
  25374. },
  25375. enumerable: true,
  25376. configurable: true
  25377. });
  25378. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25379. get: function () {
  25380. return ActionManager._OnEveryFrameTrigger;
  25381. },
  25382. enumerable: true,
  25383. configurable: true
  25384. });
  25385. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25386. get: function () {
  25387. return ActionManager._OnIntersectionEnterTrigger;
  25388. },
  25389. enumerable: true,
  25390. configurable: true
  25391. });
  25392. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25393. get: function () {
  25394. return ActionManager._OnIntersectionExitTrigger;
  25395. },
  25396. enumerable: true,
  25397. configurable: true
  25398. });
  25399. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25400. get: function () {
  25401. return ActionManager._OnKeyDownTrigger;
  25402. },
  25403. enumerable: true,
  25404. configurable: true
  25405. });
  25406. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25407. get: function () {
  25408. return ActionManager._OnKeyUpTrigger;
  25409. },
  25410. enumerable: true,
  25411. configurable: true
  25412. });
  25413. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25414. get: function () {
  25415. return ActionManager._OnPickUpTrigger;
  25416. },
  25417. enumerable: true,
  25418. configurable: true
  25419. });
  25420. // Methods
  25421. ActionManager.prototype.dispose = function () {
  25422. var index = this._scene._actionManagers.indexOf(this);
  25423. if (index > -1) {
  25424. this._scene._actionManagers.splice(index, 1);
  25425. }
  25426. };
  25427. ActionManager.prototype.getScene = function () {
  25428. return this._scene;
  25429. };
  25430. /**
  25431. * Does this action manager handles actions of any of the given triggers
  25432. * @param {number[]} triggers - the triggers to be tested
  25433. * @return {boolean} whether one (or more) of the triggers is handeled
  25434. */
  25435. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25436. for (var index = 0; index < this.actions.length; index++) {
  25437. var action = this.actions[index];
  25438. if (triggers.indexOf(action.trigger) > -1) {
  25439. return true;
  25440. }
  25441. }
  25442. return false;
  25443. };
  25444. /**
  25445. * Does this action manager handles actions of a given trigger
  25446. * @param {number} trigger - the trigger to be tested
  25447. * @return {boolean} whether the trigger is handeled
  25448. */
  25449. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25450. for (var index = 0; index < this.actions.length; index++) {
  25451. var action = this.actions[index];
  25452. if (action.trigger === trigger) {
  25453. return true;
  25454. }
  25455. }
  25456. return false;
  25457. };
  25458. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25459. /**
  25460. * Does this action manager has pointer triggers
  25461. * @return {boolean} whether or not it has pointer triggers
  25462. */
  25463. get: function () {
  25464. for (var index = 0; index < this.actions.length; index++) {
  25465. var action = this.actions[index];
  25466. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25467. return true;
  25468. }
  25469. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25470. return true;
  25471. }
  25472. }
  25473. return false;
  25474. },
  25475. enumerable: true,
  25476. configurable: true
  25477. });
  25478. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25479. /**
  25480. * Does this action manager has pick triggers
  25481. * @return {boolean} whether or not it has pick triggers
  25482. */
  25483. get: function () {
  25484. for (var index = 0; index < this.actions.length; index++) {
  25485. var action = this.actions[index];
  25486. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25487. return true;
  25488. }
  25489. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25490. return true;
  25491. }
  25492. }
  25493. return false;
  25494. },
  25495. enumerable: true,
  25496. configurable: true
  25497. });
  25498. /**
  25499. * Registers an action to this action manager
  25500. * @param {BABYLON.Action} action - the action to be registered
  25501. * @return {BABYLON.Action} the action amended (prepared) after registration
  25502. */
  25503. ActionManager.prototype.registerAction = function (action) {
  25504. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25505. if (this.getScene().actionManager !== this) {
  25506. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25507. return null;
  25508. }
  25509. }
  25510. this.actions.push(action);
  25511. action._actionManager = this;
  25512. action._prepare();
  25513. return action;
  25514. };
  25515. /**
  25516. * Process a specific trigger
  25517. * @param {number} trigger - the trigger to process
  25518. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25519. */
  25520. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25521. for (var index = 0; index < this.actions.length; index++) {
  25522. var action = this.actions[index];
  25523. if (action.trigger === trigger) {
  25524. if (trigger === ActionManager.OnKeyUpTrigger
  25525. || trigger === ActionManager.OnKeyDownTrigger) {
  25526. var parameter = action.getTriggerParameter();
  25527. if (parameter) {
  25528. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25529. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25530. if (actualkey !== parameter.toLowerCase()) {
  25531. continue;
  25532. }
  25533. }
  25534. }
  25535. action._executeCurrent(evt);
  25536. }
  25537. }
  25538. };
  25539. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25540. var properties = propertyPath.split(".");
  25541. for (var index = 0; index < properties.length - 1; index++) {
  25542. target = target[properties[index]];
  25543. }
  25544. return target;
  25545. };
  25546. ActionManager.prototype._getProperty = function (propertyPath) {
  25547. var properties = propertyPath.split(".");
  25548. return properties[properties.length - 1];
  25549. };
  25550. ActionManager.Parse = function (parsedActions, object, scene) {
  25551. var actionManager = new BABYLON.ActionManager(scene);
  25552. if (object === null)
  25553. scene.actionManager = actionManager;
  25554. else
  25555. object.actionManager = actionManager;
  25556. // instanciate a new object
  25557. var instanciate = function (name, params) {
  25558. var newInstance = Object.create(BABYLON[name].prototype);
  25559. newInstance.constructor.apply(newInstance, params);
  25560. return newInstance;
  25561. };
  25562. var parseParameter = function (name, value, target, propertyPath) {
  25563. if (propertyPath === null) {
  25564. // String, boolean or float
  25565. var floatValue = parseFloat(value);
  25566. if (value === "true" || value === "false")
  25567. return value === "true";
  25568. else
  25569. return isNaN(floatValue) ? value : floatValue;
  25570. }
  25571. var effectiveTarget = propertyPath.split(".");
  25572. var values = value.split(",");
  25573. // Get effective Target
  25574. for (var i = 0; i < effectiveTarget.length; i++) {
  25575. target = target[effectiveTarget[i]];
  25576. }
  25577. // Return appropriate value with its type
  25578. if (typeof (target) === "boolean")
  25579. return values[0] === "true";
  25580. if (typeof (target) === "string")
  25581. return values[0];
  25582. // Parameters with multiple values such as Vector3 etc.
  25583. var split = new Array();
  25584. for (var i = 0; i < values.length; i++)
  25585. split.push(parseFloat(values[i]));
  25586. if (target instanceof BABYLON.Vector3)
  25587. return BABYLON.Vector3.FromArray(split);
  25588. if (target instanceof BABYLON.Vector4)
  25589. return BABYLON.Vector4.FromArray(split);
  25590. if (target instanceof BABYLON.Color3)
  25591. return BABYLON.Color3.FromArray(split);
  25592. if (target instanceof BABYLON.Color4)
  25593. return BABYLON.Color4.FromArray(split);
  25594. return parseFloat(values[0]);
  25595. };
  25596. // traverse graph per trigger
  25597. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  25598. if (combineArray === void 0) { combineArray = null; }
  25599. if (parsedAction.detached)
  25600. return;
  25601. var parameters = new Array();
  25602. var target = null;
  25603. var propertyPath = null;
  25604. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  25605. // Parameters
  25606. if (parsedAction.type === 2)
  25607. parameters.push(actionManager);
  25608. else
  25609. parameters.push(trigger);
  25610. if (combine) {
  25611. var actions = new Array();
  25612. for (var j = 0; j < parsedAction.combine.length; j++) {
  25613. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  25614. }
  25615. parameters.push(actions);
  25616. }
  25617. else {
  25618. for (var i = 0; i < parsedAction.properties.length; i++) {
  25619. var value = parsedAction.properties[i].value;
  25620. var name = parsedAction.properties[i].name;
  25621. var targetType = parsedAction.properties[i].targetType;
  25622. if (name === "target")
  25623. if (targetType !== null && targetType === "SceneProperties")
  25624. value = target = scene;
  25625. else
  25626. value = target = scene.getNodeByName(value);
  25627. else if (name === "parent")
  25628. value = scene.getNodeByName(value);
  25629. else if (name === "sound")
  25630. value = scene.getSoundByName(value);
  25631. else if (name !== "propertyPath") {
  25632. if (parsedAction.type === 2 && name === "operator")
  25633. value = BABYLON.ValueCondition[value];
  25634. else
  25635. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  25636. }
  25637. else {
  25638. propertyPath = value;
  25639. }
  25640. parameters.push(value);
  25641. }
  25642. }
  25643. if (combineArray === null) {
  25644. parameters.push(condition);
  25645. }
  25646. else {
  25647. parameters.push(null);
  25648. }
  25649. // If interpolate value action
  25650. if (parsedAction.name === "InterpolateValueAction") {
  25651. var param = parameters[parameters.length - 2];
  25652. parameters[parameters.length - 1] = param;
  25653. parameters[parameters.length - 2] = condition;
  25654. }
  25655. // Action or condition(s) and not CombineAction
  25656. var newAction = instanciate(parsedAction.name, parameters);
  25657. if (newAction instanceof BABYLON.Condition && condition !== null) {
  25658. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  25659. if (action)
  25660. action.then(nothing);
  25661. else
  25662. actionManager.registerAction(nothing);
  25663. action = nothing;
  25664. }
  25665. if (combineArray === null) {
  25666. if (newAction instanceof BABYLON.Condition) {
  25667. condition = newAction;
  25668. newAction = action;
  25669. }
  25670. else {
  25671. condition = null;
  25672. if (action)
  25673. action.then(newAction);
  25674. else
  25675. actionManager.registerAction(newAction);
  25676. }
  25677. }
  25678. else {
  25679. combineArray.push(newAction);
  25680. }
  25681. for (var i = 0; i < parsedAction.children.length; i++)
  25682. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  25683. };
  25684. // triggers
  25685. for (var i = 0; i < parsedActions.children.length; i++) {
  25686. var triggerParams;
  25687. var trigger = parsedActions.children[i];
  25688. if (trigger.properties.length > 0) {
  25689. var param = trigger.properties[0].value;
  25690. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  25691. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  25692. }
  25693. else
  25694. triggerParams = BABYLON.ActionManager[trigger.name];
  25695. for (var j = 0; j < trigger.children.length; j++) {
  25696. if (!trigger.detached)
  25697. traverse(trigger.children[j], triggerParams, null, null);
  25698. }
  25699. }
  25700. };
  25701. // Statics
  25702. ActionManager._NothingTrigger = 0;
  25703. ActionManager._OnPickTrigger = 1;
  25704. ActionManager._OnLeftPickTrigger = 2;
  25705. ActionManager._OnRightPickTrigger = 3;
  25706. ActionManager._OnCenterPickTrigger = 4;
  25707. ActionManager._OnPointerOverTrigger = 5;
  25708. ActionManager._OnPointerOutTrigger = 6;
  25709. ActionManager._OnEveryFrameTrigger = 7;
  25710. ActionManager._OnIntersectionEnterTrigger = 8;
  25711. ActionManager._OnIntersectionExitTrigger = 9;
  25712. ActionManager._OnKeyDownTrigger = 10;
  25713. ActionManager._OnKeyUpTrigger = 11;
  25714. ActionManager._OnPickUpTrigger = 12;
  25715. return ActionManager;
  25716. })();
  25717. BABYLON.ActionManager = ActionManager;
  25718. })(BABYLON || (BABYLON = {}));
  25719. var BABYLON;
  25720. (function (BABYLON) {
  25721. var InterpolateValueAction = (function (_super) {
  25722. __extends(InterpolateValueAction, _super);
  25723. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25724. if (duration === void 0) { duration = 1000; }
  25725. _super.call(this, triggerOptions, condition);
  25726. this.propertyPath = propertyPath;
  25727. this.value = value;
  25728. this.duration = duration;
  25729. this.stopOtherAnimations = stopOtherAnimations;
  25730. this.onInterpolationDone = onInterpolationDone;
  25731. this._target = target;
  25732. }
  25733. InterpolateValueAction.prototype._prepare = function () {
  25734. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25735. this._property = this._getProperty(this.propertyPath);
  25736. };
  25737. InterpolateValueAction.prototype.execute = function () {
  25738. var scene = this._actionManager.getScene();
  25739. var keys = [
  25740. {
  25741. frame: 0,
  25742. value: this._target[this._property]
  25743. }, {
  25744. frame: 100,
  25745. value: this.value
  25746. }
  25747. ];
  25748. var dataType;
  25749. if (typeof this.value === "number") {
  25750. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25751. }
  25752. else if (this.value instanceof BABYLON.Color3) {
  25753. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25754. }
  25755. else if (this.value instanceof BABYLON.Vector3) {
  25756. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25757. }
  25758. else if (this.value instanceof BABYLON.Matrix) {
  25759. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25760. }
  25761. else if (this.value instanceof BABYLON.Quaternion) {
  25762. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25763. }
  25764. else {
  25765. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25766. return;
  25767. }
  25768. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25769. animation.setKeys(keys);
  25770. if (this.stopOtherAnimations) {
  25771. scene.stopAnimation(this._target);
  25772. }
  25773. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25774. };
  25775. return InterpolateValueAction;
  25776. })(BABYLON.Action);
  25777. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25778. })(BABYLON || (BABYLON = {}));
  25779. var BABYLON;
  25780. (function (BABYLON) {
  25781. var SwitchBooleanAction = (function (_super) {
  25782. __extends(SwitchBooleanAction, _super);
  25783. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25784. _super.call(this, triggerOptions, condition);
  25785. this.propertyPath = propertyPath;
  25786. this._target = target;
  25787. }
  25788. SwitchBooleanAction.prototype._prepare = function () {
  25789. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25790. this._property = this._getProperty(this.propertyPath);
  25791. };
  25792. SwitchBooleanAction.prototype.execute = function () {
  25793. this._target[this._property] = !this._target[this._property];
  25794. };
  25795. return SwitchBooleanAction;
  25796. })(BABYLON.Action);
  25797. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25798. var SetStateAction = (function (_super) {
  25799. __extends(SetStateAction, _super);
  25800. function SetStateAction(triggerOptions, target, value, condition) {
  25801. _super.call(this, triggerOptions, condition);
  25802. this.value = value;
  25803. this._target = target;
  25804. }
  25805. SetStateAction.prototype.execute = function () {
  25806. this._target.state = this.value;
  25807. };
  25808. return SetStateAction;
  25809. })(BABYLON.Action);
  25810. BABYLON.SetStateAction = SetStateAction;
  25811. var SetValueAction = (function (_super) {
  25812. __extends(SetValueAction, _super);
  25813. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25814. _super.call(this, triggerOptions, condition);
  25815. this.propertyPath = propertyPath;
  25816. this.value = value;
  25817. this._target = target;
  25818. }
  25819. SetValueAction.prototype._prepare = function () {
  25820. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25821. this._property = this._getProperty(this.propertyPath);
  25822. };
  25823. SetValueAction.prototype.execute = function () {
  25824. this._target[this._property] = this.value;
  25825. };
  25826. return SetValueAction;
  25827. })(BABYLON.Action);
  25828. BABYLON.SetValueAction = SetValueAction;
  25829. var IncrementValueAction = (function (_super) {
  25830. __extends(IncrementValueAction, _super);
  25831. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25832. _super.call(this, triggerOptions, condition);
  25833. this.propertyPath = propertyPath;
  25834. this.value = value;
  25835. this._target = target;
  25836. }
  25837. IncrementValueAction.prototype._prepare = function () {
  25838. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25839. this._property = this._getProperty(this.propertyPath);
  25840. if (typeof this._target[this._property] !== "number") {
  25841. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25842. }
  25843. };
  25844. IncrementValueAction.prototype.execute = function () {
  25845. this._target[this._property] += this.value;
  25846. };
  25847. return IncrementValueAction;
  25848. })(BABYLON.Action);
  25849. BABYLON.IncrementValueAction = IncrementValueAction;
  25850. var PlayAnimationAction = (function (_super) {
  25851. __extends(PlayAnimationAction, _super);
  25852. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25853. _super.call(this, triggerOptions, condition);
  25854. this.from = from;
  25855. this.to = to;
  25856. this.loop = loop;
  25857. this._target = target;
  25858. }
  25859. PlayAnimationAction.prototype._prepare = function () {
  25860. };
  25861. PlayAnimationAction.prototype.execute = function () {
  25862. var scene = this._actionManager.getScene();
  25863. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25864. };
  25865. return PlayAnimationAction;
  25866. })(BABYLON.Action);
  25867. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25868. var StopAnimationAction = (function (_super) {
  25869. __extends(StopAnimationAction, _super);
  25870. function StopAnimationAction(triggerOptions, target, condition) {
  25871. _super.call(this, triggerOptions, condition);
  25872. this._target = target;
  25873. }
  25874. StopAnimationAction.prototype._prepare = function () {
  25875. };
  25876. StopAnimationAction.prototype.execute = function () {
  25877. var scene = this._actionManager.getScene();
  25878. scene.stopAnimation(this._target);
  25879. };
  25880. return StopAnimationAction;
  25881. })(BABYLON.Action);
  25882. BABYLON.StopAnimationAction = StopAnimationAction;
  25883. var DoNothingAction = (function (_super) {
  25884. __extends(DoNothingAction, _super);
  25885. function DoNothingAction(triggerOptions, condition) {
  25886. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25887. _super.call(this, triggerOptions, condition);
  25888. }
  25889. DoNothingAction.prototype.execute = function () {
  25890. };
  25891. return DoNothingAction;
  25892. })(BABYLON.Action);
  25893. BABYLON.DoNothingAction = DoNothingAction;
  25894. var CombineAction = (function (_super) {
  25895. __extends(CombineAction, _super);
  25896. function CombineAction(triggerOptions, children, condition) {
  25897. _super.call(this, triggerOptions, condition);
  25898. this.children = children;
  25899. }
  25900. CombineAction.prototype._prepare = function () {
  25901. for (var index = 0; index < this.children.length; index++) {
  25902. this.children[index]._actionManager = this._actionManager;
  25903. this.children[index]._prepare();
  25904. }
  25905. };
  25906. CombineAction.prototype.execute = function (evt) {
  25907. for (var index = 0; index < this.children.length; index++) {
  25908. this.children[index].execute(evt);
  25909. }
  25910. };
  25911. return CombineAction;
  25912. })(BABYLON.Action);
  25913. BABYLON.CombineAction = CombineAction;
  25914. var ExecuteCodeAction = (function (_super) {
  25915. __extends(ExecuteCodeAction, _super);
  25916. function ExecuteCodeAction(triggerOptions, func, condition) {
  25917. _super.call(this, triggerOptions, condition);
  25918. this.func = func;
  25919. }
  25920. ExecuteCodeAction.prototype.execute = function (evt) {
  25921. this.func(evt);
  25922. };
  25923. return ExecuteCodeAction;
  25924. })(BABYLON.Action);
  25925. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25926. var SetParentAction = (function (_super) {
  25927. __extends(SetParentAction, _super);
  25928. function SetParentAction(triggerOptions, target, parent, condition) {
  25929. _super.call(this, triggerOptions, condition);
  25930. this._target = target;
  25931. this._parent = parent;
  25932. }
  25933. SetParentAction.prototype._prepare = function () {
  25934. };
  25935. SetParentAction.prototype.execute = function () {
  25936. if (this._target.parent === this._parent) {
  25937. return;
  25938. }
  25939. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25940. invertParentWorldMatrix.invert();
  25941. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25942. this._target.parent = this._parent;
  25943. };
  25944. return SetParentAction;
  25945. })(BABYLON.Action);
  25946. BABYLON.SetParentAction = SetParentAction;
  25947. var PlaySoundAction = (function (_super) {
  25948. __extends(PlaySoundAction, _super);
  25949. function PlaySoundAction(triggerOptions, sound, condition) {
  25950. _super.call(this, triggerOptions, condition);
  25951. this._sound = sound;
  25952. }
  25953. PlaySoundAction.prototype._prepare = function () {
  25954. };
  25955. PlaySoundAction.prototype.execute = function () {
  25956. if (this._sound !== undefined)
  25957. this._sound.play();
  25958. };
  25959. return PlaySoundAction;
  25960. })(BABYLON.Action);
  25961. BABYLON.PlaySoundAction = PlaySoundAction;
  25962. var StopSoundAction = (function (_super) {
  25963. __extends(StopSoundAction, _super);
  25964. function StopSoundAction(triggerOptions, sound, condition) {
  25965. _super.call(this, triggerOptions, condition);
  25966. this._sound = sound;
  25967. }
  25968. StopSoundAction.prototype._prepare = function () {
  25969. };
  25970. StopSoundAction.prototype.execute = function () {
  25971. if (this._sound !== undefined)
  25972. this._sound.stop();
  25973. };
  25974. return StopSoundAction;
  25975. })(BABYLON.Action);
  25976. BABYLON.StopSoundAction = StopSoundAction;
  25977. })(BABYLON || (BABYLON = {}));
  25978. var BABYLON;
  25979. (function (BABYLON) {
  25980. var Geometry = (function () {
  25981. function Geometry(id, scene, vertexData, updatable, mesh) {
  25982. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25983. this._totalVertices = 0;
  25984. this._isDisposed = false;
  25985. this.id = id;
  25986. this._engine = scene.getEngine();
  25987. this._meshes = [];
  25988. this._scene = scene;
  25989. //Init vertex buffer cache
  25990. this._vertexBuffers = {};
  25991. this._indices = [];
  25992. // vertexData
  25993. if (vertexData) {
  25994. this.setAllVerticesData(vertexData, updatable);
  25995. }
  25996. else {
  25997. this._totalVertices = 0;
  25998. this._indices = [];
  25999. }
  26000. // applyToMesh
  26001. if (mesh) {
  26002. this.applyToMesh(mesh);
  26003. mesh.computeWorldMatrix(true);
  26004. }
  26005. }
  26006. Object.defineProperty(Geometry.prototype, "extend", {
  26007. get: function () {
  26008. return this._extend;
  26009. },
  26010. enumerable: true,
  26011. configurable: true
  26012. });
  26013. Geometry.prototype.getScene = function () {
  26014. return this._scene;
  26015. };
  26016. Geometry.prototype.getEngine = function () {
  26017. return this._engine;
  26018. };
  26019. Geometry.prototype.isReady = function () {
  26020. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26021. };
  26022. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26023. vertexData.applyToGeometry(this, updatable);
  26024. this.notifyUpdate();
  26025. };
  26026. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26027. if (this._vertexBuffers[kind]) {
  26028. this._vertexBuffers[kind].dispose();
  26029. }
  26030. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26031. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26032. stride = this._vertexBuffers[kind].getStrideSize();
  26033. this._totalVertices = data.length / stride;
  26034. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26035. var meshes = this._meshes;
  26036. var numOfMeshes = meshes.length;
  26037. for (var index = 0; index < numOfMeshes; index++) {
  26038. var mesh = meshes[index];
  26039. mesh._resetPointsArrayCache();
  26040. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26041. mesh._createGlobalSubMesh();
  26042. mesh.computeWorldMatrix(true);
  26043. }
  26044. }
  26045. this.notifyUpdate(kind);
  26046. };
  26047. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26048. var vertexBuffer = this.getVertexBuffer(kind);
  26049. if (!vertexBuffer) {
  26050. return;
  26051. }
  26052. vertexBuffer.updateDirectly(data, offset);
  26053. this.notifyUpdate(kind);
  26054. };
  26055. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26056. var vertexBuffer = this.getVertexBuffer(kind);
  26057. if (!vertexBuffer) {
  26058. return;
  26059. }
  26060. vertexBuffer.update(data);
  26061. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26062. var stride = vertexBuffer.getStrideSize();
  26063. this._totalVertices = data.length / stride;
  26064. if (updateExtends) {
  26065. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26066. }
  26067. var meshes = this._meshes;
  26068. var numOfMeshes = meshes.length;
  26069. for (var index = 0; index < numOfMeshes; index++) {
  26070. var mesh = meshes[index];
  26071. mesh._resetPointsArrayCache();
  26072. if (updateExtends) {
  26073. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26074. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26075. var subMesh = mesh.subMeshes[subIndex];
  26076. subMesh.refreshBoundingInfo();
  26077. }
  26078. }
  26079. }
  26080. }
  26081. this.notifyUpdate(kind);
  26082. };
  26083. Geometry.prototype.getTotalVertices = function () {
  26084. if (!this.isReady()) {
  26085. return 0;
  26086. }
  26087. return this._totalVertices;
  26088. };
  26089. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26090. var vertexBuffer = this.getVertexBuffer(kind);
  26091. if (!vertexBuffer) {
  26092. return null;
  26093. }
  26094. var orig = vertexBuffer.getData();
  26095. if (!copyWhenShared || this._meshes.length === 1) {
  26096. return orig;
  26097. }
  26098. else {
  26099. var len = orig.length;
  26100. var copy = [];
  26101. for (var i = 0; i < len; i++) {
  26102. copy.push(orig[i]);
  26103. }
  26104. return copy;
  26105. }
  26106. };
  26107. Geometry.prototype.getVertexBuffer = function (kind) {
  26108. if (!this.isReady()) {
  26109. return null;
  26110. }
  26111. return this._vertexBuffers[kind];
  26112. };
  26113. Geometry.prototype.getVertexBuffers = function () {
  26114. if (!this.isReady()) {
  26115. return null;
  26116. }
  26117. return this._vertexBuffers;
  26118. };
  26119. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26120. if (!this._vertexBuffers) {
  26121. if (this._delayInfo) {
  26122. return this._delayInfo.indexOf(kind) !== -1;
  26123. }
  26124. return false;
  26125. }
  26126. return this._vertexBuffers[kind] !== undefined;
  26127. };
  26128. Geometry.prototype.getVerticesDataKinds = function () {
  26129. var result = [];
  26130. var kind;
  26131. if (!this._vertexBuffers && this._delayInfo) {
  26132. for (kind in this._delayInfo) {
  26133. result.push(kind);
  26134. }
  26135. }
  26136. else {
  26137. for (kind in this._vertexBuffers) {
  26138. result.push(kind);
  26139. }
  26140. }
  26141. return result;
  26142. };
  26143. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26144. if (this._indexBuffer) {
  26145. this._engine._releaseBuffer(this._indexBuffer);
  26146. }
  26147. this._indices = indices;
  26148. if (this._meshes.length !== 0 && this._indices) {
  26149. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26150. }
  26151. if (totalVertices !== undefined) {
  26152. this._totalVertices = totalVertices;
  26153. }
  26154. var meshes = this._meshes;
  26155. var numOfMeshes = meshes.length;
  26156. for (var index = 0; index < numOfMeshes; index++) {
  26157. meshes[index]._createGlobalSubMesh();
  26158. }
  26159. this.notifyUpdate();
  26160. };
  26161. Geometry.prototype.getTotalIndices = function () {
  26162. if (!this.isReady()) {
  26163. return 0;
  26164. }
  26165. return this._indices.length;
  26166. };
  26167. Geometry.prototype.getIndices = function (copyWhenShared) {
  26168. if (!this.isReady()) {
  26169. return null;
  26170. }
  26171. var orig = this._indices;
  26172. if (!copyWhenShared || this._meshes.length === 1) {
  26173. return orig;
  26174. }
  26175. else {
  26176. var len = orig.length;
  26177. var copy = [];
  26178. for (var i = 0; i < len; i++) {
  26179. copy.push(orig[i]);
  26180. }
  26181. return copy;
  26182. }
  26183. };
  26184. Geometry.prototype.getIndexBuffer = function () {
  26185. if (!this.isReady()) {
  26186. return null;
  26187. }
  26188. return this._indexBuffer;
  26189. };
  26190. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26191. var meshes = this._meshes;
  26192. var index = meshes.indexOf(mesh);
  26193. if (index === -1) {
  26194. return;
  26195. }
  26196. for (var kind in this._vertexBuffers) {
  26197. this._vertexBuffers[kind].dispose();
  26198. }
  26199. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26200. this._indexBuffer = null;
  26201. }
  26202. meshes.splice(index, 1);
  26203. mesh._geometry = null;
  26204. if (meshes.length === 0 && shouldDispose) {
  26205. this.dispose();
  26206. }
  26207. };
  26208. Geometry.prototype.applyToMesh = function (mesh) {
  26209. if (mesh._geometry === this) {
  26210. return;
  26211. }
  26212. var previousGeometry = mesh._geometry;
  26213. if (previousGeometry) {
  26214. previousGeometry.releaseForMesh(mesh);
  26215. }
  26216. var meshes = this._meshes;
  26217. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26218. mesh._geometry = this;
  26219. this._scene.pushGeometry(this);
  26220. meshes.push(mesh);
  26221. if (this.isReady()) {
  26222. this._applyToMesh(mesh);
  26223. }
  26224. else {
  26225. mesh._boundingInfo = this._boundingInfo;
  26226. }
  26227. };
  26228. Geometry.prototype._applyToMesh = function (mesh) {
  26229. var numOfMeshes = this._meshes.length;
  26230. // vertexBuffers
  26231. for (var kind in this._vertexBuffers) {
  26232. if (numOfMeshes === 1) {
  26233. this._vertexBuffers[kind].create();
  26234. }
  26235. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26236. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26237. mesh._resetPointsArrayCache();
  26238. if (!this._extend) {
  26239. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26240. }
  26241. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26242. mesh._createGlobalSubMesh();
  26243. //bounding info was just created again, world matrix should be applied again.
  26244. mesh._updateBoundingInfo();
  26245. }
  26246. }
  26247. // indexBuffer
  26248. if (numOfMeshes === 1 && this._indices) {
  26249. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26250. }
  26251. if (this._indexBuffer) {
  26252. this._indexBuffer.references = numOfMeshes;
  26253. }
  26254. };
  26255. Geometry.prototype.notifyUpdate = function (kind) {
  26256. if (this.onGeometryUpdated) {
  26257. this.onGeometryUpdated(this, kind);
  26258. }
  26259. };
  26260. Geometry.prototype.load = function (scene, onLoaded) {
  26261. var _this = this;
  26262. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26263. return;
  26264. }
  26265. if (this.isReady()) {
  26266. if (onLoaded) {
  26267. onLoaded();
  26268. }
  26269. return;
  26270. }
  26271. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26272. scene._addPendingData(this);
  26273. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26274. _this._delayLoadingFunction(JSON.parse(data), _this);
  26275. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26276. _this._delayInfo = [];
  26277. scene._removePendingData(_this);
  26278. var meshes = _this._meshes;
  26279. var numOfMeshes = meshes.length;
  26280. for (var index = 0; index < numOfMeshes; index++) {
  26281. _this._applyToMesh(meshes[index]);
  26282. }
  26283. if (onLoaded) {
  26284. onLoaded();
  26285. }
  26286. }, function () { }, scene.database);
  26287. };
  26288. Geometry.prototype.isDisposed = function () {
  26289. return this._isDisposed;
  26290. };
  26291. Geometry.prototype.dispose = function () {
  26292. var meshes = this._meshes;
  26293. var numOfMeshes = meshes.length;
  26294. var index;
  26295. for (index = 0; index < numOfMeshes; index++) {
  26296. this.releaseForMesh(meshes[index]);
  26297. }
  26298. this._meshes = [];
  26299. for (var kind in this._vertexBuffers) {
  26300. this._vertexBuffers[kind].dispose();
  26301. }
  26302. this._vertexBuffers = [];
  26303. this._totalVertices = 0;
  26304. if (this._indexBuffer) {
  26305. this._engine._releaseBuffer(this._indexBuffer);
  26306. }
  26307. this._indexBuffer = null;
  26308. this._indices = [];
  26309. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26310. this.delayLoadingFile = null;
  26311. this._delayLoadingFunction = null;
  26312. this._delayInfo = [];
  26313. this._boundingInfo = null;
  26314. this._scene.removeGeometry(this);
  26315. this._isDisposed = true;
  26316. };
  26317. Geometry.prototype.copy = function (id) {
  26318. var vertexData = new BABYLON.VertexData();
  26319. vertexData.indices = [];
  26320. var indices = this.getIndices();
  26321. for (var index = 0; index < indices.length; index++) {
  26322. vertexData.indices.push(indices[index]);
  26323. }
  26324. var updatable = false;
  26325. var stopChecking = false;
  26326. var kind;
  26327. for (kind in this._vertexBuffers) {
  26328. // using slice() to make a copy of the array and not just reference it
  26329. var data = this.getVerticesData(kind);
  26330. if (data instanceof Float32Array) {
  26331. vertexData.set(new Float32Array(data), kind);
  26332. }
  26333. else {
  26334. vertexData.set(data.slice(0), kind);
  26335. }
  26336. if (!stopChecking) {
  26337. updatable = this.getVertexBuffer(kind).isUpdatable();
  26338. stopChecking = !updatable;
  26339. }
  26340. }
  26341. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26342. geometry.delayLoadState = this.delayLoadState;
  26343. geometry.delayLoadingFile = this.delayLoadingFile;
  26344. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26345. for (kind in this._delayInfo) {
  26346. geometry._delayInfo = geometry._delayInfo || [];
  26347. geometry._delayInfo.push(kind);
  26348. }
  26349. // Bounding info
  26350. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26351. return geometry;
  26352. };
  26353. Geometry.prototype.serialize = function () {
  26354. var serializationObject = {};
  26355. serializationObject.id = this.id;
  26356. if (BABYLON.Tags.HasTags(this)) {
  26357. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26358. }
  26359. return serializationObject;
  26360. };
  26361. Geometry.prototype.serializeVerticeData = function () {
  26362. var serializationObject = this.serialize();
  26363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26364. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26365. }
  26366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26367. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26368. }
  26369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26370. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26371. }
  26372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26373. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26374. }
  26375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26376. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26377. }
  26378. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26379. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26380. }
  26381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26382. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26383. }
  26384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26385. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26386. }
  26387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26388. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26389. }
  26390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26391. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26392. serializationObject.matricesIndices._isExpanded = true;
  26393. }
  26394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26395. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26396. }
  26397. serializationObject.indices = this.getIndices();
  26398. return serializationObject;
  26399. };
  26400. // Statics
  26401. Geometry.ExtractFromMesh = function (mesh, id) {
  26402. var geometry = mesh._geometry;
  26403. if (!geometry) {
  26404. return null;
  26405. }
  26406. return geometry.copy(id);
  26407. };
  26408. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26409. // be aware Math.random() could cause collisions
  26410. Geometry.RandomId = function () {
  26411. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26412. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26413. return v.toString(16);
  26414. });
  26415. };
  26416. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26417. var scene = mesh.getScene();
  26418. // Geometry
  26419. var geometryId = parsedGeometry.geometryId;
  26420. if (geometryId) {
  26421. var geometry = scene.getGeometryByID(geometryId);
  26422. if (geometry) {
  26423. geometry.applyToMesh(mesh);
  26424. }
  26425. }
  26426. else if (parsedGeometry instanceof ArrayBuffer) {
  26427. var binaryInfo = mesh._binaryInfo;
  26428. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26429. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26430. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26431. }
  26432. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26433. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26434. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26435. }
  26436. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26437. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26438. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26439. }
  26440. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26441. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26442. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26443. }
  26444. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26445. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26446. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26447. }
  26448. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26449. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26450. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26451. }
  26452. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26453. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26454. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26455. }
  26456. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26457. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26458. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26459. }
  26460. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26461. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26462. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26463. }
  26464. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26465. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26466. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26467. }
  26468. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26469. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26470. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26471. }
  26472. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26473. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26474. mesh.setIndices(indicesData);
  26475. }
  26476. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26477. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26478. mesh.subMeshes = [];
  26479. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26480. var materialIndex = subMeshesData[(i * 5) + 0];
  26481. var verticesStart = subMeshesData[(i * 5) + 1];
  26482. var verticesCount = subMeshesData[(i * 5) + 2];
  26483. var indexStart = subMeshesData[(i * 5) + 3];
  26484. var indexCount = subMeshesData[(i * 5) + 4];
  26485. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26486. }
  26487. }
  26488. }
  26489. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26490. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  26491. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  26492. if (parsedGeometry.uvs) {
  26493. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  26494. }
  26495. if (parsedGeometry.uvs2) {
  26496. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  26497. }
  26498. if (parsedGeometry.uvs3) {
  26499. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  26500. }
  26501. if (parsedGeometry.uvs4) {
  26502. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  26503. }
  26504. if (parsedGeometry.uvs5) {
  26505. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  26506. }
  26507. if (parsedGeometry.uvs6) {
  26508. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  26509. }
  26510. if (parsedGeometry.colors) {
  26511. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  26512. }
  26513. if (parsedGeometry.matricesIndices) {
  26514. if (!parsedGeometry.matricesIndices._isExpanded) {
  26515. var floatIndices = [];
  26516. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26517. var matricesIndex = parsedGeometry.matricesIndices[i];
  26518. floatIndices.push(matricesIndex & 0x000000FF);
  26519. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26520. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26521. floatIndices.push(matricesIndex >> 24);
  26522. }
  26523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  26524. }
  26525. else {
  26526. delete parsedGeometry.matricesIndices._isExpanded;
  26527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  26528. }
  26529. }
  26530. if (parsedGeometry.matricesIndicesExtra) {
  26531. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26532. var floatIndices = [];
  26533. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26534. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26535. floatIndices.push(matricesIndex & 0x000000FF);
  26536. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26537. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26538. floatIndices.push(matricesIndex >> 24);
  26539. }
  26540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  26541. }
  26542. else {
  26543. delete parsedGeometry.matricesIndices._isExpanded;
  26544. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  26545. }
  26546. }
  26547. if (parsedGeometry.matricesWeights) {
  26548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  26549. }
  26550. if (parsedGeometry.matricesWeightsExtra) {
  26551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  26552. }
  26553. mesh.setIndices(parsedGeometry.indices);
  26554. }
  26555. // SubMeshes
  26556. if (parsedGeometry.subMeshes) {
  26557. mesh.subMeshes = [];
  26558. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26559. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26560. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26561. }
  26562. }
  26563. // Flat shading
  26564. if (mesh._shouldGenerateFlatShading) {
  26565. mesh.convertToFlatShadedMesh();
  26566. delete mesh._shouldGenerateFlatShading;
  26567. }
  26568. // Update
  26569. mesh.computeWorldMatrix(true);
  26570. // Octree
  26571. if (scene['_selectionOctree']) {
  26572. scene['_selectionOctree'].addMesh(mesh);
  26573. }
  26574. };
  26575. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26576. if (scene.getGeometryByID(parsedVertexData.id)) {
  26577. return null; // null since geometry could be something else than a box...
  26578. }
  26579. var geometry = new Geometry(parsedVertexData.id, scene);
  26580. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26581. if (parsedVertexData.delayLoadingFile) {
  26582. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26583. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26584. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26585. geometry._delayInfo = [];
  26586. if (parsedVertexData.hasUVs) {
  26587. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26588. }
  26589. if (parsedVertexData.hasUVs2) {
  26590. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26591. }
  26592. if (parsedVertexData.hasUVs3) {
  26593. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26594. }
  26595. if (parsedVertexData.hasUVs4) {
  26596. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26597. }
  26598. if (parsedVertexData.hasUVs5) {
  26599. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26600. }
  26601. if (parsedVertexData.hasUVs6) {
  26602. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26603. }
  26604. if (parsedVertexData.hasColors) {
  26605. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26606. }
  26607. if (parsedVertexData.hasMatricesIndices) {
  26608. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26609. }
  26610. if (parsedVertexData.hasMatricesWeights) {
  26611. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26612. }
  26613. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26614. }
  26615. else {
  26616. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26617. }
  26618. scene.pushGeometry(geometry, true);
  26619. return geometry;
  26620. };
  26621. return Geometry;
  26622. })();
  26623. BABYLON.Geometry = Geometry;
  26624. /////// Primitives //////////////////////////////////////////////
  26625. var Geometry;
  26626. (function (Geometry) {
  26627. var Primitives;
  26628. (function (Primitives) {
  26629. /// Abstract class
  26630. var _Primitive = (function (_super) {
  26631. __extends(_Primitive, _super);
  26632. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26633. this._beingRegenerated = true;
  26634. this._canBeRegenerated = canBeRegenerated;
  26635. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26636. this._beingRegenerated = false;
  26637. }
  26638. _Primitive.prototype.canBeRegenerated = function () {
  26639. return this._canBeRegenerated;
  26640. };
  26641. _Primitive.prototype.regenerate = function () {
  26642. if (!this._canBeRegenerated) {
  26643. return;
  26644. }
  26645. this._beingRegenerated = true;
  26646. this.setAllVerticesData(this._regenerateVertexData(), false);
  26647. this._beingRegenerated = false;
  26648. };
  26649. _Primitive.prototype.asNewGeometry = function (id) {
  26650. return _super.prototype.copy.call(this, id);
  26651. };
  26652. // overrides
  26653. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26654. if (!this._beingRegenerated) {
  26655. return;
  26656. }
  26657. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26658. };
  26659. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26660. if (!this._beingRegenerated) {
  26661. return;
  26662. }
  26663. _super.prototype.setVerticesData.call(this, kind, data, false);
  26664. };
  26665. // to override
  26666. // protected
  26667. _Primitive.prototype._regenerateVertexData = function () {
  26668. throw new Error("Abstract method");
  26669. };
  26670. _Primitive.prototype.copy = function (id) {
  26671. throw new Error("Must be overriden in sub-classes.");
  26672. };
  26673. _Primitive.prototype.serialize = function () {
  26674. var serializationObject = _super.prototype.serialize.call(this);
  26675. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26676. return serializationObject;
  26677. };
  26678. return _Primitive;
  26679. })(Geometry);
  26680. Primitives._Primitive = _Primitive;
  26681. var Ribbon = (function (_super) {
  26682. __extends(Ribbon, _super);
  26683. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26684. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26685. this.pathArray = pathArray;
  26686. this.closeArray = closeArray;
  26687. this.closePath = closePath;
  26688. this.offset = offset;
  26689. this.side = side;
  26690. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26691. }
  26692. Ribbon.prototype._regenerateVertexData = function () {
  26693. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26694. };
  26695. Ribbon.prototype.copy = function (id) {
  26696. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26697. };
  26698. return Ribbon;
  26699. })(_Primitive);
  26700. Primitives.Ribbon = Ribbon;
  26701. var Box = (function (_super) {
  26702. __extends(Box, _super);
  26703. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26704. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26705. this.size = size;
  26706. this.side = side;
  26707. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26708. }
  26709. Box.prototype._regenerateVertexData = function () {
  26710. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26711. };
  26712. Box.prototype.copy = function (id) {
  26713. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26714. };
  26715. Box.prototype.serialize = function () {
  26716. var serializationObject = _super.prototype.serialize.call(this);
  26717. serializationObject.size = this.size;
  26718. return serializationObject;
  26719. };
  26720. Box.Parse = function (parsedBox, scene) {
  26721. if (scene.getGeometryByID(parsedBox.id)) {
  26722. return null; // null since geometry could be something else than a box...
  26723. }
  26724. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26725. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26726. scene.pushGeometry(box, true);
  26727. return box;
  26728. };
  26729. return Box;
  26730. })(_Primitive);
  26731. Primitives.Box = Box;
  26732. var Sphere = (function (_super) {
  26733. __extends(Sphere, _super);
  26734. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26735. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26736. this.segments = segments;
  26737. this.diameter = diameter;
  26738. this.side = side;
  26739. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26740. }
  26741. Sphere.prototype._regenerateVertexData = function () {
  26742. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26743. };
  26744. Sphere.prototype.copy = function (id) {
  26745. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26746. };
  26747. Sphere.prototype.serialize = function () {
  26748. var serializationObject = _super.prototype.serialize.call(this);
  26749. serializationObject.segments = this.segments;
  26750. serializationObject.diameter = this.diameter;
  26751. return serializationObject;
  26752. };
  26753. Sphere.Parse = function (parsedSphere, scene) {
  26754. if (scene.getGeometryByID(parsedSphere.id)) {
  26755. return null; // null since geometry could be something else than a sphere...
  26756. }
  26757. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26758. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26759. scene.pushGeometry(sphere, true);
  26760. return sphere;
  26761. };
  26762. return Sphere;
  26763. })(_Primitive);
  26764. Primitives.Sphere = Sphere;
  26765. var Disc = (function (_super) {
  26766. __extends(Disc, _super);
  26767. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26768. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26769. this.radius = radius;
  26770. this.tessellation = tessellation;
  26771. this.side = side;
  26772. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26773. }
  26774. Disc.prototype._regenerateVertexData = function () {
  26775. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26776. };
  26777. Disc.prototype.copy = function (id) {
  26778. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26779. };
  26780. return Disc;
  26781. })(_Primitive);
  26782. Primitives.Disc = Disc;
  26783. var Cylinder = (function (_super) {
  26784. __extends(Cylinder, _super);
  26785. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26786. if (subdivisions === void 0) { subdivisions = 1; }
  26787. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26788. this.height = height;
  26789. this.diameterTop = diameterTop;
  26790. this.diameterBottom = diameterBottom;
  26791. this.tessellation = tessellation;
  26792. this.subdivisions = subdivisions;
  26793. this.side = side;
  26794. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26795. }
  26796. Cylinder.prototype._regenerateVertexData = function () {
  26797. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26798. };
  26799. Cylinder.prototype.copy = function (id) {
  26800. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26801. };
  26802. Cylinder.prototype.serialize = function () {
  26803. var serializationObject = _super.prototype.serialize.call(this);
  26804. serializationObject.height = this.height;
  26805. serializationObject.diameterTop = this.diameterTop;
  26806. serializationObject.diameterBottom = this.diameterBottom;
  26807. serializationObject.tessellation = this.tessellation;
  26808. return serializationObject;
  26809. };
  26810. Cylinder.Parse = function (parsedCylinder, scene) {
  26811. if (scene.getGeometryByID(parsedCylinder.id)) {
  26812. return null; // null since geometry could be something else than a cylinder...
  26813. }
  26814. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26815. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26816. scene.pushGeometry(cylinder, true);
  26817. return cylinder;
  26818. };
  26819. return Cylinder;
  26820. })(_Primitive);
  26821. Primitives.Cylinder = Cylinder;
  26822. var Torus = (function (_super) {
  26823. __extends(Torus, _super);
  26824. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26826. this.diameter = diameter;
  26827. this.thickness = thickness;
  26828. this.tessellation = tessellation;
  26829. this.side = side;
  26830. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26831. }
  26832. Torus.prototype._regenerateVertexData = function () {
  26833. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26834. };
  26835. Torus.prototype.copy = function (id) {
  26836. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26837. };
  26838. Torus.prototype.serialize = function () {
  26839. var serializationObject = _super.prototype.serialize.call(this);
  26840. serializationObject.diameter = this.diameter;
  26841. serializationObject.thickness = this.thickness;
  26842. serializationObject.tessellation = this.tessellation;
  26843. return serializationObject;
  26844. };
  26845. Torus.Parse = function (parsedTorus, scene) {
  26846. if (scene.getGeometryByID(parsedTorus.id)) {
  26847. return null; // null since geometry could be something else than a torus...
  26848. }
  26849. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26850. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26851. scene.pushGeometry(torus, true);
  26852. return torus;
  26853. };
  26854. return Torus;
  26855. })(_Primitive);
  26856. Primitives.Torus = Torus;
  26857. var Ground = (function (_super) {
  26858. __extends(Ground, _super);
  26859. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26860. this.width = width;
  26861. this.height = height;
  26862. this.subdivisions = subdivisions;
  26863. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26864. }
  26865. Ground.prototype._regenerateVertexData = function () {
  26866. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26867. };
  26868. Ground.prototype.copy = function (id) {
  26869. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26870. };
  26871. Ground.prototype.serialize = function () {
  26872. var serializationObject = _super.prototype.serialize.call(this);
  26873. serializationObject.width = this.width;
  26874. serializationObject.height = this.height;
  26875. serializationObject.subdivisions = this.subdivisions;
  26876. return serializationObject;
  26877. };
  26878. Ground.Parse = function (parsedGround, scene) {
  26879. if (scene.getGeometryByID(parsedGround.id)) {
  26880. return null; // null since geometry could be something else than a ground...
  26881. }
  26882. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26883. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26884. scene.pushGeometry(ground, true);
  26885. return ground;
  26886. };
  26887. return Ground;
  26888. })(_Primitive);
  26889. Primitives.Ground = Ground;
  26890. var TiledGround = (function (_super) {
  26891. __extends(TiledGround, _super);
  26892. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26893. this.xmin = xmin;
  26894. this.zmin = zmin;
  26895. this.xmax = xmax;
  26896. this.zmax = zmax;
  26897. this.subdivisions = subdivisions;
  26898. this.precision = precision;
  26899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26900. }
  26901. TiledGround.prototype._regenerateVertexData = function () {
  26902. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26903. };
  26904. TiledGround.prototype.copy = function (id) {
  26905. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26906. };
  26907. return TiledGround;
  26908. })(_Primitive);
  26909. Primitives.TiledGround = TiledGround;
  26910. var Plane = (function (_super) {
  26911. __extends(Plane, _super);
  26912. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26914. this.size = size;
  26915. this.side = side;
  26916. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26917. }
  26918. Plane.prototype._regenerateVertexData = function () {
  26919. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26920. };
  26921. Plane.prototype.copy = function (id) {
  26922. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26923. };
  26924. Plane.prototype.serialize = function () {
  26925. var serializationObject = _super.prototype.serialize.call(this);
  26926. serializationObject.size = this.size;
  26927. return serializationObject;
  26928. };
  26929. Plane.Parse = function (parsedPlane, scene) {
  26930. if (scene.getGeometryByID(parsedPlane.id)) {
  26931. return null; // null since geometry could be something else than a ground...
  26932. }
  26933. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26934. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26935. scene.pushGeometry(plane, true);
  26936. return plane;
  26937. };
  26938. return Plane;
  26939. })(_Primitive);
  26940. Primitives.Plane = Plane;
  26941. var TorusKnot = (function (_super) {
  26942. __extends(TorusKnot, _super);
  26943. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26944. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26945. this.radius = radius;
  26946. this.tube = tube;
  26947. this.radialSegments = radialSegments;
  26948. this.tubularSegments = tubularSegments;
  26949. this.p = p;
  26950. this.q = q;
  26951. this.side = side;
  26952. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26953. }
  26954. TorusKnot.prototype._regenerateVertexData = function () {
  26955. 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 });
  26956. };
  26957. TorusKnot.prototype.copy = function (id) {
  26958. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26959. };
  26960. TorusKnot.prototype.serialize = function () {
  26961. var serializationObject = _super.prototype.serialize.call(this);
  26962. serializationObject.radius = this.radius;
  26963. serializationObject.tube = this.tube;
  26964. serializationObject.radialSegments = this.radialSegments;
  26965. serializationObject.tubularSegments = this.tubularSegments;
  26966. serializationObject.p = this.p;
  26967. serializationObject.q = this.q;
  26968. return serializationObject;
  26969. };
  26970. ;
  26971. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26972. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26973. return null; // null since geometry could be something else than a ground...
  26974. }
  26975. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26976. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26977. scene.pushGeometry(torusKnot, true);
  26978. return torusKnot;
  26979. };
  26980. return TorusKnot;
  26981. })(_Primitive);
  26982. Primitives.TorusKnot = TorusKnot;
  26983. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26984. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26985. })(BABYLON || (BABYLON = {}));
  26986. var BABYLON;
  26987. (function (BABYLON) {
  26988. var GroundMesh = (function (_super) {
  26989. __extends(GroundMesh, _super);
  26990. function GroundMesh(name, scene) {
  26991. _super.call(this, name, scene);
  26992. this.generateOctree = false;
  26993. this._worldInverse = new BABYLON.Matrix();
  26994. }
  26995. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26996. get: function () {
  26997. return this._subdivisions;
  26998. },
  26999. enumerable: true,
  27000. configurable: true
  27001. });
  27002. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27003. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27004. this._subdivisions = chunksCount;
  27005. this.subdivide(this._subdivisions);
  27006. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27007. };
  27008. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27009. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27010. this.getWorldMatrix().invertToRef(this._worldInverse);
  27011. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27012. var pickInfo = this.intersects(ray);
  27013. if (pickInfo.hit) {
  27014. return pickInfo.pickedPoint.y;
  27015. }
  27016. return 0;
  27017. };
  27018. return GroundMesh;
  27019. })(BABYLON.Mesh);
  27020. BABYLON.GroundMesh = GroundMesh;
  27021. })(BABYLON || (BABYLON = {}));
  27022. var BABYLON;
  27023. (function (BABYLON) {
  27024. var LinesMesh = (function (_super) {
  27025. __extends(LinesMesh, _super);
  27026. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27027. if (parent === void 0) { parent = null; }
  27028. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27029. this.color = new BABYLON.Color3(1, 1, 1);
  27030. this.alpha = 1;
  27031. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27032. attributes: ["position"],
  27033. uniforms: ["worldViewProjection", "color"],
  27034. needAlphaBlending: true
  27035. });
  27036. }
  27037. Object.defineProperty(LinesMesh.prototype, "material", {
  27038. get: function () {
  27039. return this._colorShader;
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27045. get: function () {
  27046. return false;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27052. get: function () {
  27053. return false;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27059. var engine = this.getScene().getEngine();
  27060. var indexToBind = this._geometry.getIndexBuffer();
  27061. // VBOs
  27062. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27063. // Color
  27064. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27065. };
  27066. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27067. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27068. return;
  27069. }
  27070. var engine = this.getScene().getEngine();
  27071. // Draw order
  27072. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27073. };
  27074. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27075. return null;
  27076. };
  27077. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27078. this._colorShader.dispose();
  27079. _super.prototype.dispose.call(this, doNotRecurse);
  27080. };
  27081. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27082. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27083. };
  27084. return LinesMesh;
  27085. })(BABYLON.Mesh);
  27086. BABYLON.LinesMesh = LinesMesh;
  27087. })(BABYLON || (BABYLON = {}));
  27088. var BABYLON;
  27089. (function (BABYLON) {
  27090. var DebugLayer = (function () {
  27091. function DebugLayer(scene) {
  27092. var _this = this;
  27093. this._transformationMatrix = BABYLON.Matrix.Identity();
  27094. this._enabled = false;
  27095. this._labelsEnabled = false;
  27096. this._displayStatistics = true;
  27097. this._displayTree = false;
  27098. this._displayLogs = false;
  27099. this._identityMatrix = BABYLON.Matrix.Identity();
  27100. this.axisRatio = 0.02;
  27101. this.accentColor = "orange";
  27102. this._scene = scene;
  27103. this._syncPositions = function () {
  27104. var engine = _this._scene.getEngine();
  27105. var canvasRect = engine.getRenderingCanvasClientRect();
  27106. if (_this._showUI) {
  27107. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27108. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27109. _this._statsDiv.style.width = "400px";
  27110. _this._statsDiv.style.height = "auto";
  27111. _this._statsSubsetDiv.style.maxHeight = "240px";
  27112. _this._optionsDiv.style.left = "0px";
  27113. _this._optionsDiv.style.top = "10px";
  27114. _this._optionsDiv.style.width = "200px";
  27115. _this._optionsDiv.style.height = "auto";
  27116. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27117. _this._logDiv.style.left = "0px";
  27118. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27119. _this._logDiv.style.width = "600px";
  27120. _this._logDiv.style.height = "160px";
  27121. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27122. _this._treeDiv.style.top = "10px";
  27123. _this._treeDiv.style.width = "300px";
  27124. _this._treeDiv.style.height = "auto";
  27125. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27126. }
  27127. _this._globalDiv.style.left = canvasRect.left + "px";
  27128. _this._globalDiv.style.top = canvasRect.top + "px";
  27129. _this._drawingCanvas.style.left = "0px";
  27130. _this._drawingCanvas.style.top = "0px";
  27131. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27132. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27133. var devicePixelRatio = window.devicePixelRatio || 1;
  27134. var context = _this._drawingContext;
  27135. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27136. context.mozBackingStorePixelRatio ||
  27137. context.msBackingStorePixelRatio ||
  27138. context.oBackingStorePixelRatio ||
  27139. context.backingStorePixelRatio || 1;
  27140. _this._ratio = devicePixelRatio / backingStoreRatio;
  27141. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27142. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27143. };
  27144. this._onCanvasClick = function (evt) {
  27145. _this._clickPosition = {
  27146. x: evt.clientX * _this._ratio,
  27147. y: evt.clientY * _this._ratio
  27148. };
  27149. };
  27150. this._syncUI = function () {
  27151. if (_this._showUI) {
  27152. if (_this._displayStatistics) {
  27153. _this._displayStats();
  27154. _this._statsDiv.style.display = "";
  27155. }
  27156. else {
  27157. _this._statsDiv.style.display = "none";
  27158. }
  27159. if (_this._displayLogs) {
  27160. _this._logDiv.style.display = "";
  27161. }
  27162. else {
  27163. _this._logDiv.style.display = "none";
  27164. }
  27165. if (_this._displayTree) {
  27166. _this._treeDiv.style.display = "";
  27167. if (_this._needToRefreshMeshesTree) {
  27168. _this._needToRefreshMeshesTree = false;
  27169. _this._refreshMeshesTreeContent();
  27170. }
  27171. }
  27172. else {
  27173. _this._treeDiv.style.display = "none";
  27174. }
  27175. }
  27176. };
  27177. this._syncData = function () {
  27178. if (_this._labelsEnabled || !_this._showUI) {
  27179. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27180. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27181. var engine = _this._scene.getEngine();
  27182. var viewport = _this._camera.viewport;
  27183. var globalViewport = viewport.toGlobal(engine);
  27184. // Meshes
  27185. var meshes = _this._camera.getActiveMeshes();
  27186. var index;
  27187. var projectedPosition;
  27188. for (index = 0; index < meshes.length; index++) {
  27189. var mesh = meshes.data[index];
  27190. var position = mesh.getBoundingInfo().boundingSphere.center;
  27191. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27192. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27193. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27194. }
  27195. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27196. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27197. }
  27198. }
  27199. // Cameras
  27200. var cameras = _this._scene.cameras;
  27201. for (index = 0; index < cameras.length; index++) {
  27202. var camera = cameras[index];
  27203. if (camera === _this._camera) {
  27204. continue;
  27205. }
  27206. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27207. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27208. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27209. _this._camera.detachControl(engine.getRenderingCanvas());
  27210. _this._camera = camera;
  27211. _this._camera.attachControl(engine.getRenderingCanvas());
  27212. }, function () { return "purple"; });
  27213. }
  27214. }
  27215. // Lights
  27216. var lights = _this._scene.lights;
  27217. for (index = 0; index < lights.length; index++) {
  27218. var light = lights[index];
  27219. if (light.position) {
  27220. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27221. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27222. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27223. light.setEnabled(!light.isEnabled());
  27224. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27225. }
  27226. }
  27227. }
  27228. }
  27229. _this._clickPosition = undefined;
  27230. };
  27231. }
  27232. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27233. while (this._treeSubsetDiv.hasChildNodes()) {
  27234. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27235. }
  27236. // Add meshes
  27237. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27238. sortedArray.sort(function (a, b) {
  27239. if (a.name === b.name) {
  27240. return 0;
  27241. }
  27242. return (a.name > b.name) ? 1 : -1;
  27243. });
  27244. for (var index = 0; index < sortedArray.length; index++) {
  27245. var mesh = sortedArray[index];
  27246. if (!mesh.isEnabled()) {
  27247. continue;
  27248. }
  27249. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27250. m.isVisible = element.checked;
  27251. }, mesh);
  27252. }
  27253. };
  27254. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27255. this._drawingContext.beginPath();
  27256. this._drawingContext.moveTo(zero.x, zero.y);
  27257. this._drawingContext.lineTo(unit.x, unit.y);
  27258. this._drawingContext.strokeStyle = color;
  27259. this._drawingContext.lineWidth = 4;
  27260. this._drawingContext.stroke();
  27261. this._drawingContext.font = "normal 14px Segoe UI";
  27262. this._drawingContext.fillStyle = color;
  27263. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27264. };
  27265. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27266. var position = mesh.getBoundingInfo().boundingSphere.center;
  27267. var worldMatrix = mesh.getWorldMatrix();
  27268. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27269. var unit = (unprojectedVector.subtract(position)).length();
  27270. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27271. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27272. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27273. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27274. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27275. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27276. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27277. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27278. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27279. };
  27280. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27281. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27282. this._drawingContext.font = "normal 12px Segoe UI";
  27283. var textMetrics = this._drawingContext.measureText(text);
  27284. var centerX = projectedPosition.x - textMetrics.width / 2;
  27285. var centerY = projectedPosition.y;
  27286. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27287. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27288. onClick();
  27289. }
  27290. this._drawingContext.beginPath();
  27291. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27292. this._drawingContext.fillStyle = getFillStyle();
  27293. this._drawingContext.globalAlpha = 0.5;
  27294. this._drawingContext.fill();
  27295. this._drawingContext.globalAlpha = 1.0;
  27296. this._drawingContext.strokeStyle = '#FFFFFF';
  27297. this._drawingContext.lineWidth = 1;
  27298. this._drawingContext.stroke();
  27299. this._drawingContext.fillStyle = "#FFFFFF";
  27300. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27301. this._drawingContext.beginPath();
  27302. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27303. this._drawingContext.fill();
  27304. }
  27305. };
  27306. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27307. if (!this._clickPosition) {
  27308. return false;
  27309. }
  27310. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27311. return false;
  27312. }
  27313. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27314. return false;
  27315. }
  27316. return true;
  27317. };
  27318. DebugLayer.prototype.isVisible = function () {
  27319. return this._enabled;
  27320. };
  27321. DebugLayer.prototype.hide = function () {
  27322. if (!this._enabled) {
  27323. return;
  27324. }
  27325. this._enabled = false;
  27326. var engine = this._scene.getEngine();
  27327. this._scene.unregisterBeforeRender(this._syncData);
  27328. this._scene.unregisterAfterRender(this._syncUI);
  27329. this._rootElement.removeChild(this._globalDiv);
  27330. this._scene.forceShowBoundingBoxes = false;
  27331. this._scene.forceWireframe = false;
  27332. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27333. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27334. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27335. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27336. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27337. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27338. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27339. BABYLON.StandardMaterial.LightmapEnabled = true;
  27340. this._scene.shadowsEnabled = true;
  27341. this._scene.particlesEnabled = true;
  27342. this._scene.postProcessesEnabled = true;
  27343. this._scene.collisionsEnabled = true;
  27344. this._scene.lightsEnabled = true;
  27345. this._scene.texturesEnabled = true;
  27346. this._scene.lensFlaresEnabled = true;
  27347. this._scene.proceduralTexturesEnabled = true;
  27348. this._scene.renderTargetsEnabled = true;
  27349. this._scene.probesEnabled = true;
  27350. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27351. };
  27352. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  27353. if (showUI === void 0) { showUI = true; }
  27354. if (camera === void 0) { camera = null; }
  27355. if (rootElement === void 0) { rootElement = null; }
  27356. if (this._enabled) {
  27357. return;
  27358. }
  27359. this._enabled = true;
  27360. if (camera) {
  27361. this._camera = camera;
  27362. }
  27363. else {
  27364. this._camera = this._scene.activeCamera;
  27365. }
  27366. this._showUI = showUI;
  27367. var engine = this._scene.getEngine();
  27368. this._globalDiv = document.createElement("div");
  27369. this._rootElement = rootElement || document.body;
  27370. this._rootElement.appendChild(this._globalDiv);
  27371. this._generateDOMelements();
  27372. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27373. this._syncPositions();
  27374. this._scene.registerBeforeRender(this._syncData);
  27375. this._scene.registerAfterRender(this._syncUI);
  27376. };
  27377. DebugLayer.prototype._clearLabels = function () {
  27378. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27379. for (var index = 0; index < this._scene.meshes.length; index++) {
  27380. var mesh = this._scene.meshes[index];
  27381. mesh.renderOverlay = false;
  27382. }
  27383. };
  27384. DebugLayer.prototype._generateheader = function (root, text) {
  27385. var header = document.createElement("div");
  27386. header.innerHTML = text + "&nbsp;";
  27387. header.style.textAlign = "right";
  27388. header.style.width = "100%";
  27389. header.style.color = "white";
  27390. header.style.backgroundColor = "Black";
  27391. header.style.padding = "5px 5px 4px 0px";
  27392. header.style.marginLeft = "-5px";
  27393. header.style.fontWeight = "bold";
  27394. root.appendChild(header);
  27395. };
  27396. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27397. var label = document.createElement("label");
  27398. label.innerHTML = title;
  27399. label.style.color = color;
  27400. root.appendChild(label);
  27401. root.appendChild(document.createElement("br"));
  27402. };
  27403. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27404. if (tag === void 0) { tag = null; }
  27405. var label = document.createElement("label");
  27406. var boundingBoxesCheckbox = document.createElement("input");
  27407. boundingBoxesCheckbox.type = "checkbox";
  27408. boundingBoxesCheckbox.checked = initialState;
  27409. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27410. task(evt.target, tag);
  27411. });
  27412. label.appendChild(boundingBoxesCheckbox);
  27413. var container = document.createElement("span");
  27414. var leftPart = document.createElement("span");
  27415. var rightPart = document.createElement("span");
  27416. rightPart.style.cssFloat = "right";
  27417. leftPart.innerHTML = leftTitle;
  27418. rightPart.innerHTML = rightTitle;
  27419. rightPart.style.fontSize = "12px";
  27420. rightPart.style.maxWidth = "200px";
  27421. container.appendChild(leftPart);
  27422. container.appendChild(rightPart);
  27423. label.appendChild(container);
  27424. root.appendChild(label);
  27425. root.appendChild(document.createElement("br"));
  27426. };
  27427. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27428. if (tag === void 0) { tag = null; }
  27429. var label = document.createElement("label");
  27430. var checkBox = document.createElement("input");
  27431. checkBox.type = "checkbox";
  27432. checkBox.checked = initialState;
  27433. checkBox.addEventListener("change", function (evt) {
  27434. task(evt.target, tag);
  27435. });
  27436. label.appendChild(checkBox);
  27437. label.appendChild(document.createTextNode(title));
  27438. root.appendChild(label);
  27439. root.appendChild(document.createElement("br"));
  27440. };
  27441. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27442. if (tag === void 0) { tag = null; }
  27443. var button = document.createElement("button");
  27444. button.innerHTML = title;
  27445. button.style.height = "24px";
  27446. button.style.width = "150px";
  27447. button.style.marginBottom = "5px";
  27448. button.style.color = "#444444";
  27449. button.style.border = "1px solid white";
  27450. button.className = "debugLayerButton";
  27451. button.addEventListener("click", function (evt) {
  27452. task(evt.target, tag);
  27453. });
  27454. root.appendChild(button);
  27455. root.appendChild(document.createElement("br"));
  27456. };
  27457. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27458. if (tag === void 0) { tag = null; }
  27459. var label = document.createElement("label");
  27460. var boundingBoxesRadio = document.createElement("input");
  27461. boundingBoxesRadio.type = "radio";
  27462. boundingBoxesRadio.name = name;
  27463. boundingBoxesRadio.checked = initialState;
  27464. boundingBoxesRadio.addEventListener("change", function (evt) {
  27465. task(evt.target, tag);
  27466. });
  27467. label.appendChild(boundingBoxesRadio);
  27468. label.appendChild(document.createTextNode(title));
  27469. root.appendChild(label);
  27470. root.appendChild(document.createElement("br"));
  27471. };
  27472. DebugLayer.prototype._generateDOMelements = function () {
  27473. var _this = this;
  27474. this._globalDiv.id = "DebugLayer";
  27475. this._globalDiv.style.position = "absolute";
  27476. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27477. this._globalDiv.style.fontSize = "14px";
  27478. this._globalDiv.style.color = "white";
  27479. // Drawing canvas
  27480. this._drawingCanvas = document.createElement("canvas");
  27481. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27482. this._drawingCanvas.style.position = "absolute";
  27483. this._drawingCanvas.style.pointerEvents = "none";
  27484. this._drawingCanvas.style.backgroundColor = "transparent";
  27485. this._drawingContext = this._drawingCanvas.getContext("2d");
  27486. this._globalDiv.appendChild(this._drawingCanvas);
  27487. if (this._showUI) {
  27488. var background = "rgba(128, 128, 128, 0.4)";
  27489. var border = "rgb(180, 180, 180) solid 1px";
  27490. // Stats
  27491. this._statsDiv = document.createElement("div");
  27492. this._statsDiv.id = "DebugLayerStats";
  27493. this._statsDiv.style.border = border;
  27494. this._statsDiv.style.position = "absolute";
  27495. this._statsDiv.style.background = background;
  27496. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27497. this._generateheader(this._statsDiv, "STATISTICS");
  27498. this._statsSubsetDiv = document.createElement("div");
  27499. this._statsSubsetDiv.style.paddingTop = "5px";
  27500. this._statsSubsetDiv.style.paddingBottom = "5px";
  27501. this._statsSubsetDiv.style.overflowY = "auto";
  27502. this._statsDiv.appendChild(this._statsSubsetDiv);
  27503. // Tree
  27504. this._treeDiv = document.createElement("div");
  27505. this._treeDiv.id = "DebugLayerTree";
  27506. this._treeDiv.style.border = border;
  27507. this._treeDiv.style.position = "absolute";
  27508. this._treeDiv.style.background = background;
  27509. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27510. this._treeDiv.style.display = "none";
  27511. this._generateheader(this._treeDiv, "MESHES TREE");
  27512. this._treeSubsetDiv = document.createElement("div");
  27513. this._treeSubsetDiv.style.paddingTop = "5px";
  27514. this._treeSubsetDiv.style.paddingRight = "5px";
  27515. this._treeSubsetDiv.style.overflowY = "auto";
  27516. this._treeSubsetDiv.style.maxHeight = "300px";
  27517. this._treeDiv.appendChild(this._treeSubsetDiv);
  27518. this._needToRefreshMeshesTree = true;
  27519. // Logs
  27520. this._logDiv = document.createElement("div");
  27521. this._logDiv.style.border = border;
  27522. this._logDiv.id = "DebugLayerLogs";
  27523. this._logDiv.style.position = "absolute";
  27524. this._logDiv.style.background = background;
  27525. this._logDiv.style.padding = "0px 0px 0px 5px";
  27526. this._logDiv.style.display = "none";
  27527. this._generateheader(this._logDiv, "LOGS");
  27528. this._logSubsetDiv = document.createElement("div");
  27529. this._logSubsetDiv.style.height = "127px";
  27530. this._logSubsetDiv.style.paddingTop = "5px";
  27531. this._logSubsetDiv.style.overflowY = "auto";
  27532. this._logSubsetDiv.style.fontSize = "12px";
  27533. this._logSubsetDiv.style.fontFamily = "consolas";
  27534. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27535. this._logDiv.appendChild(this._logSubsetDiv);
  27536. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27537. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27538. };
  27539. // Options
  27540. this._optionsDiv = document.createElement("div");
  27541. this._optionsDiv.id = "DebugLayerOptions";
  27542. this._optionsDiv.style.border = border;
  27543. this._optionsDiv.style.position = "absolute";
  27544. this._optionsDiv.style.background = background;
  27545. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27546. this._optionsDiv.style.overflowY = "auto";
  27547. this._generateheader(this._optionsDiv, "OPTIONS");
  27548. this._optionsSubsetDiv = document.createElement("div");
  27549. this._optionsSubsetDiv.style.paddingTop = "5px";
  27550. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27551. this._optionsSubsetDiv.style.overflowY = "auto";
  27552. this._optionsSubsetDiv.style.maxHeight = "200px";
  27553. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27554. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27555. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27556. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27557. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27558. _this._displayTree = element.checked;
  27559. _this._needToRefreshMeshesTree = true;
  27560. });
  27561. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27562. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27563. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27564. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27565. _this._labelsEnabled = element.checked;
  27566. if (!_this._labelsEnabled) {
  27567. _this._clearLabels();
  27568. }
  27569. });
  27570. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27571. if (element.checked) {
  27572. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27573. }
  27574. else {
  27575. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27576. }
  27577. });
  27578. ;
  27579. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27580. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27581. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27582. if (element.checked) {
  27583. _this._scene.forceWireframe = false;
  27584. _this._scene.forcePointsCloud = false;
  27585. }
  27586. });
  27587. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27588. if (element.checked) {
  27589. _this._scene.forceWireframe = true;
  27590. _this._scene.forcePointsCloud = false;
  27591. }
  27592. });
  27593. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27594. if (element.checked) {
  27595. _this._scene.forceWireframe = false;
  27596. _this._scene.forcePointsCloud = true;
  27597. }
  27598. });
  27599. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27600. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27601. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27602. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27603. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27604. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27605. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27606. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27607. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27608. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27609. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27610. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27611. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27612. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27613. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27614. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27615. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27616. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27617. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27618. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27619. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27620. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27621. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27622. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27623. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27624. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27625. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27626. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27627. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27628. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27629. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27630. if (element.checked) {
  27631. _this._scene.headphone = true;
  27632. }
  27633. });
  27634. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27635. if (element.checked) {
  27636. _this._scene.headphone = false;
  27637. }
  27638. });
  27639. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27640. _this._scene.audioEnabled = !element.checked;
  27641. });
  27642. }
  27643. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27644. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27645. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27646. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27647. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27648. if (_this._camera) {
  27649. console.log(_this._camera);
  27650. }
  27651. else {
  27652. console.warn("No camera defined, or debug layer created before camera creation!");
  27653. }
  27654. });
  27655. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27656. this._globalDiv.appendChild(this._statsDiv);
  27657. this._globalDiv.appendChild(this._logDiv);
  27658. this._globalDiv.appendChild(this._optionsDiv);
  27659. this._globalDiv.appendChild(this._treeDiv);
  27660. }
  27661. };
  27662. DebugLayer.prototype._displayStats = function () {
  27663. var scene = this._scene;
  27664. var engine = scene.getEngine();
  27665. var glInfo = engine.getGlInfo();
  27666. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27667. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27668. + "<b>Count</b><br>"
  27669. + "Total meshes: " + scene.meshes.length + "<br>"
  27670. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27671. + "Total materials: " + scene.materials.length + "<br>"
  27672. + "Total textures: " + scene.textures.length + "<br>"
  27673. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27674. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27675. + "Active bones: " + scene.getActiveBones() + "<br>"
  27676. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27677. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27678. + "<b>Duration</b><br>"
  27679. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27680. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27681. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27682. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27683. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27684. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27685. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27686. + "</div>"
  27687. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27688. + "<b>Extensions</b><br>"
  27689. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27690. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27691. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27692. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27693. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27694. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27695. + "<b>Caps.</b><br>"
  27696. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27697. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27698. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27699. + "</div><br>"
  27700. + "<b>Info</b><br>"
  27701. + glInfo.version + "<br>"
  27702. + glInfo.renderer + "<br>";
  27703. if (this.customStatsFunction) {
  27704. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27705. }
  27706. };
  27707. return DebugLayer;
  27708. })();
  27709. BABYLON.DebugLayer = DebugLayer;
  27710. })(BABYLON || (BABYLON = {}));
  27711. var BABYLON;
  27712. (function (BABYLON) {
  27713. var DefaultLoadingScreen = (function () {
  27714. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27715. var _this = this;
  27716. if (_loadingText === void 0) { _loadingText = ""; }
  27717. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27718. this._renderingCanvas = _renderingCanvas;
  27719. this._loadingText = _loadingText;
  27720. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27721. // Resize
  27722. this._resizeLoadingUI = function () {
  27723. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27724. _this._loadingDiv.style.position = "absolute";
  27725. _this._loadingDiv.style.left = canvasRect.left + "px";
  27726. _this._loadingDiv.style.top = canvasRect.top + "px";
  27727. _this._loadingDiv.style.width = canvasRect.width + "px";
  27728. _this._loadingDiv.style.height = canvasRect.height + "px";
  27729. };
  27730. }
  27731. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27732. var _this = this;
  27733. this._loadingDiv = document.createElement("div");
  27734. this._loadingDiv.id = "babylonjsLoadingDiv";
  27735. this._loadingDiv.style.opacity = "0";
  27736. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27737. // Loading text
  27738. this._loadingTextDiv = document.createElement("div");
  27739. this._loadingTextDiv.style.position = "absolute";
  27740. this._loadingTextDiv.style.left = "0";
  27741. this._loadingTextDiv.style.top = "50%";
  27742. this._loadingTextDiv.style.marginTop = "80px";
  27743. this._loadingTextDiv.style.width = "100%";
  27744. this._loadingTextDiv.style.height = "20px";
  27745. this._loadingTextDiv.style.fontFamily = "Arial";
  27746. this._loadingTextDiv.style.fontSize = "14px";
  27747. this._loadingTextDiv.style.color = "white";
  27748. this._loadingTextDiv.style.textAlign = "center";
  27749. this._loadingTextDiv.innerHTML = "Loading";
  27750. this._loadingDiv.appendChild(this._loadingTextDiv);
  27751. //set the predefined text
  27752. this._loadingTextDiv.innerHTML = this._loadingText;
  27753. // Loading img
  27754. var imgBack = new Image();
  27755. 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==";
  27756. imgBack.style.position = "absolute";
  27757. imgBack.style.left = "50%";
  27758. imgBack.style.top = "50%";
  27759. imgBack.style.marginLeft = "-50px";
  27760. imgBack.style.marginTop = "-50px";
  27761. imgBack.style.transition = "transform 1.0s ease";
  27762. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27763. var deg = 360;
  27764. var onTransitionEnd = function () {
  27765. deg += 360;
  27766. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27767. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27768. };
  27769. imgBack.addEventListener("transitionend", onTransitionEnd);
  27770. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27771. this._loadingDiv.appendChild(imgBack);
  27772. // front image
  27773. var imgFront = new Image();
  27774. 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=";
  27775. imgFront.style.position = "absolute";
  27776. imgFront.style.left = "50%";
  27777. imgFront.style.top = "50%";
  27778. imgFront.style.marginLeft = "-50px";
  27779. imgFront.style.marginTop = "-50px";
  27780. this._loadingDiv.appendChild(imgFront);
  27781. this._resizeLoadingUI();
  27782. window.addEventListener("resize", this._resizeLoadingUI);
  27783. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27784. document.body.appendChild(this._loadingDiv);
  27785. setTimeout(function () {
  27786. _this._loadingDiv.style.opacity = "1";
  27787. imgBack.style.transform = "rotateZ(360deg)";
  27788. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27789. }, 0);
  27790. };
  27791. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27792. var _this = this;
  27793. if (!this._loadingDiv) {
  27794. return;
  27795. }
  27796. var onTransitionEnd = function () {
  27797. if (!_this._loadingDiv) {
  27798. return;
  27799. }
  27800. document.body.removeChild(_this._loadingDiv);
  27801. window.removeEventListener("resize", _this._resizeLoadingUI);
  27802. _this._loadingDiv = null;
  27803. };
  27804. this._loadingDiv.style.opacity = "0";
  27805. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27806. };
  27807. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27808. set: function (text) {
  27809. this._loadingText = text;
  27810. if (this._loadingTextDiv) {
  27811. this._loadingTextDiv.innerHTML = this._loadingText;
  27812. }
  27813. },
  27814. enumerable: true,
  27815. configurable: true
  27816. });
  27817. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27818. get: function () {
  27819. return this._loadingDivBackgroundColor;
  27820. },
  27821. set: function (color) {
  27822. this._loadingDivBackgroundColor = color;
  27823. if (!this._loadingDiv) {
  27824. return;
  27825. }
  27826. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27827. },
  27828. enumerable: true,
  27829. configurable: true
  27830. });
  27831. return DefaultLoadingScreen;
  27832. })();
  27833. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27834. })(BABYLON || (BABYLON = {}));
  27835. var BABYLON;
  27836. (function (BABYLON) {
  27837. var SIMDVector3 = (function () {
  27838. function SIMDVector3() {
  27839. }
  27840. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27841. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27842. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27843. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27844. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27845. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27846. 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));
  27847. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27848. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27849. };
  27850. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27851. var v0 = SIMD.float32x4.splat(x);
  27852. var v1 = SIMD.float32x4.splat(y);
  27853. var v2 = SIMD.float32x4.splat(z);
  27854. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27855. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27856. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27857. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27858. 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));
  27859. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27860. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27861. };
  27862. return SIMDVector3;
  27863. })();
  27864. BABYLON.SIMDVector3 = SIMDVector3;
  27865. var SIMDMatrix = (function () {
  27866. function SIMDMatrix() {
  27867. }
  27868. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27869. if (offset === void 0) { offset = 0; }
  27870. var tm = this.m;
  27871. var om = other.m;
  27872. var om0 = SIMD.float32x4.load(om, 0);
  27873. var om1 = SIMD.float32x4.load(om, 4);
  27874. var om2 = SIMD.float32x4.load(om, 8);
  27875. var om3 = SIMD.float32x4.load(om, 12);
  27876. var tm0 = SIMD.float32x4.load(tm, 0);
  27877. 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)))));
  27878. var tm1 = SIMD.float32x4.load(tm, 4);
  27879. 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)))));
  27880. var tm2 = SIMD.float32x4.load(tm, 8);
  27881. 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)))));
  27882. var tm3 = SIMD.float32x4.load(tm, 12);
  27883. 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)))));
  27884. };
  27885. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27886. var src = this.m;
  27887. var dest = other.m;
  27888. var row0, row1, row2, row3;
  27889. var tmp1;
  27890. var minor0, minor1, minor2, minor3;
  27891. var det;
  27892. // Load the 4 rows
  27893. var src0 = SIMD.float32x4.load(src, 0);
  27894. var src1 = SIMD.float32x4.load(src, 4);
  27895. var src2 = SIMD.float32x4.load(src, 8);
  27896. var src3 = SIMD.float32x4.load(src, 12);
  27897. // Transpose the source matrix. Sort of. Not a true transpose operation
  27898. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27899. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27900. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27901. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27902. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27903. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27904. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27905. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27906. // This is a true transposition, but it will lead to an incorrect result
  27907. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27908. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27909. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27910. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27911. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27912. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27913. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27914. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27915. // ----
  27916. tmp1 = SIMD.float32x4.mul(row2, row3);
  27917. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27918. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27919. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27920. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27921. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27922. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27923. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27924. // ----
  27925. tmp1 = SIMD.float32x4.mul(row1, row2);
  27926. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27927. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27928. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27929. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27930. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27931. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27932. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27933. // ----
  27934. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27935. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27936. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27937. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27938. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27939. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27940. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27941. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27942. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27943. // ----
  27944. tmp1 = SIMD.float32x4.mul(row0, row1);
  27945. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27946. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27947. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27948. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27949. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27950. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27951. // ----
  27952. tmp1 = SIMD.float32x4.mul(row0, row3);
  27953. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27954. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27955. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27956. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27957. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27958. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27959. // ----
  27960. tmp1 = SIMD.float32x4.mul(row0, row2);
  27961. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27962. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27963. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27964. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27965. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27966. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27967. // Compute determinant
  27968. det = SIMD.float32x4.mul(row0, minor0);
  27969. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27970. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27971. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27972. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27973. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27974. // These shuffles aren't necessary if the faulty transposition is done
  27975. // up at the top of this function.
  27976. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27977. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27978. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27979. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27980. // Compute final values by multiplying with 1/det
  27981. minor0 = SIMD.float32x4.mul(det, minor0);
  27982. minor1 = SIMD.float32x4.mul(det, minor1);
  27983. minor2 = SIMD.float32x4.mul(det, minor2);
  27984. minor3 = SIMD.float32x4.mul(det, minor3);
  27985. SIMD.float32x4.store(dest, 0, minor0);
  27986. SIMD.float32x4.store(dest, 4, minor1);
  27987. SIMD.float32x4.store(dest, 8, minor2);
  27988. SIMD.float32x4.store(dest, 12, minor3);
  27989. return this;
  27990. };
  27991. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27992. var out = result.m;
  27993. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27994. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27995. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27996. // cc.kmVec3Subtract(f, pCenter, pEye);
  27997. var f = SIMD.float32x4.sub(center, eye);
  27998. // cc.kmVec3Normalize(f, f);
  27999. var tmp = SIMD.float32x4.mul(f, f);
  28000. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28001. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28002. // cc.kmVec3Assign(up, pUp);
  28003. // cc.kmVec3Normalize(up, up);
  28004. tmp = SIMD.float32x4.mul(up, up);
  28005. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28006. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28007. // cc.kmVec3Cross(s, f, up);
  28008. 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)));
  28009. // cc.kmVec3Normalize(s, s);
  28010. tmp = SIMD.float32x4.mul(s, s);
  28011. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28012. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28013. // cc.kmVec3Cross(u, s, f);
  28014. 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)));
  28015. // cc.kmVec3Normalize(s, s);
  28016. tmp = SIMD.float32x4.mul(s, s);
  28017. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28018. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28019. var zero = SIMD.float32x4.splat(0.0);
  28020. s = SIMD.float32x4.neg(s);
  28021. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28022. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28023. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28024. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28025. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28026. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28027. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28028. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28029. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28030. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28031. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28032. var b3 = SIMD.float32x4.neg(eye);
  28033. b3 = SIMD.float32x4.withW(b3, 1.0);
  28034. 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)))));
  28035. 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)))));
  28036. 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)))));
  28037. 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)))));
  28038. };
  28039. return SIMDMatrix;
  28040. })();
  28041. BABYLON.SIMDMatrix = SIMDMatrix;
  28042. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28043. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28044. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28045. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28046. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28047. var SIMDHelper = (function () {
  28048. function SIMDHelper() {
  28049. }
  28050. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28051. get: function () {
  28052. return SIMDHelper._isEnabled;
  28053. },
  28054. enumerable: true,
  28055. configurable: true
  28056. });
  28057. SIMDHelper.DisableSIMD = function () {
  28058. // Replace functions
  28059. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28060. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28061. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28062. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28063. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28064. SIMDHelper._isEnabled = false;
  28065. };
  28066. SIMDHelper.EnableSIMD = function () {
  28067. if (window.SIMD === undefined) {
  28068. return;
  28069. }
  28070. // Replace functions
  28071. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28072. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28073. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28074. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28075. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28076. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28077. get: function () { return this._data[0]; },
  28078. set: function (value) {
  28079. if (!this._data) {
  28080. this._data = new Float32Array(3);
  28081. }
  28082. this._data[0] = value;
  28083. }
  28084. });
  28085. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28086. get: function () { return this._data[1]; },
  28087. set: function (value) {
  28088. this._data[1] = value;
  28089. }
  28090. });
  28091. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28092. get: function () { return this._data[2]; },
  28093. set: function (value) {
  28094. this._data[2] = value;
  28095. }
  28096. });
  28097. SIMDHelper._isEnabled = true;
  28098. };
  28099. SIMDHelper._isEnabled = false;
  28100. return SIMDHelper;
  28101. })();
  28102. BABYLON.SIMDHelper = SIMDHelper;
  28103. })(BABYLON || (BABYLON = {}));
  28104. var BABYLON;
  28105. (function (BABYLON) {
  28106. var ShaderMaterial = (function (_super) {
  28107. __extends(ShaderMaterial, _super);
  28108. function ShaderMaterial(name, scene, shaderPath, options) {
  28109. _super.call(this, name, scene);
  28110. this._textures = new Array();
  28111. this._floats = new Array();
  28112. this._floatsArrays = {};
  28113. this._colors3 = new Array();
  28114. this._colors4 = new Array();
  28115. this._vectors2 = new Array();
  28116. this._vectors3 = new Array();
  28117. this._vectors4 = new Array();
  28118. this._matrices = new Array();
  28119. this._matrices3x3 = new Array();
  28120. this._matrices2x2 = new Array();
  28121. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28122. this._shaderPath = shaderPath;
  28123. options.needAlphaBlending = options.needAlphaBlending || false;
  28124. options.needAlphaTesting = options.needAlphaTesting || false;
  28125. options.attributes = options.attributes || ["position", "normal", "uv"];
  28126. options.uniforms = options.uniforms || ["worldViewProjection"];
  28127. options.samplers = options.samplers || [];
  28128. options.defines = options.defines || [];
  28129. this._options = options;
  28130. }
  28131. ShaderMaterial.prototype.needAlphaBlending = function () {
  28132. return this._options.needAlphaBlending;
  28133. };
  28134. ShaderMaterial.prototype.needAlphaTesting = function () {
  28135. return this._options.needAlphaTesting;
  28136. };
  28137. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28138. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28139. this._options.uniforms.push(uniformName);
  28140. }
  28141. };
  28142. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28143. if (this._options.samplers.indexOf(name) === -1) {
  28144. this._options.samplers.push(name);
  28145. }
  28146. this._textures[name] = texture;
  28147. return this;
  28148. };
  28149. ShaderMaterial.prototype.setFloat = function (name, value) {
  28150. this._checkUniform(name);
  28151. this._floats[name] = value;
  28152. return this;
  28153. };
  28154. ShaderMaterial.prototype.setFloats = function (name, value) {
  28155. this._checkUniform(name);
  28156. this._floatsArrays[name] = value;
  28157. return this;
  28158. };
  28159. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28160. this._checkUniform(name);
  28161. this._colors3[name] = value;
  28162. return this;
  28163. };
  28164. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28165. this._checkUniform(name);
  28166. this._colors4[name] = value;
  28167. return this;
  28168. };
  28169. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28170. this._checkUniform(name);
  28171. this._vectors2[name] = value;
  28172. return this;
  28173. };
  28174. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28175. this._checkUniform(name);
  28176. this._vectors3[name] = value;
  28177. return this;
  28178. };
  28179. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28180. this._checkUniform(name);
  28181. this._vectors4[name] = value;
  28182. return this;
  28183. };
  28184. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28185. this._checkUniform(name);
  28186. this._matrices[name] = value;
  28187. return this;
  28188. };
  28189. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28190. this._checkUniform(name);
  28191. this._matrices3x3[name] = value;
  28192. return this;
  28193. };
  28194. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28195. this._checkUniform(name);
  28196. this._matrices2x2[name] = value;
  28197. return this;
  28198. };
  28199. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28200. var scene = this.getScene();
  28201. var engine = scene.getEngine();
  28202. if (!this.checkReadyOnEveryCall) {
  28203. if (this._renderId === scene.getRenderId()) {
  28204. return true;
  28205. }
  28206. }
  28207. // Instances
  28208. var defines = [];
  28209. var fallbacks = new BABYLON.EffectFallbacks();
  28210. if (useInstances) {
  28211. defines.push("#define INSTANCES");
  28212. }
  28213. for (var index = 0; index < this._options.defines.length; index++) {
  28214. defines.push(this._options.defines[index]);
  28215. }
  28216. // Bones
  28217. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28218. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28219. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28220. fallbacks.addCPUSkinningFallback(0, mesh);
  28221. }
  28222. // Alpha test
  28223. if (engine.getAlphaTesting()) {
  28224. defines.push("#define ALPHATEST");
  28225. }
  28226. var previousEffect = this._effect;
  28227. var join = defines.join("\n");
  28228. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28229. if (!this._effect.isReady()) {
  28230. return false;
  28231. }
  28232. if (previousEffect !== this._effect) {
  28233. scene.resetCachedMaterial();
  28234. }
  28235. this._renderId = scene.getRenderId();
  28236. return true;
  28237. };
  28238. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28239. var scene = this.getScene();
  28240. if (this._options.uniforms.indexOf("world") !== -1) {
  28241. this._effect.setMatrix("world", world);
  28242. }
  28243. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28244. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28245. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28246. }
  28247. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28248. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28249. }
  28250. };
  28251. ShaderMaterial.prototype.bind = function (world, mesh) {
  28252. // Std values
  28253. this.bindOnlyWorldMatrix(world);
  28254. if (this.getScene().getCachedMaterial() !== this) {
  28255. if (this._options.uniforms.indexOf("view") !== -1) {
  28256. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28257. }
  28258. if (this._options.uniforms.indexOf("projection") !== -1) {
  28259. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28260. }
  28261. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28262. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28263. }
  28264. // Bones
  28265. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28266. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28267. }
  28268. // Texture
  28269. for (var name in this._textures) {
  28270. this._effect.setTexture(name, this._textures[name]);
  28271. }
  28272. // Float
  28273. for (name in this._floats) {
  28274. this._effect.setFloat(name, this._floats[name]);
  28275. }
  28276. // Float s
  28277. for (name in this._floatsArrays) {
  28278. this._effect.setArray(name, this._floatsArrays[name]);
  28279. }
  28280. // Color3
  28281. for (name in this._colors3) {
  28282. this._effect.setColor3(name, this._colors3[name]);
  28283. }
  28284. // Color4
  28285. for (name in this._colors4) {
  28286. var color = this._colors4[name];
  28287. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28288. }
  28289. // Vector2
  28290. for (name in this._vectors2) {
  28291. this._effect.setVector2(name, this._vectors2[name]);
  28292. }
  28293. // Vector3
  28294. for (name in this._vectors3) {
  28295. this._effect.setVector3(name, this._vectors3[name]);
  28296. }
  28297. // Vector4
  28298. for (name in this._vectors4) {
  28299. this._effect.setVector4(name, this._vectors4[name]);
  28300. }
  28301. // Matrix
  28302. for (name in this._matrices) {
  28303. this._effect.setMatrix(name, this._matrices[name]);
  28304. }
  28305. // Matrix 3x3
  28306. for (name in this._matrices3x3) {
  28307. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28308. }
  28309. // Matrix 2x2
  28310. for (name in this._matrices2x2) {
  28311. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28312. }
  28313. }
  28314. _super.prototype.bind.call(this, world, mesh);
  28315. };
  28316. ShaderMaterial.prototype.clone = function (name) {
  28317. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28318. return newShaderMaterial;
  28319. };
  28320. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28321. for (var name in this._textures) {
  28322. this._textures[name].dispose();
  28323. }
  28324. this._textures = [];
  28325. _super.prototype.dispose.call(this, forceDisposeEffect);
  28326. };
  28327. return ShaderMaterial;
  28328. })(BABYLON.Material);
  28329. BABYLON.ShaderMaterial = ShaderMaterial;
  28330. })(BABYLON || (BABYLON = {}));
  28331. var BABYLON;
  28332. (function (BABYLON) {
  28333. var Internals;
  28334. (function (Internals) {
  28335. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  28336. // All values and structures referenced from:
  28337. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  28338. var DDS_MAGIC = 0x20534444;
  28339. 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;
  28340. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  28341. 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;
  28342. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  28343. function FourCCToInt32(value) {
  28344. return value.charCodeAt(0) +
  28345. (value.charCodeAt(1) << 8) +
  28346. (value.charCodeAt(2) << 16) +
  28347. (value.charCodeAt(3) << 24);
  28348. }
  28349. function Int32ToFourCC(value) {
  28350. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  28351. }
  28352. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  28353. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  28354. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  28355. var headerLengthInt = 31; // The header length in 32 bit ints
  28356. // Offsets into the header array
  28357. var off_magic = 0;
  28358. var off_size = 1;
  28359. var off_flags = 2;
  28360. var off_height = 3;
  28361. var off_width = 4;
  28362. var off_mipmapCount = 7;
  28363. var off_pfFlags = 20;
  28364. var off_pfFourCC = 21;
  28365. var off_RGBbpp = 22;
  28366. var off_RMask = 23;
  28367. var off_GMask = 24;
  28368. var off_BMask = 25;
  28369. var off_AMask = 26;
  28370. var off_caps1 = 27;
  28371. var off_caps2 = 28;
  28372. ;
  28373. var DDSTools = (function () {
  28374. function DDSTools() {
  28375. }
  28376. DDSTools.GetDDSInfo = function (arrayBuffer) {
  28377. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  28378. var mipmapCount = 1;
  28379. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  28380. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28381. }
  28382. return {
  28383. width: header[off_width],
  28384. height: header[off_height],
  28385. mipmapCount: mipmapCount,
  28386. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28387. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28388. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28389. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28390. };
  28391. };
  28392. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28393. var byteArray = new Uint8Array(dataLength);
  28394. var srcData = new Uint8Array(arrayBuffer);
  28395. var index = 0;
  28396. for (var y = height - 1; y >= 0; y--) {
  28397. for (var x = 0; x < width; x++) {
  28398. var srcPos = dataOffset + (x + y * width) * 4;
  28399. byteArray[index + 2] = srcData[srcPos];
  28400. byteArray[index + 1] = srcData[srcPos + 1];
  28401. byteArray[index] = srcData[srcPos + 2];
  28402. byteArray[index + 3] = srcData[srcPos + 3];
  28403. index += 4;
  28404. }
  28405. }
  28406. return byteArray;
  28407. };
  28408. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28409. var byteArray = new Uint8Array(dataLength);
  28410. var srcData = new Uint8Array(arrayBuffer);
  28411. var index = 0;
  28412. for (var y = height - 1; y >= 0; y--) {
  28413. for (var x = 0; x < width; x++) {
  28414. var srcPos = dataOffset + (x + y * width) * 3;
  28415. byteArray[index + 2] = srcData[srcPos];
  28416. byteArray[index + 1] = srcData[srcPos + 1];
  28417. byteArray[index] = srcData[srcPos + 2];
  28418. index += 3;
  28419. }
  28420. }
  28421. return byteArray;
  28422. };
  28423. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28424. var byteArray = new Uint8Array(dataLength);
  28425. var srcData = new Uint8Array(arrayBuffer);
  28426. var index = 0;
  28427. for (var y = height - 1; y >= 0; y--) {
  28428. for (var x = 0; x < width; x++) {
  28429. var srcPos = dataOffset + (x + y * width);
  28430. byteArray[index] = srcData[srcPos];
  28431. index++;
  28432. }
  28433. }
  28434. return byteArray;
  28435. };
  28436. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28437. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28438. if (header[off_magic] != DDS_MAGIC) {
  28439. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28440. return;
  28441. }
  28442. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28443. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28444. return;
  28445. }
  28446. if (info.isFourCC) {
  28447. fourCC = header[off_pfFourCC];
  28448. switch (fourCC) {
  28449. case FOURCC_DXT1:
  28450. blockBytes = 8;
  28451. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28452. break;
  28453. case FOURCC_DXT3:
  28454. blockBytes = 16;
  28455. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28456. break;
  28457. case FOURCC_DXT5:
  28458. blockBytes = 16;
  28459. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28460. break;
  28461. default:
  28462. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28463. return;
  28464. }
  28465. }
  28466. mipmapCount = 1;
  28467. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28468. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28469. }
  28470. var bpp = header[off_RGBbpp];
  28471. for (var face = 0; face < faces; face++) {
  28472. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28473. width = header[off_width];
  28474. height = header[off_height];
  28475. dataOffset = header[off_size] + 4;
  28476. for (i = 0; i < mipmapCount; ++i) {
  28477. if (info.isRGB) {
  28478. if (bpp === 24) {
  28479. dataLength = width * height * 3;
  28480. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28481. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28482. }
  28483. else {
  28484. dataLength = width * height * 4;
  28485. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28486. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28487. }
  28488. }
  28489. else if (info.isLuminance) {
  28490. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28491. var unpaddedRowSize = width;
  28492. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28493. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28494. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28495. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28496. }
  28497. else {
  28498. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28499. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28500. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28501. }
  28502. dataOffset += dataLength;
  28503. width *= 0.5;
  28504. height *= 0.5;
  28505. width = Math.max(1.0, width);
  28506. height = Math.max(1.0, height);
  28507. }
  28508. }
  28509. };
  28510. return DDSTools;
  28511. })();
  28512. Internals.DDSTools = DDSTools;
  28513. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28514. })(BABYLON || (BABYLON = {}));
  28515. var BABYLON;
  28516. (function (BABYLON) {
  28517. var CannonJSPlugin = (function () {
  28518. function CannonJSPlugin() {
  28519. this._registeredMeshes = [];
  28520. this._physicsMaterials = [];
  28521. this.name = "cannon";
  28522. this.updateBodyPosition = function (mesh) {
  28523. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28524. var registeredMesh = this._registeredMeshes[index];
  28525. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28526. var body = registeredMesh.body;
  28527. var center = mesh.getBoundingInfo().boundingBox.center;
  28528. body.position.set(center.x, center.y, center.z);
  28529. body.quaternion.copy(mesh.rotationQuaternion);
  28530. if (registeredMesh.deltaRotation) {
  28531. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28532. body.quaternion = body.quaternion.mult(tmpQ);
  28533. }
  28534. if (registeredMesh.heightmap) {
  28535. //calculate the correct body position:
  28536. var rotationQuaternion = mesh.rotationQuaternion;
  28537. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28538. mesh.computeWorldMatrix(true);
  28539. //get original center with no rotation
  28540. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28541. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28542. //rotation is back
  28543. mesh.rotationQuaternion = rotationQuaternion;
  28544. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28545. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28546. mesh.setPivotMatrix(p);
  28547. mesh.computeWorldMatrix(true);
  28548. //calculate the translation
  28549. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28550. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28551. //add it inverted to the delta
  28552. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28553. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28554. mesh.setPivotMatrix(oldPivot);
  28555. mesh.computeWorldMatrix(true);
  28556. }
  28557. return;
  28558. }
  28559. }
  28560. };
  28561. }
  28562. CannonJSPlugin.prototype.initialize = function (iterations) {
  28563. if (iterations === void 0) { iterations = 10; }
  28564. this._world = new CANNON.World();
  28565. this._world.broadphase = new CANNON.NaiveBroadphase();
  28566. this._world.solver.iterations = iterations;
  28567. };
  28568. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28569. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28570. };
  28571. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28572. var _this = this;
  28573. this._world.step(delta);
  28574. this._registeredMeshes.forEach(function (registeredMesh) {
  28575. // Body position
  28576. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28577. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28578. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28579. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28580. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28581. if (registeredMesh.deltaRotation) {
  28582. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28583. }
  28584. //is the physics collision callback is set?
  28585. if (registeredMesh.mesh.onPhysicsCollide) {
  28586. if (!registeredMesh.collisionFunction) {
  28587. registeredMesh.collisionFunction = function (e) {
  28588. //find the mesh that collided with the registered mesh
  28589. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28590. if (_this._registeredMeshes[idx].body == e.body) {
  28591. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28592. }
  28593. }
  28594. };
  28595. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28596. }
  28597. }
  28598. else {
  28599. //unregister, in case the function was removed for some reason
  28600. if (registeredMesh.collisionFunction) {
  28601. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28602. }
  28603. }
  28604. });
  28605. };
  28606. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28607. this._gravity = gravity;
  28608. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28609. };
  28610. CannonJSPlugin.prototype.getGravity = function () {
  28611. return this._gravity;
  28612. };
  28613. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28614. this.unregisterMesh(mesh);
  28615. if (!mesh.rotationQuaternion) {
  28616. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28617. }
  28618. mesh.computeWorldMatrix(true);
  28619. var shape = this._createShape(mesh, impostor);
  28620. return this._createRigidBodyFromShape(shape, mesh, options);
  28621. };
  28622. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28623. //get the correct bounding box
  28624. var oldQuaternion = mesh.rotationQuaternion;
  28625. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28626. mesh.computeWorldMatrix(true);
  28627. var returnValue;
  28628. switch (impostor) {
  28629. case BABYLON.PhysicsEngine.SphereImpostor:
  28630. var bbox = mesh.getBoundingInfo().boundingBox;
  28631. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28632. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28633. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28634. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28635. break;
  28636. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28637. case BABYLON.PhysicsEngine.CylinderImpostor:
  28638. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28639. case BABYLON.PhysicsEngine.BoxImpostor:
  28640. bbox = mesh.getBoundingInfo().boundingBox;
  28641. var min = bbox.minimumWorld;
  28642. var max = bbox.maximumWorld;
  28643. var box = max.subtract(min).scale(0.5);
  28644. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28645. break;
  28646. case BABYLON.PhysicsEngine.PlaneImpostor:
  28647. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28648. returnValue = new CANNON.Plane();
  28649. break;
  28650. case BABYLON.PhysicsEngine.MeshImpostor:
  28651. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28652. var rawFaces = mesh.getIndices();
  28653. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28654. break;
  28655. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28656. returnValue = this._createHeightmap(mesh);
  28657. break;
  28658. }
  28659. mesh.rotationQuaternion = oldQuaternion;
  28660. return returnValue;
  28661. };
  28662. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28663. var verts = [], faces = [];
  28664. mesh.computeWorldMatrix(true);
  28665. //reuse this variable
  28666. var transformed = BABYLON.Vector3.Zero();
  28667. // Get vertices
  28668. for (var i = 0; i < rawVerts.length; i += 3) {
  28669. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28670. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28671. }
  28672. // Get faces
  28673. for (var j = 0; j < rawFaces.length; j += 3) {
  28674. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28675. }
  28676. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28677. return shape;
  28678. };
  28679. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28680. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28681. var matrix = [];
  28682. //For now pointDepth will not be used and will be automatically calculated.
  28683. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28684. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28685. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28686. var elementSize = dim * 2 / arraySize;
  28687. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28688. for (var i = 0; i < pos.length; i = i + 3) {
  28689. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28690. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28691. var y = pos[i + 1] + minY;
  28692. if (!matrix[x]) {
  28693. matrix[x] = [];
  28694. }
  28695. if (!matrix[x][z]) {
  28696. matrix[x][z] = y;
  28697. }
  28698. matrix[x][z] = Math.max(y, matrix[x][z]);
  28699. }
  28700. for (var x = 0; x <= arraySize; ++x) {
  28701. if (!matrix[x]) {
  28702. var loc = 1;
  28703. while (!matrix[(x + loc) % arraySize]) {
  28704. loc++;
  28705. }
  28706. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28707. }
  28708. for (var z = 0; z <= arraySize; ++z) {
  28709. if (!matrix[x][z]) {
  28710. var loc = 1;
  28711. var newValue;
  28712. while (newValue === undefined) {
  28713. newValue = matrix[x][(z + loc++) % arraySize];
  28714. }
  28715. matrix[x][z] = newValue;
  28716. }
  28717. }
  28718. }
  28719. var shape = new CANNON.Heightfield(matrix, {
  28720. elementSize: elementSize
  28721. });
  28722. //For future reference, needed for body transformation
  28723. shape.minY = minY;
  28724. return shape;
  28725. };
  28726. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28727. var index;
  28728. var mat;
  28729. for (index = 0; index < this._physicsMaterials.length; index++) {
  28730. mat = this._physicsMaterials[index];
  28731. if (mat.friction === friction && mat.restitution === restitution) {
  28732. return mat;
  28733. }
  28734. }
  28735. var currentMat = new CANNON.Material("mat");
  28736. this._physicsMaterials.push(currentMat);
  28737. for (index = 0; index < this._physicsMaterials.length; index++) {
  28738. mat = this._physicsMaterials[index];
  28739. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28740. this._world.addContactMaterial(contactMaterial);
  28741. }
  28742. return currentMat;
  28743. };
  28744. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28745. if (!mesh.rotationQuaternion) {
  28746. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28747. }
  28748. // The delta between the mesh position and the mesh bounding box center
  28749. var bbox = mesh.getBoundingInfo().boundingBox;
  28750. var deltaPosition = mesh.position.subtract(bbox.center);
  28751. var deltaRotation;
  28752. var material = this._addMaterial(options.friction, options.restitution);
  28753. var body = new CANNON.Body({
  28754. mass: options.mass,
  28755. material: material,
  28756. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28757. });
  28758. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28759. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28760. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28761. //-90 DEG in X, precalculated
  28762. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28763. body.quaternion = body.quaternion.mult(tmpQ);
  28764. //Invert! (Precalculated, 90 deg in X)
  28765. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28766. }
  28767. //If it is a heightfield, if should be centered.
  28768. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28769. //calculate the correct body position:
  28770. var rotationQuaternion = mesh.rotationQuaternion;
  28771. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28772. mesh.computeWorldMatrix(true);
  28773. //get original center with no rotation
  28774. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28775. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28776. //rotation is back
  28777. mesh.rotationQuaternion = rotationQuaternion;
  28778. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28779. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28780. mesh.setPivotMatrix(p);
  28781. mesh.computeWorldMatrix(true);
  28782. //calculate the translation
  28783. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28784. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28785. //add it inverted to the delta
  28786. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28787. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28788. mesh.setPivotMatrix(oldPivot);
  28789. mesh.computeWorldMatrix(true);
  28790. }
  28791. //add the shape
  28792. body.addShape(shape);
  28793. this._world.add(body);
  28794. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28795. return body;
  28796. };
  28797. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28798. var initialMesh = parts[0].mesh;
  28799. this.unregisterMesh(initialMesh);
  28800. initialMesh.computeWorldMatrix(true);
  28801. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28802. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28803. for (var index = 1; index < parts.length; index++) {
  28804. var mesh = parts[index].mesh;
  28805. mesh.computeWorldMatrix(true);
  28806. var shape = this._createShape(mesh, parts[index].impostor);
  28807. var localPosition = mesh.position;
  28808. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28809. }
  28810. return body;
  28811. };
  28812. CannonJSPlugin.prototype._unbindBody = function (body) {
  28813. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28814. var registeredMesh = this._registeredMeshes[index];
  28815. if (registeredMesh.body === body) {
  28816. this._world.remove(registeredMesh.body);
  28817. registeredMesh.body = null;
  28818. registeredMesh.delta = null;
  28819. registeredMesh.deltaRotation = null;
  28820. }
  28821. }
  28822. };
  28823. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28824. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28825. var registeredMesh = this._registeredMeshes[index];
  28826. if (registeredMesh.mesh === mesh) {
  28827. // Remove body
  28828. if (registeredMesh.body) {
  28829. this._unbindBody(registeredMesh.body);
  28830. }
  28831. this._registeredMeshes.splice(index, 1);
  28832. return;
  28833. }
  28834. }
  28835. };
  28836. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28837. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28838. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28839. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28840. var registeredMesh = this._registeredMeshes[index];
  28841. if (registeredMesh.mesh === mesh) {
  28842. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28843. return;
  28844. }
  28845. }
  28846. };
  28847. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28848. var body1 = null, body2 = null;
  28849. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28850. var registeredMesh = this._registeredMeshes[index];
  28851. if (registeredMesh.mesh === mesh1) {
  28852. body1 = registeredMesh.body;
  28853. }
  28854. else if (registeredMesh.mesh === mesh2) {
  28855. body2 = registeredMesh.body;
  28856. }
  28857. }
  28858. if (!body1 || !body2) {
  28859. return false;
  28860. }
  28861. 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));
  28862. this._world.addConstraint(constraint);
  28863. return true;
  28864. };
  28865. CannonJSPlugin.prototype.dispose = function () {
  28866. while (this._registeredMeshes.length) {
  28867. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28868. }
  28869. };
  28870. CannonJSPlugin.prototype.isSupported = function () {
  28871. return window.CANNON !== undefined;
  28872. };
  28873. CannonJSPlugin.prototype.getWorldObject = function () {
  28874. return this._world;
  28875. };
  28876. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28877. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28878. var registeredMesh = this._registeredMeshes[index];
  28879. if (registeredMesh.mesh === mesh) {
  28880. return registeredMesh.body;
  28881. }
  28882. }
  28883. return null;
  28884. };
  28885. return CannonJSPlugin;
  28886. })();
  28887. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28888. })(BABYLON || (BABYLON = {}));
  28889. var BABYLON;
  28890. (function (BABYLON) {
  28891. var OimoJSPlugin = (function () {
  28892. function OimoJSPlugin() {
  28893. this._registeredMeshes = [];
  28894. this.name = "oimo";
  28895. /**
  28896. * Update the body position according to the mesh position
  28897. * @param mesh
  28898. */
  28899. this.updateBodyPosition = function (mesh) {
  28900. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28901. var registeredMesh = this._registeredMeshes[index];
  28902. var body = registeredMesh.body.body;
  28903. var updated = false;
  28904. var newPosition;
  28905. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28906. mesh.computeWorldMatrix(true);
  28907. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28908. updated = true;
  28909. }
  28910. else if (registeredMesh.mesh.parent === mesh) {
  28911. mesh.computeWorldMatrix(true);
  28912. registeredMesh.mesh.computeWorldMatrix(true);
  28913. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28914. updated = true;
  28915. }
  28916. if (updated) {
  28917. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28918. body.setQuaternion(mesh.rotationQuaternion);
  28919. body.sleeping = false;
  28920. //force Oimo to update the body's position
  28921. body.updatePosition(1);
  28922. }
  28923. }
  28924. };
  28925. }
  28926. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28927. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28928. };
  28929. OimoJSPlugin.prototype.initialize = function (iterations) {
  28930. this._world = new OIMO.World(null, null, iterations);
  28931. this._world.clear();
  28932. };
  28933. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28934. this._gravity = this._world.gravity = gravity;
  28935. };
  28936. OimoJSPlugin.prototype.getGravity = function () {
  28937. return this._gravity;
  28938. };
  28939. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28940. this.unregisterMesh(mesh);
  28941. if (!mesh.rotationQuaternion) {
  28942. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28943. }
  28944. mesh.computeWorldMatrix(true);
  28945. var bbox = mesh.getBoundingInfo().boundingBox;
  28946. // The delta between the mesh position and the mesh bounding box center
  28947. var deltaPosition = mesh.position.subtract(bbox.center);
  28948. //calculate rotation to fit Oimo's needs (Euler...)
  28949. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28950. //get the correct bounding box
  28951. var oldQuaternion = mesh.rotationQuaternion;
  28952. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28953. mesh.computeWorldMatrix(true);
  28954. var bodyConfig = {
  28955. name: mesh.uniqueId,
  28956. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28957. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28958. move: options.mass != 0,
  28959. config: [options.mass, options.friction, options.restitution],
  28960. world: this._world
  28961. };
  28962. // register mesh
  28963. switch (impostor) {
  28964. case BABYLON.PhysicsEngine.SphereImpostor:
  28965. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28966. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28967. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28968. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28969. bodyConfig.type = 'sphere';
  28970. bodyConfig.size = [size];
  28971. break;
  28972. case BABYLON.PhysicsEngine.PlaneImpostor:
  28973. //Oimo "fakes" a cylinder as a box, so why don't we!
  28974. case BABYLON.PhysicsEngine.CylinderImpostor:
  28975. case BABYLON.PhysicsEngine.BoxImpostor:
  28976. var min = bbox.minimumWorld;
  28977. var max = bbox.maximumWorld;
  28978. var box = max.subtract(min);
  28979. var sizeX = this._checkWithEpsilon(box.x);
  28980. var sizeY = this._checkWithEpsilon(box.y);
  28981. var sizeZ = this._checkWithEpsilon(box.z);
  28982. bodyConfig.type = 'box';
  28983. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28984. break;
  28985. }
  28986. var body = new OIMO.Body(bodyConfig);
  28987. //We have to access the rigid body's properties to set the quaternion.
  28988. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28989. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28990. //TEST
  28991. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28992. //update the internal rotation matrix
  28993. //body.body.syncShapes();
  28994. this._registeredMeshes.push({
  28995. mesh: mesh,
  28996. body: body,
  28997. delta: deltaPosition
  28998. });
  28999. //for the sake of consistency.
  29000. mesh.rotationQuaternion = oldQuaternion;
  29001. return body;
  29002. };
  29003. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29004. var types = [], sizes = [], positions = [], rotations = [];
  29005. var initialMesh = parts[0].mesh;
  29006. for (var index = 0; index < parts.length; index++) {
  29007. var part = parts[index];
  29008. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29009. types.push(bodyParameters.type);
  29010. sizes.push.apply(sizes, bodyParameters.size);
  29011. positions.push.apply(positions, bodyParameters.pos);
  29012. rotations.push.apply(rotations, bodyParameters.rot);
  29013. }
  29014. var body = new OIMO.Body({
  29015. name: initialMesh.uniqueId,
  29016. type: types,
  29017. size: sizes,
  29018. pos: positions,
  29019. rot: rotations,
  29020. move: options.mass != 0,
  29021. config: [options.mass, options.friction, options.restitution],
  29022. world: this._world
  29023. });
  29024. //Reset the body's rotation to be of the initial mesh's.
  29025. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29026. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29027. this._registeredMeshes.push({
  29028. mesh: initialMesh,
  29029. body: body
  29030. });
  29031. return body;
  29032. };
  29033. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29034. var mesh = part.mesh;
  29035. if (!mesh.rotationQuaternion) {
  29036. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29037. }
  29038. // We need the bounding box/sphere info to compute the physics body
  29039. mesh.computeWorldMatrix(true);
  29040. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29041. var bodyParameters = {
  29042. name: mesh.uniqueId,
  29043. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29044. //A bug in Oimo (Body class) prevents us from using rot directly.
  29045. rot: [0, 0, 0],
  29046. //For future reference, if the bug will ever be fixed.
  29047. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29048. };
  29049. var oldQuaternion = mesh.rotationQuaternion;
  29050. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29051. mesh.computeWorldMatrix(true);
  29052. switch (part.impostor) {
  29053. case BABYLON.PhysicsEngine.SphereImpostor:
  29054. var bbox = mesh.getBoundingInfo().boundingBox;
  29055. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29056. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29057. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29058. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29059. bodyParameters.type = 'sphere';
  29060. bodyParameters.size = [size, size, size];
  29061. break;
  29062. case BABYLON.PhysicsEngine.PlaneImpostor:
  29063. case BABYLON.PhysicsEngine.CylinderImpostor:
  29064. case BABYLON.PhysicsEngine.BoxImpostor:
  29065. bbox = mesh.getBoundingInfo().boundingBox;
  29066. var min = bbox.minimumWorld;
  29067. var max = bbox.maximumWorld;
  29068. var box = max.subtract(min);
  29069. var sizeX = this._checkWithEpsilon(box.x);
  29070. var sizeY = this._checkWithEpsilon(box.y);
  29071. var sizeZ = this._checkWithEpsilon(box.z);
  29072. bodyParameters.type = 'box';
  29073. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29074. break;
  29075. }
  29076. mesh.rotationQuaternion = oldQuaternion;
  29077. return bodyParameters;
  29078. };
  29079. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29080. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29081. var registeredMesh = this._registeredMeshes[index];
  29082. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29083. if (registeredMesh.body) {
  29084. this._world.removeRigidBody(registeredMesh.body.body);
  29085. this._unbindBody(registeredMesh.body);
  29086. }
  29087. this._registeredMeshes.splice(index, 1);
  29088. return;
  29089. }
  29090. }
  29091. };
  29092. OimoJSPlugin.prototype._unbindBody = function (body) {
  29093. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29094. var registeredMesh = this._registeredMeshes[index];
  29095. if (registeredMesh.body === body) {
  29096. registeredMesh.body = null;
  29097. }
  29098. }
  29099. };
  29100. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29101. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29102. var registeredMesh = this._registeredMeshes[index];
  29103. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29104. // Get object mass to have a behaviour similar to cannon.js
  29105. var mass = registeredMesh.body.body.massInfo.mass;
  29106. // The force is scaled with the mass of object
  29107. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29108. return;
  29109. }
  29110. }
  29111. };
  29112. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29113. var body1 = null, body2 = null;
  29114. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29115. var registeredMesh = this._registeredMeshes[index];
  29116. if (registeredMesh.mesh === mesh1) {
  29117. body1 = registeredMesh.body.body;
  29118. }
  29119. else if (registeredMesh.mesh === mesh2) {
  29120. body2 = registeredMesh.body.body;
  29121. }
  29122. }
  29123. if (!body1 || !body2) {
  29124. return false;
  29125. }
  29126. if (!options) {
  29127. options = {};
  29128. }
  29129. new OIMO.Link({
  29130. type: options.type,
  29131. body1: body1,
  29132. body2: body2,
  29133. min: options.min,
  29134. max: options.max,
  29135. axe1: options.axe1,
  29136. axe2: options.axe2,
  29137. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29138. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29139. collision: options.collision,
  29140. spring: options.spring,
  29141. world: this._world
  29142. });
  29143. return true;
  29144. };
  29145. OimoJSPlugin.prototype.dispose = function () {
  29146. this._world.clear();
  29147. while (this._registeredMeshes.length) {
  29148. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29149. }
  29150. };
  29151. OimoJSPlugin.prototype.isSupported = function () {
  29152. return OIMO !== undefined;
  29153. };
  29154. OimoJSPlugin.prototype.getWorldObject = function () {
  29155. return this._world;
  29156. };
  29157. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29158. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29159. var registeredMesh = this._registeredMeshes[index];
  29160. if (registeredMesh.mesh === mesh) {
  29161. return registeredMesh.body;
  29162. }
  29163. }
  29164. return null;
  29165. };
  29166. OimoJSPlugin.prototype._getLastShape = function (body) {
  29167. var lastShape = body.shapes;
  29168. while (lastShape.next) {
  29169. lastShape = lastShape.next;
  29170. }
  29171. return lastShape;
  29172. };
  29173. OimoJSPlugin.prototype.runOneStep = function (time) {
  29174. this._world.step();
  29175. // Update the position of all registered meshes
  29176. var i = this._registeredMeshes.length;
  29177. var m;
  29178. while (i--) {
  29179. var body = this._registeredMeshes[i].body.body;
  29180. var mesh = this._registeredMeshes[i].mesh;
  29181. if (!this._registeredMeshes[i].delta) {
  29182. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29183. }
  29184. if (!body.sleeping) {
  29185. //TODO check that
  29186. if (body.shapes.next) {
  29187. var parentShape = this._getLastShape(body);
  29188. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29189. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29190. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29191. }
  29192. else {
  29193. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29194. }
  29195. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29196. mesh.computeWorldMatrix();
  29197. }
  29198. //check if the collide callback is set.
  29199. if (mesh.onPhysicsCollide) {
  29200. var meshUniqueName = mesh.uniqueId;
  29201. var contact = this._world.contacts;
  29202. while (contact !== null) {
  29203. //is this body colliding with any other?
  29204. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29205. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29206. //get the mesh and execute the callback
  29207. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29208. if (otherMesh)
  29209. mesh.onPhysicsCollide(otherMesh);
  29210. }
  29211. contact = contact.next;
  29212. }
  29213. }
  29214. }
  29215. };
  29216. return OimoJSPlugin;
  29217. })();
  29218. BABYLON.OimoJSPlugin = OimoJSPlugin;
  29219. })(BABYLON || (BABYLON = {}));
  29220. var BABYLON;
  29221. (function (BABYLON) {
  29222. var DisplayPassPostProcess = (function (_super) {
  29223. __extends(DisplayPassPostProcess, _super);
  29224. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  29225. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  29226. }
  29227. return DisplayPassPostProcess;
  29228. })(BABYLON.PostProcess);
  29229. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  29230. })(BABYLON || (BABYLON = {}));
  29231. var BABYLON;
  29232. (function (BABYLON) {
  29233. var SimplificationSettings = (function () {
  29234. function SimplificationSettings(quality, distance, optimizeMesh) {
  29235. this.quality = quality;
  29236. this.distance = distance;
  29237. this.optimizeMesh = optimizeMesh;
  29238. }
  29239. return SimplificationSettings;
  29240. })();
  29241. BABYLON.SimplificationSettings = SimplificationSettings;
  29242. var SimplificationQueue = (function () {
  29243. function SimplificationQueue() {
  29244. this.running = false;
  29245. this._simplificationArray = [];
  29246. }
  29247. SimplificationQueue.prototype.addTask = function (task) {
  29248. this._simplificationArray.push(task);
  29249. };
  29250. SimplificationQueue.prototype.executeNext = function () {
  29251. var task = this._simplificationArray.pop();
  29252. if (task) {
  29253. this.running = true;
  29254. this.runSimplification(task);
  29255. }
  29256. else {
  29257. this.running = false;
  29258. }
  29259. };
  29260. SimplificationQueue.prototype.runSimplification = function (task) {
  29261. var _this = this;
  29262. if (task.parallelProcessing) {
  29263. //parallel simplifier
  29264. task.settings.forEach(function (setting) {
  29265. var simplifier = _this.getSimplifier(task);
  29266. simplifier.simplify(setting, function (newMesh) {
  29267. task.mesh.addLODLevel(setting.distance, newMesh);
  29268. newMesh.isVisible = true;
  29269. //check if it is the last
  29270. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  29271. //all done, run the success callback.
  29272. task.successCallback();
  29273. }
  29274. _this.executeNext();
  29275. });
  29276. });
  29277. }
  29278. else {
  29279. //single simplifier.
  29280. var simplifier = this.getSimplifier(task);
  29281. var runDecimation = function (setting, callback) {
  29282. simplifier.simplify(setting, function (newMesh) {
  29283. task.mesh.addLODLevel(setting.distance, newMesh);
  29284. newMesh.isVisible = true;
  29285. //run the next quality level
  29286. callback();
  29287. });
  29288. };
  29289. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  29290. runDecimation(task.settings[loop.index], function () {
  29291. loop.executeNext();
  29292. });
  29293. }, function () {
  29294. //execution ended, run the success callback.
  29295. if (task.successCallback) {
  29296. task.successCallback();
  29297. }
  29298. _this.executeNext();
  29299. });
  29300. }
  29301. };
  29302. SimplificationQueue.prototype.getSimplifier = function (task) {
  29303. switch (task.simplificationType) {
  29304. case SimplificationType.QUADRATIC:
  29305. default:
  29306. return new QuadraticErrorSimplification(task.mesh);
  29307. }
  29308. };
  29309. return SimplificationQueue;
  29310. })();
  29311. BABYLON.SimplificationQueue = SimplificationQueue;
  29312. /**
  29313. * The implemented types of simplification.
  29314. * At the moment only Quadratic Error Decimation is implemented.
  29315. */
  29316. (function (SimplificationType) {
  29317. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  29318. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  29319. var SimplificationType = BABYLON.SimplificationType;
  29320. var DecimationTriangle = (function () {
  29321. function DecimationTriangle(vertices) {
  29322. this.vertices = vertices;
  29323. this.error = new Array(4);
  29324. this.deleted = false;
  29325. this.isDirty = false;
  29326. this.deletePending = false;
  29327. this.borderFactor = 0;
  29328. }
  29329. return DecimationTriangle;
  29330. })();
  29331. BABYLON.DecimationTriangle = DecimationTriangle;
  29332. var DecimationVertex = (function () {
  29333. function DecimationVertex(position, id) {
  29334. this.position = position;
  29335. this.id = id;
  29336. this.isBorder = true;
  29337. this.q = new QuadraticMatrix();
  29338. this.triangleCount = 0;
  29339. this.triangleStart = 0;
  29340. this.originalOffsets = [];
  29341. }
  29342. DecimationVertex.prototype.updatePosition = function (newPosition) {
  29343. this.position.copyFrom(newPosition);
  29344. };
  29345. return DecimationVertex;
  29346. })();
  29347. BABYLON.DecimationVertex = DecimationVertex;
  29348. var QuadraticMatrix = (function () {
  29349. function QuadraticMatrix(data) {
  29350. this.data = new Array(10);
  29351. for (var i = 0; i < 10; ++i) {
  29352. if (data && data[i]) {
  29353. this.data[i] = data[i];
  29354. }
  29355. else {
  29356. this.data[i] = 0;
  29357. }
  29358. }
  29359. }
  29360. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  29361. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  29362. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  29363. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  29364. return det;
  29365. };
  29366. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  29367. for (var i = 0; i < 10; ++i) {
  29368. this.data[i] += matrix.data[i];
  29369. }
  29370. };
  29371. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  29372. for (var i = 0; i < 10; ++i) {
  29373. this.data[i] += data[i];
  29374. }
  29375. };
  29376. QuadraticMatrix.prototype.add = function (matrix) {
  29377. var m = new QuadraticMatrix();
  29378. for (var i = 0; i < 10; ++i) {
  29379. m.data[i] = this.data[i] + matrix.data[i];
  29380. }
  29381. return m;
  29382. };
  29383. QuadraticMatrix.FromData = function (a, b, c, d) {
  29384. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  29385. };
  29386. //returning an array to avoid garbage collection
  29387. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  29388. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  29389. };
  29390. return QuadraticMatrix;
  29391. })();
  29392. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29393. var Reference = (function () {
  29394. function Reference(vertexId, triangleId) {
  29395. this.vertexId = vertexId;
  29396. this.triangleId = triangleId;
  29397. }
  29398. return Reference;
  29399. })();
  29400. BABYLON.Reference = Reference;
  29401. /**
  29402. * An implementation of the Quadratic Error simplification algorithm.
  29403. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29404. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29405. * @author RaananW
  29406. */
  29407. var QuadraticErrorSimplification = (function () {
  29408. function QuadraticErrorSimplification(_mesh) {
  29409. this._mesh = _mesh;
  29410. this.initialized = false;
  29411. this.syncIterations = 5000;
  29412. this.aggressiveness = 7;
  29413. this.decimationIterations = 100;
  29414. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29415. }
  29416. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29417. var _this = this;
  29418. this.initDecimatedMesh();
  29419. //iterating through the submeshes array, one after the other.
  29420. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29421. _this.initWithMesh(loop.index, function () {
  29422. _this.runDecimation(settings, loop.index, function () {
  29423. loop.executeNext();
  29424. });
  29425. }, settings.optimizeMesh);
  29426. }, function () {
  29427. setTimeout(function () {
  29428. successCallback(_this._reconstructedMesh);
  29429. }, 0);
  29430. });
  29431. };
  29432. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29433. var _this = this;
  29434. var gCount = 0;
  29435. triangle.vertices.forEach(function (vertex) {
  29436. var count = 0;
  29437. var vPos = vertex.position;
  29438. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29439. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29440. ++count;
  29441. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29442. ++count;
  29443. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29444. ++count;
  29445. if (count > 1) {
  29446. ++gCount;
  29447. }
  29448. ;
  29449. });
  29450. if (gCount > 1) {
  29451. console.log(triangle, gCount);
  29452. }
  29453. return gCount > 1;
  29454. };
  29455. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29456. var _this = this;
  29457. var targetCount = ~~(this.triangles.length * settings.quality);
  29458. var deletedTriangles = 0;
  29459. var triangleCount = this.triangles.length;
  29460. var iterationFunction = function (iteration, callback) {
  29461. setTimeout(function () {
  29462. if (iteration % 5 === 0) {
  29463. _this.updateMesh(iteration === 0);
  29464. }
  29465. for (var i = 0; i < _this.triangles.length; ++i) {
  29466. _this.triangles[i].isDirty = false;
  29467. }
  29468. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29469. var trianglesIterator = function (i) {
  29470. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29471. var t = _this.triangles[tIdx];
  29472. if (!t)
  29473. return;
  29474. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29475. return;
  29476. }
  29477. for (var j = 0; j < 3; ++j) {
  29478. if (t.error[j] < threshold) {
  29479. var deleted0 = [];
  29480. var deleted1 = [];
  29481. var v0 = t.vertices[j];
  29482. var v1 = t.vertices[(j + 1) % 3];
  29483. if (v0.isBorder !== v1.isBorder)
  29484. continue;
  29485. var p = BABYLON.Vector3.Zero();
  29486. var n = BABYLON.Vector3.Zero();
  29487. var uv = BABYLON.Vector2.Zero();
  29488. var color = new BABYLON.Color4(0, 0, 0, 1);
  29489. _this.calculateError(v0, v1, p, n, uv, color);
  29490. var delTr = [];
  29491. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29492. continue;
  29493. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29494. continue;
  29495. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29496. continue;
  29497. var uniqueArray = [];
  29498. delTr.forEach(function (deletedT) {
  29499. if (uniqueArray.indexOf(deletedT) === -1) {
  29500. deletedT.deletePending = true;
  29501. uniqueArray.push(deletedT);
  29502. }
  29503. });
  29504. if (uniqueArray.length % 2 !== 0) {
  29505. continue;
  29506. }
  29507. v0.q = v1.q.add(v0.q);
  29508. v0.updatePosition(p);
  29509. var tStart = _this.references.length;
  29510. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29511. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29512. var tCount = _this.references.length - tStart;
  29513. if (tCount <= v0.triangleCount) {
  29514. if (tCount) {
  29515. for (var c = 0; c < tCount; c++) {
  29516. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29517. }
  29518. }
  29519. }
  29520. else {
  29521. v0.triangleStart = tStart;
  29522. }
  29523. v0.triangleCount = tCount;
  29524. break;
  29525. }
  29526. }
  29527. };
  29528. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29529. }, 0);
  29530. };
  29531. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29532. if (triangleCount - deletedTriangles <= targetCount)
  29533. loop.breakLoop();
  29534. else {
  29535. iterationFunction(loop.index, function () {
  29536. loop.executeNext();
  29537. });
  29538. }
  29539. }, function () {
  29540. setTimeout(function () {
  29541. //reconstruct this part of the mesh
  29542. _this.reconstructMesh(submeshIndex);
  29543. successCallback();
  29544. }, 0);
  29545. });
  29546. };
  29547. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29548. var _this = this;
  29549. this.vertices = [];
  29550. this.triangles = [];
  29551. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29552. var indices = this._mesh.getIndices();
  29553. var submesh = this._mesh.subMeshes[submeshIndex];
  29554. var findInVertices = function (positionToSearch) {
  29555. if (optimizeMesh) {
  29556. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29557. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29558. return _this.vertices[ii];
  29559. }
  29560. }
  29561. }
  29562. return null;
  29563. };
  29564. var vertexReferences = [];
  29565. var vertexInit = function (i) {
  29566. var offset = i + submesh.verticesStart;
  29567. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29568. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29569. vertex.originalOffsets.push(offset);
  29570. if (vertex.id === _this.vertices.length) {
  29571. _this.vertices.push(vertex);
  29572. }
  29573. vertexReferences.push(vertex.id);
  29574. };
  29575. //var totalVertices = mesh.getTotalVertices();
  29576. var totalVertices = submesh.verticesCount;
  29577. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29578. var indicesInit = function (i) {
  29579. var offset = (submesh.indexStart / 3) + i;
  29580. var pos = (offset * 3);
  29581. var i0 = indices[pos + 0];
  29582. var i1 = indices[pos + 1];
  29583. var i2 = indices[pos + 2];
  29584. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29585. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29586. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29587. var triangle = new DecimationTriangle([v0, v1, v2]);
  29588. triangle.originalOffset = pos;
  29589. _this.triangles.push(triangle);
  29590. };
  29591. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29592. _this.init(callback);
  29593. });
  29594. });
  29595. };
  29596. QuadraticErrorSimplification.prototype.init = function (callback) {
  29597. var _this = this;
  29598. var triangleInit1 = function (i) {
  29599. var t = _this.triangles[i];
  29600. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29601. for (var j = 0; j < 3; j++) {
  29602. 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))));
  29603. }
  29604. };
  29605. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29606. var triangleInit2 = function (i) {
  29607. var t = _this.triangles[i];
  29608. for (var j = 0; j < 3; ++j) {
  29609. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29610. }
  29611. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29612. };
  29613. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29614. _this.initialized = true;
  29615. callback();
  29616. });
  29617. });
  29618. };
  29619. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29620. var newTriangles = [];
  29621. var i;
  29622. for (i = 0; i < this.vertices.length; ++i) {
  29623. this.vertices[i].triangleCount = 0;
  29624. }
  29625. var t;
  29626. var j;
  29627. for (i = 0; i < this.triangles.length; ++i) {
  29628. if (!this.triangles[i].deleted) {
  29629. t = this.triangles[i];
  29630. for (j = 0; j < 3; ++j) {
  29631. t.vertices[j].triangleCount = 1;
  29632. }
  29633. newTriangles.push(t);
  29634. }
  29635. }
  29636. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29637. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29638. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29639. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29640. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29641. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29642. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29643. var vertexCount = 0;
  29644. for (i = 0; i < this.vertices.length; ++i) {
  29645. var vertex = this.vertices[i];
  29646. vertex.id = vertexCount;
  29647. if (vertex.triangleCount) {
  29648. vertex.originalOffsets.forEach(function (originalOffset) {
  29649. newPositionData.push(vertex.position.x);
  29650. newPositionData.push(vertex.position.y);
  29651. newPositionData.push(vertex.position.z);
  29652. newNormalData.push(normalData[originalOffset * 3]);
  29653. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29654. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29655. if (uvs && uvs.length) {
  29656. newUVsData.push(uvs[(originalOffset * 2)]);
  29657. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29658. }
  29659. else if (colorsData && colorsData.length) {
  29660. newColorsData.push(colorsData[(originalOffset * 4)]);
  29661. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29662. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29663. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29664. }
  29665. ++vertexCount;
  29666. });
  29667. }
  29668. }
  29669. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29670. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29671. var submeshesArray = this._reconstructedMesh.subMeshes;
  29672. this._reconstructedMesh.subMeshes = [];
  29673. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29674. var originalIndices = this._mesh.getIndices();
  29675. for (i = 0; i < newTriangles.length; ++i) {
  29676. t = newTriangles[i]; //now get the new referencing point for each vertex
  29677. [0, 1, 2].forEach(function (idx) {
  29678. var id = originalIndices[t.originalOffset + idx];
  29679. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29680. if (offset < 0)
  29681. offset = 0;
  29682. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29683. });
  29684. }
  29685. //overwriting the old vertex buffers and indices.
  29686. this._reconstructedMesh.setIndices(newIndicesArray);
  29687. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29688. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29689. if (newUVsData.length > 0)
  29690. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29691. if (newColorsData.length > 0)
  29692. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29693. //create submesh
  29694. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29695. if (submeshIndex > 0) {
  29696. this._reconstructedMesh.subMeshes = [];
  29697. submeshesArray.forEach(function (submesh) {
  29698. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29699. });
  29700. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29701. }
  29702. };
  29703. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29704. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29705. this._reconstructedMesh.material = this._mesh.material;
  29706. this._reconstructedMesh.parent = this._mesh.parent;
  29707. this._reconstructedMesh.isVisible = false;
  29708. };
  29709. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29710. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29711. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29712. if (t.deleted)
  29713. continue;
  29714. var s = this.references[vertex1.triangleStart + i].vertexId;
  29715. var v1 = t.vertices[(s + 1) % 3];
  29716. var v2 = t.vertices[(s + 2) % 3];
  29717. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29718. deletedArray[i] = true;
  29719. delTr.push(t);
  29720. continue;
  29721. }
  29722. var d1 = v1.position.subtract(point);
  29723. d1 = d1.normalize();
  29724. var d2 = v2.position.subtract(point);
  29725. d2 = d2.normalize();
  29726. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29727. return true;
  29728. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29729. deletedArray[i] = false;
  29730. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29731. return true;
  29732. }
  29733. return false;
  29734. };
  29735. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29736. var newDeleted = deletedTriangles;
  29737. for (var i = 0; i < vertex.triangleCount; ++i) {
  29738. var ref = this.references[vertex.triangleStart + i];
  29739. var t = this.triangles[ref.triangleId];
  29740. if (t.deleted)
  29741. continue;
  29742. if (deletedArray[i] && t.deletePending) {
  29743. t.deleted = true;
  29744. newDeleted++;
  29745. continue;
  29746. }
  29747. t.vertices[ref.vertexId] = origVertex;
  29748. t.isDirty = true;
  29749. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29750. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29751. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29752. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29753. this.references.push(ref);
  29754. }
  29755. return newDeleted;
  29756. };
  29757. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29758. for (var i = 0; i < this.vertices.length; ++i) {
  29759. var vCount = [];
  29760. var vId = [];
  29761. var v = this.vertices[i];
  29762. var j;
  29763. for (j = 0; j < v.triangleCount; ++j) {
  29764. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29765. for (var ii = 0; ii < 3; ii++) {
  29766. var ofs = 0;
  29767. var vv = triangle.vertices[ii];
  29768. while (ofs < vCount.length) {
  29769. if (vId[ofs] === vv.id)
  29770. break;
  29771. ++ofs;
  29772. }
  29773. if (ofs === vCount.length) {
  29774. vCount.push(1);
  29775. vId.push(vv.id);
  29776. }
  29777. else {
  29778. vCount[ofs]++;
  29779. }
  29780. }
  29781. }
  29782. for (j = 0; j < vCount.length; ++j) {
  29783. if (vCount[j] === 1) {
  29784. this.vertices[vId[j]].isBorder = true;
  29785. }
  29786. else {
  29787. this.vertices[vId[j]].isBorder = false;
  29788. }
  29789. }
  29790. }
  29791. };
  29792. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29793. if (identifyBorders === void 0) { identifyBorders = false; }
  29794. var i;
  29795. if (!identifyBorders) {
  29796. var newTrianglesVector = [];
  29797. for (i = 0; i < this.triangles.length; ++i) {
  29798. if (!this.triangles[i].deleted) {
  29799. newTrianglesVector.push(this.triangles[i]);
  29800. }
  29801. }
  29802. this.triangles = newTrianglesVector;
  29803. }
  29804. for (i = 0; i < this.vertices.length; ++i) {
  29805. this.vertices[i].triangleCount = 0;
  29806. this.vertices[i].triangleStart = 0;
  29807. }
  29808. var t;
  29809. var j;
  29810. var v;
  29811. for (i = 0; i < this.triangles.length; ++i) {
  29812. t = this.triangles[i];
  29813. for (j = 0; j < 3; ++j) {
  29814. v = t.vertices[j];
  29815. v.triangleCount++;
  29816. }
  29817. }
  29818. var tStart = 0;
  29819. for (i = 0; i < this.vertices.length; ++i) {
  29820. this.vertices[i].triangleStart = tStart;
  29821. tStart += this.vertices[i].triangleCount;
  29822. this.vertices[i].triangleCount = 0;
  29823. }
  29824. var newReferences = new Array(this.triangles.length * 3);
  29825. for (i = 0; i < this.triangles.length; ++i) {
  29826. t = this.triangles[i];
  29827. for (j = 0; j < 3; ++j) {
  29828. v = t.vertices[j];
  29829. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29830. v.triangleCount++;
  29831. }
  29832. }
  29833. this.references = newReferences;
  29834. if (identifyBorders) {
  29835. this.identifyBorder();
  29836. }
  29837. };
  29838. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29839. var x = point.x;
  29840. var y = point.y;
  29841. var z = point.z;
  29842. 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
  29843. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29844. };
  29845. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29846. var q = vertex1.q.add(vertex2.q);
  29847. var border = vertex1.isBorder && vertex2.isBorder;
  29848. var error = 0;
  29849. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29850. if (qDet !== 0 && !border) {
  29851. if (!pointResult) {
  29852. pointResult = BABYLON.Vector3.Zero();
  29853. }
  29854. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29855. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29856. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29857. error = this.vertexError(q, pointResult);
  29858. }
  29859. else {
  29860. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29861. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29862. var error1 = this.vertexError(q, vertex1.position);
  29863. var error2 = this.vertexError(q, vertex2.position);
  29864. var error3 = this.vertexError(q, p3);
  29865. error = Math.min(error1, error2, error3);
  29866. if (error === error1) {
  29867. if (pointResult) {
  29868. pointResult.copyFrom(vertex1.position);
  29869. }
  29870. }
  29871. else if (error === error2) {
  29872. if (pointResult) {
  29873. pointResult.copyFrom(vertex2.position);
  29874. }
  29875. }
  29876. else {
  29877. if (pointResult) {
  29878. pointResult.copyFrom(p3);
  29879. }
  29880. }
  29881. }
  29882. return error;
  29883. };
  29884. return QuadraticErrorSimplification;
  29885. })();
  29886. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29887. })(BABYLON || (BABYLON = {}));
  29888. var BABYLON;
  29889. (function (BABYLON) {
  29890. var serializedGeometries = [];
  29891. var serializeGeometry = function (geometry, serializationGeometries) {
  29892. if (serializedGeometries[geometry.id]) {
  29893. return;
  29894. }
  29895. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29896. serializationGeometries.boxes.push(geometry.serialize());
  29897. }
  29898. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29899. serializationGeometries.spheres.push(geometry.serialize());
  29900. }
  29901. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29902. serializationGeometries.cylinders.push(geometry.serialize());
  29903. }
  29904. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29905. serializationGeometries.toruses.push(geometry.serialize());
  29906. }
  29907. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29908. serializationGeometries.grounds.push(geometry.serialize());
  29909. }
  29910. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29911. serializationGeometries.planes.push(geometry.serialize());
  29912. }
  29913. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29914. serializationGeometries.torusKnots.push(geometry.serialize());
  29915. }
  29916. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29917. throw new Error("Unknown primitive type");
  29918. }
  29919. else {
  29920. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  29921. }
  29922. serializedGeometries[geometry.id] = true;
  29923. };
  29924. var serializeMesh = function (mesh, serializationScene) {
  29925. var serializationObject = {};
  29926. serializationObject.name = mesh.name;
  29927. serializationObject.id = mesh.id;
  29928. if (BABYLON.Tags.HasTags(mesh)) {
  29929. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29930. }
  29931. serializationObject.position = mesh.position.asArray();
  29932. if (mesh.rotationQuaternion) {
  29933. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29934. }
  29935. else if (mesh.rotation) {
  29936. serializationObject.rotation = mesh.rotation.asArray();
  29937. }
  29938. serializationObject.scaling = mesh.scaling.asArray();
  29939. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29940. serializationObject.isEnabled = mesh.isEnabled();
  29941. serializationObject.isVisible = mesh.isVisible;
  29942. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29943. serializationObject.pickable = mesh.isPickable;
  29944. serializationObject.receiveShadows = mesh.receiveShadows;
  29945. serializationObject.billboardMode = mesh.billboardMode;
  29946. serializationObject.visibility = mesh.visibility;
  29947. serializationObject.checkCollisions = mesh.checkCollisions;
  29948. // Parent
  29949. if (mesh.parent) {
  29950. serializationObject.parentId = mesh.parent.id;
  29951. }
  29952. // Geometry
  29953. var geometry = mesh._geometry;
  29954. if (geometry) {
  29955. var geometryId = geometry.id;
  29956. serializationObject.geometryId = geometryId;
  29957. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29958. // 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
  29959. serializeGeometry(geometry, serializationScene.geometries);
  29960. }
  29961. // SubMeshes
  29962. serializationObject.subMeshes = [];
  29963. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29964. var subMesh = mesh.subMeshes[subIndex];
  29965. serializationObject.subMeshes.push({
  29966. materialIndex: subMesh.materialIndex,
  29967. verticesStart: subMesh.verticesStart,
  29968. verticesCount: subMesh.verticesCount,
  29969. indexStart: subMesh.indexStart,
  29970. indexCount: subMesh.indexCount
  29971. });
  29972. }
  29973. }
  29974. // Material
  29975. if (mesh.material) {
  29976. serializationObject.materialId = mesh.material.id;
  29977. }
  29978. else {
  29979. mesh.material = null;
  29980. }
  29981. // Skeleton
  29982. if (mesh.skeleton) {
  29983. serializationObject.skeletonId = mesh.skeleton.id;
  29984. }
  29985. // Physics
  29986. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29987. serializationObject.physicsMass = mesh.getPhysicsMass();
  29988. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29989. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29990. switch (mesh.getPhysicsImpostor()) {
  29991. case BABYLON.PhysicsEngine.BoxImpostor:
  29992. serializationObject.physicsImpostor = 1;
  29993. break;
  29994. case BABYLON.PhysicsEngine.SphereImpostor:
  29995. serializationObject.physicsImpostor = 2;
  29996. break;
  29997. }
  29998. }
  29999. // Instances
  30000. serializationObject.instances = [];
  30001. for (var index = 0; index < mesh.instances.length; index++) {
  30002. var instance = mesh.instances[index];
  30003. var serializationInstance = {
  30004. name: instance.name,
  30005. position: instance.position.asArray(),
  30006. scaling: instance.scaling.asArray()
  30007. };
  30008. if (instance.rotationQuaternion) {
  30009. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30010. }
  30011. else if (instance.rotation) {
  30012. serializationInstance.rotation = instance.rotation.asArray();
  30013. }
  30014. serializationObject.instances.push(serializationInstance);
  30015. // Animations
  30016. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30017. }
  30018. // Animations
  30019. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30020. // Layer mask
  30021. serializationObject.layerMask = mesh.layerMask;
  30022. return serializationObject;
  30023. };
  30024. var finalizeSingleMesh = function (mesh, serializationObject) {
  30025. //only works if the mesh is already loaded
  30026. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30027. //serialize material
  30028. if (mesh.material) {
  30029. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30030. serializationObject.materials = serializationObject.materials || [];
  30031. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30032. serializationObject.materials.push(mesh.material.serialize());
  30033. }
  30034. }
  30035. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30036. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30037. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30038. serializationObject.multiMaterials.push(mesh.material.serialize());
  30039. }
  30040. }
  30041. }
  30042. //serialize geometry
  30043. var geometry = mesh._geometry;
  30044. if (geometry) {
  30045. if (!serializationObject.geometries) {
  30046. serializationObject.geometries = {};
  30047. serializationObject.geometries.boxes = [];
  30048. serializationObject.geometries.spheres = [];
  30049. serializationObject.geometries.cylinders = [];
  30050. serializationObject.geometries.toruses = [];
  30051. serializationObject.geometries.grounds = [];
  30052. serializationObject.geometries.planes = [];
  30053. serializationObject.geometries.torusKnots = [];
  30054. serializationObject.geometries.vertexData = [];
  30055. }
  30056. serializeGeometry(geometry, serializationObject.geometries);
  30057. }
  30058. // Skeletons
  30059. if (mesh.skeleton) {
  30060. serializationObject.skeletons = serializationObject.skeletons || [];
  30061. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30062. }
  30063. //serialize the actual mesh
  30064. serializationObject.meshes = serializationObject.meshes || [];
  30065. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30066. }
  30067. };
  30068. var SceneSerializer = (function () {
  30069. function SceneSerializer() {
  30070. }
  30071. SceneSerializer.Serialize = function (scene) {
  30072. var serializationObject = {};
  30073. // Scene
  30074. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30075. serializationObject.autoClear = scene.autoClear;
  30076. serializationObject.clearColor = scene.clearColor.asArray();
  30077. serializationObject.ambientColor = scene.ambientColor.asArray();
  30078. serializationObject.gravity = scene.gravity.asArray();
  30079. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30080. serializationObject.workerCollisions = scene.workerCollisions;
  30081. // Fog
  30082. if (scene.fogMode && scene.fogMode !== 0) {
  30083. serializationObject.fogMode = scene.fogMode;
  30084. serializationObject.fogColor = scene.fogColor.asArray();
  30085. serializationObject.fogStart = scene.fogStart;
  30086. serializationObject.fogEnd = scene.fogEnd;
  30087. serializationObject.fogDensity = scene.fogDensity;
  30088. }
  30089. //Physics
  30090. if (scene.isPhysicsEnabled()) {
  30091. serializationObject.physicsEnabled = true;
  30092. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30093. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30094. }
  30095. // Lights
  30096. serializationObject.lights = [];
  30097. var index;
  30098. var light;
  30099. for (index = 0; index < scene.lights.length; index++) {
  30100. light = scene.lights[index];
  30101. serializationObject.lights.push(light.serialize());
  30102. }
  30103. // Cameras
  30104. serializationObject.cameras = [];
  30105. for (index = 0; index < scene.cameras.length; index++) {
  30106. var camera = scene.cameras[index];
  30107. serializationObject.cameras.push(camera.serialize());
  30108. }
  30109. if (scene.activeCamera) {
  30110. serializationObject.activeCameraID = scene.activeCamera.id;
  30111. }
  30112. // Materials
  30113. serializationObject.materials = [];
  30114. serializationObject.multiMaterials = [];
  30115. var material;
  30116. for (index = 0; index < scene.materials.length; index++) {
  30117. material = scene.materials[index];
  30118. serializationObject.materials.push(material.serialize());
  30119. }
  30120. // MultiMaterials
  30121. serializationObject.multiMaterials = [];
  30122. for (index = 0; index < scene.multiMaterials.length; index++) {
  30123. var multiMaterial = scene.multiMaterials[index];
  30124. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30125. }
  30126. for (index = 0; index < scene.materials.length; index++) {
  30127. material = scene.materials[index];
  30128. serializationObject.materials.push(material.serialize());
  30129. }
  30130. // Skeletons
  30131. serializationObject.skeletons = [];
  30132. for (index = 0; index < scene.skeletons.length; index++) {
  30133. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30134. }
  30135. // Geometries
  30136. serializationObject.geometries = {};
  30137. serializationObject.geometries.boxes = [];
  30138. serializationObject.geometries.spheres = [];
  30139. serializationObject.geometries.cylinders = [];
  30140. serializationObject.geometries.toruses = [];
  30141. serializationObject.geometries.grounds = [];
  30142. serializationObject.geometries.planes = [];
  30143. serializationObject.geometries.torusKnots = [];
  30144. serializationObject.geometries.vertexData = [];
  30145. serializedGeometries = [];
  30146. var geometries = scene.getGeometries();
  30147. for (index = 0; index < geometries.length; index++) {
  30148. var geometry = geometries[index];
  30149. if (geometry.isReady()) {
  30150. serializeGeometry(geometry, serializationObject.geometries);
  30151. }
  30152. }
  30153. // Meshes
  30154. serializationObject.meshes = [];
  30155. for (index = 0; index < scene.meshes.length; index++) {
  30156. var abstractMesh = scene.meshes[index];
  30157. if (abstractMesh instanceof BABYLON.Mesh) {
  30158. var mesh = abstractMesh;
  30159. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30160. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30161. }
  30162. }
  30163. }
  30164. // Particles Systems
  30165. serializationObject.particleSystems = [];
  30166. for (index = 0; index < scene.particleSystems.length; index++) {
  30167. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30168. }
  30169. // Lens flares
  30170. serializationObject.lensFlareSystems = [];
  30171. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30172. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30173. }
  30174. // Shadows
  30175. serializationObject.shadowGenerators = [];
  30176. for (index = 0; index < scene.lights.length; index++) {
  30177. light = scene.lights[index];
  30178. if (light.getShadowGenerator()) {
  30179. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30180. }
  30181. }
  30182. return serializationObject;
  30183. };
  30184. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30185. if (withParents === void 0) { withParents = false; }
  30186. if (withChildren === void 0) { withChildren = false; }
  30187. var serializationObject = {};
  30188. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30189. if (withParents || withChildren) {
  30190. //deliberate for loop! not for each, appended should be processed as well.
  30191. for (var i = 0; i < toSerialize.length; ++i) {
  30192. if (withChildren) {
  30193. toSerialize[i].getDescendants().forEach(function (node) {
  30194. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30195. toSerialize.push(node);
  30196. }
  30197. });
  30198. }
  30199. //make sure the array doesn't contain the object already
  30200. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30201. toSerialize.push(toSerialize[i].parent);
  30202. }
  30203. }
  30204. }
  30205. toSerialize.forEach(function (mesh) {
  30206. finalizeSingleMesh(mesh, serializationObject);
  30207. });
  30208. return serializationObject;
  30209. };
  30210. return SceneSerializer;
  30211. })();
  30212. BABYLON.SceneSerializer = SceneSerializer;
  30213. })(BABYLON || (BABYLON = {}));
  30214. var BABYLON;
  30215. (function (BABYLON) {
  30216. // Unique ID when we import meshes from Babylon to CSG
  30217. var currentCSGMeshId = 0;
  30218. // # class Vertex
  30219. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30220. // one to provide additional features like texture coordinates and vertex
  30221. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30222. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30223. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30224. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30225. // is not used anywhere else.
  30226. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30227. var Vertex = (function () {
  30228. function Vertex(pos, normal, uv) {
  30229. this.pos = pos;
  30230. this.normal = normal;
  30231. this.uv = uv;
  30232. }
  30233. Vertex.prototype.clone = function () {
  30234. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30235. };
  30236. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30237. // orientation of a polygon is flipped.
  30238. Vertex.prototype.flip = function () {
  30239. this.normal = this.normal.scale(-1);
  30240. };
  30241. // Create a new vertex between this vertex and `other` by linearly
  30242. // interpolating all properties using a parameter of `t`. Subclasses should
  30243. // override this to interpolate additional properties.
  30244. Vertex.prototype.interpolate = function (other, t) {
  30245. 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));
  30246. };
  30247. return Vertex;
  30248. })();
  30249. // # class Plane
  30250. // Represents a plane in 3D space.
  30251. var Plane = (function () {
  30252. function Plane(normal, w) {
  30253. this.normal = normal;
  30254. this.w = w;
  30255. }
  30256. Plane.FromPoints = function (a, b, c) {
  30257. var v0 = c.subtract(a);
  30258. var v1 = b.subtract(a);
  30259. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30260. return null;
  30261. }
  30262. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30263. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30264. };
  30265. Plane.prototype.clone = function () {
  30266. return new Plane(this.normal.clone(), this.w);
  30267. };
  30268. Plane.prototype.flip = function () {
  30269. this.normal.scaleInPlace(-1);
  30270. this.w = -this.w;
  30271. };
  30272. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30273. // fragments in the appropriate lists. Coplanar polygons go into either
  30274. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30275. // respect to this plane. Polygons in front or in back of this plane go into
  30276. // either `front` or `back`.
  30277. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30278. var COPLANAR = 0;
  30279. var FRONT = 1;
  30280. var BACK = 2;
  30281. var SPANNING = 3;
  30282. // Classify each point as well as the entire polygon into one of the above
  30283. // four classes.
  30284. var polygonType = 0;
  30285. var types = [];
  30286. var i;
  30287. var t;
  30288. for (i = 0; i < polygon.vertices.length; i++) {
  30289. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30290. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30291. polygonType |= type;
  30292. types.push(type);
  30293. }
  30294. // Put the polygon in the correct list, splitting it when necessary.
  30295. switch (polygonType) {
  30296. case COPLANAR:
  30297. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30298. break;
  30299. case FRONT:
  30300. front.push(polygon);
  30301. break;
  30302. case BACK:
  30303. back.push(polygon);
  30304. break;
  30305. case SPANNING:
  30306. var f = [], b = [];
  30307. for (i = 0; i < polygon.vertices.length; i++) {
  30308. var j = (i + 1) % polygon.vertices.length;
  30309. var ti = types[i], tj = types[j];
  30310. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30311. if (ti !== BACK)
  30312. f.push(vi);
  30313. if (ti !== FRONT)
  30314. b.push(ti !== BACK ? vi.clone() : vi);
  30315. if ((ti | tj) === SPANNING) {
  30316. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30317. var v = vi.interpolate(vj, t);
  30318. f.push(v);
  30319. b.push(v.clone());
  30320. }
  30321. }
  30322. var poly;
  30323. if (f.length >= 3) {
  30324. poly = new Polygon(f, polygon.shared);
  30325. if (poly.plane)
  30326. front.push(poly);
  30327. }
  30328. if (b.length >= 3) {
  30329. poly = new Polygon(b, polygon.shared);
  30330. if (poly.plane)
  30331. back.push(poly);
  30332. }
  30333. break;
  30334. }
  30335. };
  30336. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30337. // point is on the plane.
  30338. Plane.EPSILON = 1e-5;
  30339. return Plane;
  30340. })();
  30341. // # class Polygon
  30342. // Represents a convex polygon. The vertices used to initialize a polygon must
  30343. // be coplanar and form a convex loop.
  30344. //
  30345. // Each convex polygon has a `shared` property, which is shared between all
  30346. // polygons that are clones of each other or were split from the same polygon.
  30347. // This can be used to define per-polygon properties (such as surface color).
  30348. var Polygon = (function () {
  30349. function Polygon(vertices, shared) {
  30350. this.vertices = vertices;
  30351. this.shared = shared;
  30352. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30353. }
  30354. Polygon.prototype.clone = function () {
  30355. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30356. return new Polygon(vertices, this.shared);
  30357. };
  30358. Polygon.prototype.flip = function () {
  30359. this.vertices.reverse().map(function (v) { v.flip(); });
  30360. this.plane.flip();
  30361. };
  30362. return Polygon;
  30363. })();
  30364. // # class Node
  30365. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30366. // by picking a polygon to split along. That polygon (and all other coplanar
  30367. // polygons) are added directly to that node and the other polygons are added to
  30368. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30369. // no distinction between internal and leaf nodes.
  30370. var Node = (function () {
  30371. function Node(polygons) {
  30372. this.plane = null;
  30373. this.front = null;
  30374. this.back = null;
  30375. this.polygons = [];
  30376. if (polygons) {
  30377. this.build(polygons);
  30378. }
  30379. }
  30380. Node.prototype.clone = function () {
  30381. var node = new Node();
  30382. node.plane = this.plane && this.plane.clone();
  30383. node.front = this.front && this.front.clone();
  30384. node.back = this.back && this.back.clone();
  30385. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30386. return node;
  30387. };
  30388. // Convert solid space to empty space and empty space to solid space.
  30389. Node.prototype.invert = function () {
  30390. for (var i = 0; i < this.polygons.length; i++) {
  30391. this.polygons[i].flip();
  30392. }
  30393. if (this.plane) {
  30394. this.plane.flip();
  30395. }
  30396. if (this.front) {
  30397. this.front.invert();
  30398. }
  30399. if (this.back) {
  30400. this.back.invert();
  30401. }
  30402. var temp = this.front;
  30403. this.front = this.back;
  30404. this.back = temp;
  30405. };
  30406. // Recursively remove all polygons in `polygons` that are inside this BSP
  30407. // tree.
  30408. Node.prototype.clipPolygons = function (polygons) {
  30409. if (!this.plane)
  30410. return polygons.slice();
  30411. var front = [], back = [];
  30412. for (var i = 0; i < polygons.length; i++) {
  30413. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30414. }
  30415. if (this.front) {
  30416. front = this.front.clipPolygons(front);
  30417. }
  30418. if (this.back) {
  30419. back = this.back.clipPolygons(back);
  30420. }
  30421. else {
  30422. back = [];
  30423. }
  30424. return front.concat(back);
  30425. };
  30426. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30427. // `bsp`.
  30428. Node.prototype.clipTo = function (bsp) {
  30429. this.polygons = bsp.clipPolygons(this.polygons);
  30430. if (this.front)
  30431. this.front.clipTo(bsp);
  30432. if (this.back)
  30433. this.back.clipTo(bsp);
  30434. };
  30435. // Return a list of all polygons in this BSP tree.
  30436. Node.prototype.allPolygons = function () {
  30437. var polygons = this.polygons.slice();
  30438. if (this.front)
  30439. polygons = polygons.concat(this.front.allPolygons());
  30440. if (this.back)
  30441. polygons = polygons.concat(this.back.allPolygons());
  30442. return polygons;
  30443. };
  30444. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30445. // new polygons are filtered down to the bottom of the tree and become new
  30446. // nodes there. Each set of polygons is partitioned using the first polygon
  30447. // (no heuristic is used to pick a good split).
  30448. Node.prototype.build = function (polygons) {
  30449. if (!polygons.length)
  30450. return;
  30451. if (!this.plane)
  30452. this.plane = polygons[0].plane.clone();
  30453. var front = [], back = [];
  30454. for (var i = 0; i < polygons.length; i++) {
  30455. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30456. }
  30457. if (front.length) {
  30458. if (!this.front)
  30459. this.front = new Node();
  30460. this.front.build(front);
  30461. }
  30462. if (back.length) {
  30463. if (!this.back)
  30464. this.back = new Node();
  30465. this.back.build(back);
  30466. }
  30467. };
  30468. return Node;
  30469. })();
  30470. var CSG = (function () {
  30471. function CSG() {
  30472. this.polygons = new Array();
  30473. }
  30474. // Convert BABYLON.Mesh to BABYLON.CSG
  30475. CSG.FromMesh = function (mesh) {
  30476. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30477. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30478. if (mesh instanceof BABYLON.Mesh) {
  30479. mesh.computeWorldMatrix(true);
  30480. matrix = mesh.getWorldMatrix();
  30481. meshPosition = mesh.position.clone();
  30482. meshRotation = mesh.rotation.clone();
  30483. if (mesh.rotationQuaternion) {
  30484. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30485. }
  30486. meshScaling = mesh.scaling.clone();
  30487. }
  30488. else {
  30489. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30490. }
  30491. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30492. var subMeshes = mesh.subMeshes;
  30493. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30494. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30495. vertices = [];
  30496. for (var j = 0; j < 3; j++) {
  30497. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30498. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30499. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30500. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30501. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30502. vertex = new Vertex(position, normal, uv);
  30503. vertices.push(vertex);
  30504. }
  30505. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30506. // To handle the case of degenerated triangle
  30507. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30508. if (polygon.plane)
  30509. polygons.push(polygon);
  30510. }
  30511. }
  30512. var csg = CSG.FromPolygons(polygons);
  30513. csg.matrix = matrix;
  30514. csg.position = meshPosition;
  30515. csg.rotation = meshRotation;
  30516. csg.scaling = meshScaling;
  30517. csg.rotationQuaternion = meshRotationQuaternion;
  30518. currentCSGMeshId++;
  30519. return csg;
  30520. };
  30521. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30522. CSG.FromPolygons = function (polygons) {
  30523. var csg = new CSG();
  30524. csg.polygons = polygons;
  30525. return csg;
  30526. };
  30527. CSG.prototype.clone = function () {
  30528. var csg = new CSG();
  30529. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30530. csg.copyTransformAttributes(this);
  30531. return csg;
  30532. };
  30533. CSG.prototype.toPolygons = function () {
  30534. return this.polygons;
  30535. };
  30536. CSG.prototype.union = function (csg) {
  30537. var a = new Node(this.clone().polygons);
  30538. var b = new Node(csg.clone().polygons);
  30539. a.clipTo(b);
  30540. b.clipTo(a);
  30541. b.invert();
  30542. b.clipTo(a);
  30543. b.invert();
  30544. a.build(b.allPolygons());
  30545. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30546. };
  30547. CSG.prototype.unionInPlace = function (csg) {
  30548. var a = new Node(this.polygons);
  30549. var b = new Node(csg.polygons);
  30550. a.clipTo(b);
  30551. b.clipTo(a);
  30552. b.invert();
  30553. b.clipTo(a);
  30554. b.invert();
  30555. a.build(b.allPolygons());
  30556. this.polygons = a.allPolygons();
  30557. };
  30558. CSG.prototype.subtract = function (csg) {
  30559. var a = new Node(this.clone().polygons);
  30560. var b = new Node(csg.clone().polygons);
  30561. a.invert();
  30562. a.clipTo(b);
  30563. b.clipTo(a);
  30564. b.invert();
  30565. b.clipTo(a);
  30566. b.invert();
  30567. a.build(b.allPolygons());
  30568. a.invert();
  30569. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30570. };
  30571. CSG.prototype.subtractInPlace = function (csg) {
  30572. var a = new Node(this.polygons);
  30573. var b = new Node(csg.polygons);
  30574. a.invert();
  30575. a.clipTo(b);
  30576. b.clipTo(a);
  30577. b.invert();
  30578. b.clipTo(a);
  30579. b.invert();
  30580. a.build(b.allPolygons());
  30581. a.invert();
  30582. this.polygons = a.allPolygons();
  30583. };
  30584. CSG.prototype.intersect = function (csg) {
  30585. var a = new Node(this.clone().polygons);
  30586. var b = new Node(csg.clone().polygons);
  30587. a.invert();
  30588. b.clipTo(a);
  30589. b.invert();
  30590. a.clipTo(b);
  30591. b.clipTo(a);
  30592. a.build(b.allPolygons());
  30593. a.invert();
  30594. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30595. };
  30596. CSG.prototype.intersectInPlace = function (csg) {
  30597. var a = new Node(this.polygons);
  30598. var b = new Node(csg.polygons);
  30599. a.invert();
  30600. b.clipTo(a);
  30601. b.invert();
  30602. a.clipTo(b);
  30603. b.clipTo(a);
  30604. a.build(b.allPolygons());
  30605. a.invert();
  30606. this.polygons = a.allPolygons();
  30607. };
  30608. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30609. // not modified.
  30610. CSG.prototype.inverse = function () {
  30611. var csg = this.clone();
  30612. csg.inverseInPlace();
  30613. return csg;
  30614. };
  30615. CSG.prototype.inverseInPlace = function () {
  30616. this.polygons.map(function (p) { p.flip(); });
  30617. };
  30618. // This is used to keep meshes transformations so they can be restored
  30619. // when we build back a Babylon Mesh
  30620. // NB : All CSG operations are performed in world coordinates
  30621. CSG.prototype.copyTransformAttributes = function (csg) {
  30622. this.matrix = csg.matrix;
  30623. this.position = csg.position;
  30624. this.rotation = csg.rotation;
  30625. this.scaling = csg.scaling;
  30626. this.rotationQuaternion = csg.rotationQuaternion;
  30627. return this;
  30628. };
  30629. // Build Raw mesh from CSG
  30630. // Coordinates here are in world space
  30631. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30632. var matrix = this.matrix.clone();
  30633. matrix.invert();
  30634. 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;
  30635. if (keepSubMeshes) {
  30636. // Sort Polygons, since subMeshes are indices range
  30637. polygons.sort(function (a, b) {
  30638. if (a.shared.meshId === b.shared.meshId) {
  30639. return a.shared.subMeshId - b.shared.subMeshId;
  30640. }
  30641. else {
  30642. return a.shared.meshId - b.shared.meshId;
  30643. }
  30644. });
  30645. }
  30646. for (var i = 0, il = polygons.length; i < il; i++) {
  30647. polygon = polygons[i];
  30648. // Building SubMeshes
  30649. if (!subMesh_dict[polygon.shared.meshId]) {
  30650. subMesh_dict[polygon.shared.meshId] = {};
  30651. }
  30652. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30653. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30654. indexStart: +Infinity,
  30655. indexEnd: -Infinity,
  30656. materialIndex: polygon.shared.materialIndex
  30657. };
  30658. }
  30659. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30660. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30661. polygonIndices[0] = 0;
  30662. polygonIndices[1] = j - 1;
  30663. polygonIndices[2] = j;
  30664. for (var k = 0; k < 3; k++) {
  30665. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30666. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30667. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30668. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30669. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30670. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30671. // Check if 2 points can be merged
  30672. if (!(typeof vertex_idx !== 'undefined' &&
  30673. normals[vertex_idx * 3] === localNormal.x &&
  30674. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30675. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30676. uvs[vertex_idx * 2] === uv.x &&
  30677. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30678. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30679. uvs.push(uv.x, uv.y);
  30680. normals.push(normal.x, normal.y, normal.z);
  30681. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30682. }
  30683. indices.push(vertex_idx);
  30684. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30685. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30686. currentIndex++;
  30687. }
  30688. }
  30689. }
  30690. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30691. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30692. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30693. mesh.setIndices(indices);
  30694. if (keepSubMeshes) {
  30695. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30696. var materialIndexOffset = 0, materialMaxIndex;
  30697. mesh.subMeshes = new Array();
  30698. for (var m in subMesh_dict) {
  30699. materialMaxIndex = -1;
  30700. for (var sm in subMesh_dict[m]) {
  30701. subMesh_obj = subMesh_dict[m][sm];
  30702. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30703. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30704. }
  30705. materialIndexOffset += ++materialMaxIndex;
  30706. }
  30707. }
  30708. return mesh;
  30709. };
  30710. // Build Mesh from CSG taking material and transforms into account
  30711. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30712. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30713. mesh.material = material;
  30714. mesh.position.copyFrom(this.position);
  30715. mesh.rotation.copyFrom(this.rotation);
  30716. if (this.rotationQuaternion) {
  30717. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30718. }
  30719. mesh.scaling.copyFrom(this.scaling);
  30720. mesh.computeWorldMatrix(true);
  30721. return mesh;
  30722. };
  30723. return CSG;
  30724. })();
  30725. BABYLON.CSG = CSG;
  30726. })(BABYLON || (BABYLON = {}));
  30727. var BABYLON;
  30728. (function (BABYLON) {
  30729. var VRDistortionCorrectionPostProcess = (function (_super) {
  30730. __extends(VRDistortionCorrectionPostProcess, _super);
  30731. //ANY
  30732. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30733. var _this = this;
  30734. _super.call(this, name, "vrDistortionCorrection", [
  30735. 'LensCenter',
  30736. 'Scale',
  30737. 'ScaleIn',
  30738. 'HmdWarpParam'
  30739. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30740. this._isRightEye = isRightEye;
  30741. this._distortionFactors = vrMetrics.distortionK;
  30742. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30743. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30744. this.onSizeChanged = function () {
  30745. _this.aspectRatio = _this.width * .5 / _this.height;
  30746. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30747. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30748. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30749. };
  30750. this.onApply = function (effect) {
  30751. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30752. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30753. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30754. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30755. };
  30756. }
  30757. return VRDistortionCorrectionPostProcess;
  30758. })(BABYLON.PostProcess);
  30759. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30760. })(BABYLON || (BABYLON = {}));
  30761. // Mainly based on these 2 articles :
  30762. // 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
  30763. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30764. var BABYLON;
  30765. (function (BABYLON) {
  30766. (function (JoystickAxis) {
  30767. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30768. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30769. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30770. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30771. var JoystickAxis = BABYLON.JoystickAxis;
  30772. var VirtualJoystick = (function () {
  30773. function VirtualJoystick(leftJoystick) {
  30774. var _this = this;
  30775. if (leftJoystick) {
  30776. this._leftJoystick = true;
  30777. }
  30778. else {
  30779. this._leftJoystick = false;
  30780. }
  30781. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30782. VirtualJoystick._globalJoystickIndex++;
  30783. // By default left & right arrow keys are moving the X
  30784. // and up & down keys are moving the Y
  30785. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30786. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30787. this.reverseLeftRight = false;
  30788. this.reverseUpDown = false;
  30789. // collections of pointers
  30790. this._touches = new BABYLON.SmartCollection();
  30791. this.deltaPosition = BABYLON.Vector3.Zero();
  30792. this._joystickSensibility = 25;
  30793. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30794. this._rotationSpeed = 25;
  30795. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30796. this._rotateOnAxisRelativeToMesh = false;
  30797. this._onResize = function (evt) {
  30798. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30799. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30800. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30801. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30802. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30803. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30804. };
  30805. // injecting a canvas element on top of the canvas 3D game
  30806. if (!VirtualJoystick.vjCanvas) {
  30807. window.addEventListener("resize", this._onResize, false);
  30808. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30809. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30810. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30811. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30812. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30813. VirtualJoystick.vjCanvas.style.width = "100%";
  30814. VirtualJoystick.vjCanvas.style.height = "100%";
  30815. VirtualJoystick.vjCanvas.style.position = "absolute";
  30816. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30817. VirtualJoystick.vjCanvas.style.top = "0px";
  30818. VirtualJoystick.vjCanvas.style.left = "0px";
  30819. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30820. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30821. // Support for jQuery PEP polyfill
  30822. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30823. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30824. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30825. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30826. document.body.appendChild(VirtualJoystick.vjCanvas);
  30827. }
  30828. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30829. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30830. this.pressed = false;
  30831. // default joystick color
  30832. this._joystickColor = "cyan";
  30833. this._joystickPointerID = -1;
  30834. // current joystick position
  30835. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30836. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30837. // origin joystick position
  30838. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30839. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30840. this._onPointerDownHandlerRef = function (evt) {
  30841. _this._onPointerDown(evt);
  30842. };
  30843. this._onPointerMoveHandlerRef = function (evt) {
  30844. _this._onPointerMove(evt);
  30845. };
  30846. this._onPointerOutHandlerRef = function (evt) {
  30847. _this._onPointerUp(evt);
  30848. };
  30849. this._onPointerUpHandlerRef = function (evt) {
  30850. _this._onPointerUp(evt);
  30851. };
  30852. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30853. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30854. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30855. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30856. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30857. evt.preventDefault(); // Disables system menu
  30858. }, false);
  30859. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30860. }
  30861. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30862. this._joystickSensibility = newJoystickSensibility;
  30863. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30864. };
  30865. VirtualJoystick.prototype._onPointerDown = function (e) {
  30866. var positionOnScreenCondition;
  30867. e.preventDefault();
  30868. if (this._leftJoystick === true) {
  30869. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30870. }
  30871. else {
  30872. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30873. }
  30874. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30875. // First contact will be dedicated to the virtual joystick
  30876. this._joystickPointerID = e.pointerId;
  30877. this._joystickPointerStartPos.x = e.clientX;
  30878. this._joystickPointerStartPos.y = e.clientY;
  30879. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30880. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30881. this._deltaJoystickVector.x = 0;
  30882. this._deltaJoystickVector.y = 0;
  30883. this.pressed = true;
  30884. this._touches.add(e.pointerId.toString(), e);
  30885. }
  30886. else {
  30887. // You can only trigger the action buttons with a joystick declared
  30888. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30889. this._action();
  30890. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30891. }
  30892. }
  30893. };
  30894. VirtualJoystick.prototype._onPointerMove = function (e) {
  30895. // If the current pointer is the one associated to the joystick (first touch contact)
  30896. if (this._joystickPointerID == e.pointerId) {
  30897. this._joystickPointerPos.x = e.clientX;
  30898. this._joystickPointerPos.y = e.clientY;
  30899. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30900. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30901. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30902. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30903. switch (this._axisTargetedByLeftAndRight) {
  30904. case JoystickAxis.X:
  30905. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30906. break;
  30907. case JoystickAxis.Y:
  30908. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30909. break;
  30910. case JoystickAxis.Z:
  30911. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30912. break;
  30913. }
  30914. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30915. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30916. switch (this._axisTargetedByUpAndDown) {
  30917. case JoystickAxis.X:
  30918. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30919. break;
  30920. case JoystickAxis.Y:
  30921. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30922. break;
  30923. case JoystickAxis.Z:
  30924. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30925. break;
  30926. }
  30927. }
  30928. else {
  30929. if (this._touches.item(e.pointerId.toString())) {
  30930. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30931. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30932. }
  30933. }
  30934. };
  30935. VirtualJoystick.prototype._onPointerUp = function (e) {
  30936. if (this._joystickPointerID == e.pointerId) {
  30937. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30938. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30939. this._joystickPointerID = -1;
  30940. this.pressed = false;
  30941. }
  30942. else {
  30943. var touch = this._touches.item(e.pointerId.toString());
  30944. if (touch) {
  30945. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30946. }
  30947. }
  30948. this._deltaJoystickVector.x = 0;
  30949. this._deltaJoystickVector.y = 0;
  30950. this._touches.remove(e.pointerId.toString());
  30951. };
  30952. /**
  30953. * Change the color of the virtual joystick
  30954. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30955. */
  30956. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30957. this._joystickColor = newColor;
  30958. };
  30959. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30960. this._action = action;
  30961. };
  30962. // Define which axis you'd like to control for left & right
  30963. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30964. switch (axis) {
  30965. case JoystickAxis.X:
  30966. case JoystickAxis.Y:
  30967. case JoystickAxis.Z:
  30968. this._axisTargetedByLeftAndRight = axis;
  30969. break;
  30970. default:
  30971. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30972. break;
  30973. }
  30974. };
  30975. // Define which axis you'd like to control for up & down
  30976. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30977. switch (axis) {
  30978. case JoystickAxis.X:
  30979. case JoystickAxis.Y:
  30980. case JoystickAxis.Z:
  30981. this._axisTargetedByUpAndDown = axis;
  30982. break;
  30983. default:
  30984. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30985. break;
  30986. }
  30987. };
  30988. VirtualJoystick.prototype._clearCanvas = function () {
  30989. if (this._leftJoystick) {
  30990. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30991. }
  30992. else {
  30993. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30994. }
  30995. };
  30996. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30997. var _this = this;
  30998. if (this.pressed) {
  30999. this._touches.forEach(function (touch) {
  31000. if (touch.pointerId === _this._joystickPointerID) {
  31001. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31002. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31003. VirtualJoystick.vjCanvasContext.beginPath();
  31004. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31005. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31006. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31007. VirtualJoystick.vjCanvasContext.stroke();
  31008. VirtualJoystick.vjCanvasContext.closePath();
  31009. VirtualJoystick.vjCanvasContext.beginPath();
  31010. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31011. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31012. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31013. VirtualJoystick.vjCanvasContext.stroke();
  31014. VirtualJoystick.vjCanvasContext.closePath();
  31015. VirtualJoystick.vjCanvasContext.beginPath();
  31016. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31017. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31018. VirtualJoystick.vjCanvasContext.stroke();
  31019. VirtualJoystick.vjCanvasContext.closePath();
  31020. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31021. }
  31022. else {
  31023. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31024. VirtualJoystick.vjCanvasContext.beginPath();
  31025. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31026. VirtualJoystick.vjCanvasContext.beginPath();
  31027. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31028. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31029. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31030. VirtualJoystick.vjCanvasContext.stroke();
  31031. VirtualJoystick.vjCanvasContext.closePath();
  31032. touch.prevX = touch.x;
  31033. touch.prevY = touch.y;
  31034. }
  31035. ;
  31036. });
  31037. }
  31038. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31039. };
  31040. VirtualJoystick.prototype.releaseCanvas = function () {
  31041. if (VirtualJoystick.vjCanvas) {
  31042. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31043. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31044. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31045. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31046. window.removeEventListener("resize", this._onResize);
  31047. document.body.removeChild(VirtualJoystick.vjCanvas);
  31048. VirtualJoystick.vjCanvas = null;
  31049. }
  31050. };
  31051. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31052. VirtualJoystick._globalJoystickIndex = 0;
  31053. return VirtualJoystick;
  31054. })();
  31055. BABYLON.VirtualJoystick = VirtualJoystick;
  31056. })(BABYLON || (BABYLON = {}));
  31057. var BABYLON;
  31058. (function (BABYLON) {
  31059. // We're mainly based on the logic defined into the FreeCamera code
  31060. var VirtualJoysticksCamera = (function (_super) {
  31061. __extends(VirtualJoysticksCamera, _super);
  31062. function VirtualJoysticksCamera(name, position, scene) {
  31063. _super.call(this, name, position, scene);
  31064. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31065. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31066. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31067. this._leftjoystick.setJoystickSensibility(0.15);
  31068. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31069. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31070. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31071. this._rightjoystick.reverseUpDown = true;
  31072. this._rightjoystick.setJoystickSensibility(0.05);
  31073. this._rightjoystick.setJoystickColor("yellow");
  31074. }
  31075. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31076. return this._leftjoystick;
  31077. };
  31078. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31079. return this._rightjoystick;
  31080. };
  31081. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31082. var speed = this._computeLocalCameraSpeed() * 50;
  31083. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31084. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31085. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31086. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31087. if (!this._leftjoystick.pressed) {
  31088. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31089. }
  31090. if (!this._rightjoystick.pressed) {
  31091. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31092. }
  31093. _super.prototype._checkInputs.call(this);
  31094. };
  31095. VirtualJoysticksCamera.prototype.dispose = function () {
  31096. this._leftjoystick.releaseCanvas();
  31097. _super.prototype.dispose.call(this);
  31098. };
  31099. return VirtualJoysticksCamera;
  31100. })(BABYLON.FreeCamera);
  31101. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31102. })(BABYLON || (BABYLON = {}));
  31103. var BABYLON;
  31104. (function (BABYLON) {
  31105. var AnaglyphPostProcess = (function (_super) {
  31106. __extends(AnaglyphPostProcess, _super);
  31107. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31108. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31109. }
  31110. return AnaglyphPostProcess;
  31111. })(BABYLON.PostProcess);
  31112. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31113. })(BABYLON || (BABYLON = {}));
  31114. var BABYLON;
  31115. (function (BABYLON) {
  31116. var OutlineRenderer = (function () {
  31117. function OutlineRenderer(scene) {
  31118. this._scene = scene;
  31119. }
  31120. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31121. var _this = this;
  31122. if (useOverlay === void 0) { useOverlay = false; }
  31123. var scene = this._scene;
  31124. var engine = this._scene.getEngine();
  31125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31126. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31127. return;
  31128. }
  31129. var mesh = subMesh.getRenderingMesh();
  31130. var material = subMesh.getMaterial();
  31131. engine.enableEffect(this._effect);
  31132. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31133. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31134. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31135. // Bones
  31136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31137. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31138. }
  31139. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31140. // Alpha test
  31141. if (material && material.needAlphaTesting()) {
  31142. var alphaTexture = material.getAlphaTestTexture();
  31143. this._effect.setTexture("diffuseSampler", alphaTexture);
  31144. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31145. }
  31146. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31147. };
  31148. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31149. var defines = [];
  31150. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31151. var mesh = subMesh.getMesh();
  31152. var material = subMesh.getMaterial();
  31153. // Alpha test
  31154. if (material && material.needAlphaTesting()) {
  31155. defines.push("#define ALPHATEST");
  31156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31157. attribs.push(BABYLON.VertexBuffer.UVKind);
  31158. defines.push("#define UV1");
  31159. }
  31160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31161. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31162. defines.push("#define UV2");
  31163. }
  31164. }
  31165. // Bones
  31166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31169. if (mesh.numBoneInfluencers > 4) {
  31170. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31171. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31172. }
  31173. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31174. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31175. }
  31176. else {
  31177. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31178. }
  31179. // Instances
  31180. if (useInstances) {
  31181. defines.push("#define INSTANCES");
  31182. attribs.push("world0");
  31183. attribs.push("world1");
  31184. attribs.push("world2");
  31185. attribs.push("world3");
  31186. }
  31187. // Get correct effect
  31188. var join = defines.join("\n");
  31189. if (this._cachedDefines !== join) {
  31190. this._cachedDefines = join;
  31191. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31192. }
  31193. return this._effect.isReady();
  31194. };
  31195. return OutlineRenderer;
  31196. })();
  31197. BABYLON.OutlineRenderer = OutlineRenderer;
  31198. })(BABYLON || (BABYLON = {}));
  31199. var BABYLON;
  31200. (function (BABYLON) {
  31201. var MeshAssetTask = (function () {
  31202. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31203. this.name = name;
  31204. this.meshesNames = meshesNames;
  31205. this.rootUrl = rootUrl;
  31206. this.sceneFilename = sceneFilename;
  31207. this.isCompleted = false;
  31208. }
  31209. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31210. var _this = this;
  31211. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31212. _this.loadedMeshes = meshes;
  31213. _this.loadedParticleSystems = particleSystems;
  31214. _this.loadedSkeletons = skeletons;
  31215. _this.isCompleted = true;
  31216. if (_this.onSuccess) {
  31217. _this.onSuccess(_this);
  31218. }
  31219. onSuccess();
  31220. }, null, function () {
  31221. if (_this.onError) {
  31222. _this.onError(_this);
  31223. }
  31224. onError();
  31225. });
  31226. };
  31227. return MeshAssetTask;
  31228. })();
  31229. BABYLON.MeshAssetTask = MeshAssetTask;
  31230. var TextFileAssetTask = (function () {
  31231. function TextFileAssetTask(name, url) {
  31232. this.name = name;
  31233. this.url = url;
  31234. this.isCompleted = false;
  31235. }
  31236. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31237. var _this = this;
  31238. BABYLON.Tools.LoadFile(this.url, function (data) {
  31239. _this.text = data;
  31240. _this.isCompleted = true;
  31241. if (_this.onSuccess) {
  31242. _this.onSuccess(_this);
  31243. }
  31244. onSuccess();
  31245. }, null, scene.database, false, function () {
  31246. if (_this.onError) {
  31247. _this.onError(_this);
  31248. }
  31249. onError();
  31250. });
  31251. };
  31252. return TextFileAssetTask;
  31253. })();
  31254. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31255. var BinaryFileAssetTask = (function () {
  31256. function BinaryFileAssetTask(name, url) {
  31257. this.name = name;
  31258. this.url = url;
  31259. this.isCompleted = false;
  31260. }
  31261. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31262. var _this = this;
  31263. BABYLON.Tools.LoadFile(this.url, function (data) {
  31264. _this.data = data;
  31265. _this.isCompleted = true;
  31266. if (_this.onSuccess) {
  31267. _this.onSuccess(_this);
  31268. }
  31269. onSuccess();
  31270. }, null, scene.database, true, function () {
  31271. if (_this.onError) {
  31272. _this.onError(_this);
  31273. }
  31274. onError();
  31275. });
  31276. };
  31277. return BinaryFileAssetTask;
  31278. })();
  31279. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31280. var ImageAssetTask = (function () {
  31281. function ImageAssetTask(name, url) {
  31282. this.name = name;
  31283. this.url = url;
  31284. this.isCompleted = false;
  31285. }
  31286. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31287. var _this = this;
  31288. var img = new Image();
  31289. img.onload = function () {
  31290. _this.image = img;
  31291. _this.isCompleted = true;
  31292. if (_this.onSuccess) {
  31293. _this.onSuccess(_this);
  31294. }
  31295. onSuccess();
  31296. };
  31297. img.onerror = function () {
  31298. if (_this.onError) {
  31299. _this.onError(_this);
  31300. }
  31301. onError();
  31302. };
  31303. img.src = this.url;
  31304. };
  31305. return ImageAssetTask;
  31306. })();
  31307. BABYLON.ImageAssetTask = ImageAssetTask;
  31308. var TextureAssetTask = (function () {
  31309. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31311. this.name = name;
  31312. this.url = url;
  31313. this.noMipmap = noMipmap;
  31314. this.invertY = invertY;
  31315. this.samplingMode = samplingMode;
  31316. this.isCompleted = false;
  31317. }
  31318. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31319. var _this = this;
  31320. var onload = function () {
  31321. _this.isCompleted = true;
  31322. if (_this.onSuccess) {
  31323. _this.onSuccess(_this);
  31324. }
  31325. onSuccess();
  31326. };
  31327. var onerror = function () {
  31328. if (_this.onError) {
  31329. _this.onError(_this);
  31330. }
  31331. onError();
  31332. };
  31333. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31334. };
  31335. return TextureAssetTask;
  31336. })();
  31337. BABYLON.TextureAssetTask = TextureAssetTask;
  31338. var AssetsManager = (function () {
  31339. function AssetsManager(scene) {
  31340. this._tasks = new Array();
  31341. this._waitingTasksCount = 0;
  31342. this.useDefaultLoadingScreen = true;
  31343. this._scene = scene;
  31344. }
  31345. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31346. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31347. this._tasks.push(task);
  31348. return task;
  31349. };
  31350. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31351. var task = new TextFileAssetTask(taskName, url);
  31352. this._tasks.push(task);
  31353. return task;
  31354. };
  31355. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31356. var task = new BinaryFileAssetTask(taskName, url);
  31357. this._tasks.push(task);
  31358. return task;
  31359. };
  31360. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31361. var task = new ImageAssetTask(taskName, url);
  31362. this._tasks.push(task);
  31363. return task;
  31364. };
  31365. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31367. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31368. this._tasks.push(task);
  31369. return task;
  31370. };
  31371. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31372. this._waitingTasksCount--;
  31373. if (this._waitingTasksCount === 0) {
  31374. if (this.onFinish) {
  31375. this.onFinish(this._tasks);
  31376. }
  31377. this._scene.getEngine().hideLoadingUI();
  31378. }
  31379. };
  31380. AssetsManager.prototype._runTask = function (task) {
  31381. var _this = this;
  31382. task.run(this._scene, function () {
  31383. if (_this.onTaskSuccess) {
  31384. _this.onTaskSuccess(task);
  31385. }
  31386. _this._decreaseWaitingTasksCount();
  31387. }, function () {
  31388. if (_this.onTaskError) {
  31389. _this.onTaskError(task);
  31390. }
  31391. _this._decreaseWaitingTasksCount();
  31392. });
  31393. };
  31394. AssetsManager.prototype.reset = function () {
  31395. this._tasks = new Array();
  31396. return this;
  31397. };
  31398. AssetsManager.prototype.load = function () {
  31399. this._waitingTasksCount = this._tasks.length;
  31400. if (this._waitingTasksCount === 0) {
  31401. if (this.onFinish) {
  31402. this.onFinish(this._tasks);
  31403. }
  31404. return this;
  31405. }
  31406. if (this.useDefaultLoadingScreen) {
  31407. this._scene.getEngine().displayLoadingUI();
  31408. }
  31409. for (var index = 0; index < this._tasks.length; index++) {
  31410. var task = this._tasks[index];
  31411. this._runTask(task);
  31412. }
  31413. return this;
  31414. };
  31415. return AssetsManager;
  31416. })();
  31417. BABYLON.AssetsManager = AssetsManager;
  31418. })(BABYLON || (BABYLON = {}));
  31419. var BABYLON;
  31420. (function (BABYLON) {
  31421. var VRDeviceOrientationFreeCamera = (function (_super) {
  31422. __extends(VRDeviceOrientationFreeCamera, _super);
  31423. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31424. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31425. _super.call(this, name, position, scene);
  31426. this._alpha = 0;
  31427. this._beta = 0;
  31428. this._gamma = 0;
  31429. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31430. metrics.compensateDistortion = compensateDistortion;
  31431. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31432. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31433. }
  31434. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31435. this._alpha = +evt.alpha | 0;
  31436. this._beta = +evt.beta | 0;
  31437. this._gamma = +evt.gamma | 0;
  31438. if (this._gamma < 0) {
  31439. this._gamma = 90 + this._gamma;
  31440. }
  31441. else {
  31442. // Incline it in the correct angle.
  31443. this._gamma = 270 - this._gamma;
  31444. }
  31445. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31446. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31447. this.rotation.z = this._beta / 180.0 * Math.PI;
  31448. };
  31449. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31450. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31451. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31452. };
  31453. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31454. _super.prototype.detachControl.call(this, element);
  31455. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31456. };
  31457. return VRDeviceOrientationFreeCamera;
  31458. })(BABYLON.FreeCamera);
  31459. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31460. })(BABYLON || (BABYLON = {}));
  31461. var BABYLON;
  31462. (function (BABYLON) {
  31463. var WebVRFreeCamera = (function (_super) {
  31464. __extends(WebVRFreeCamera, _super);
  31465. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31466. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31467. _super.call(this, name, position, scene);
  31468. this._hmdDevice = null;
  31469. this._sensorDevice = null;
  31470. this._cacheState = null;
  31471. this._cacheQuaternion = new BABYLON.Quaternion();
  31472. this._cacheRotation = BABYLON.Vector3.Zero();
  31473. this._vrEnabled = false;
  31474. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31475. metrics.compensateDistortion = compensateDistortion;
  31476. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31477. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31478. }
  31479. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31480. var size = devices.length;
  31481. var i = 0;
  31482. // Reset devices.
  31483. this._sensorDevice = null;
  31484. this._hmdDevice = null;
  31485. // Search for a HmdDevice.
  31486. while (i < size && this._hmdDevice === null) {
  31487. if (devices[i] instanceof HMDVRDevice) {
  31488. this._hmdDevice = devices[i];
  31489. }
  31490. i++;
  31491. }
  31492. i = 0;
  31493. while (i < size && this._sensorDevice === null) {
  31494. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31495. this._sensorDevice = devices[i];
  31496. }
  31497. i++;
  31498. }
  31499. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31500. };
  31501. WebVRFreeCamera.prototype._checkInputs = function () {
  31502. if (this._vrEnabled) {
  31503. this._cacheState = this._sensorDevice.getState();
  31504. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31505. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31506. this.rotation.x = -this._cacheRotation.z;
  31507. this.rotation.y = -this._cacheRotation.y;
  31508. this.rotation.z = this._cacheRotation.x;
  31509. }
  31510. _super.prototype._checkInputs.call(this);
  31511. };
  31512. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31513. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31514. if (navigator.getVRDevices) {
  31515. navigator.getVRDevices().then(this._getWebVRDevices);
  31516. }
  31517. else if (navigator.mozGetVRDevices) {
  31518. navigator.mozGetVRDevices(this._getWebVRDevices);
  31519. }
  31520. };
  31521. WebVRFreeCamera.prototype.detachControl = function (element) {
  31522. _super.prototype.detachControl.call(this, element);
  31523. this._vrEnabled = false;
  31524. };
  31525. return WebVRFreeCamera;
  31526. })(BABYLON.FreeCamera);
  31527. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31528. })(BABYLON || (BABYLON = {}));
  31529. var BABYLON;
  31530. (function (BABYLON) {
  31531. // Standard optimizations
  31532. var SceneOptimization = (function () {
  31533. function SceneOptimization(priority) {
  31534. if (priority === void 0) { priority = 0; }
  31535. this.priority = priority;
  31536. this.apply = function (scene) {
  31537. return true; // Return true if everything that can be done was applied
  31538. };
  31539. }
  31540. return SceneOptimization;
  31541. })();
  31542. BABYLON.SceneOptimization = SceneOptimization;
  31543. var TextureOptimization = (function (_super) {
  31544. __extends(TextureOptimization, _super);
  31545. function TextureOptimization(priority, maximumSize) {
  31546. var _this = this;
  31547. if (priority === void 0) { priority = 0; }
  31548. if (maximumSize === void 0) { maximumSize = 1024; }
  31549. _super.call(this, priority);
  31550. this.priority = priority;
  31551. this.maximumSize = maximumSize;
  31552. this.apply = function (scene) {
  31553. var allDone = true;
  31554. for (var index = 0; index < scene.textures.length; index++) {
  31555. var texture = scene.textures[index];
  31556. if (!texture.canRescale) {
  31557. continue;
  31558. }
  31559. var currentSize = texture.getSize();
  31560. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31561. if (maxDimension > _this.maximumSize) {
  31562. texture.scale(0.5);
  31563. allDone = false;
  31564. }
  31565. }
  31566. return allDone;
  31567. };
  31568. }
  31569. return TextureOptimization;
  31570. })(SceneOptimization);
  31571. BABYLON.TextureOptimization = TextureOptimization;
  31572. var HardwareScalingOptimization = (function (_super) {
  31573. __extends(HardwareScalingOptimization, _super);
  31574. function HardwareScalingOptimization(priority, maximumScale) {
  31575. var _this = this;
  31576. if (priority === void 0) { priority = 0; }
  31577. if (maximumScale === void 0) { maximumScale = 2; }
  31578. _super.call(this, priority);
  31579. this.priority = priority;
  31580. this.maximumScale = maximumScale;
  31581. this._currentScale = 1;
  31582. this.apply = function (scene) {
  31583. _this._currentScale++;
  31584. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31585. return _this._currentScale >= _this.maximumScale;
  31586. };
  31587. }
  31588. return HardwareScalingOptimization;
  31589. })(SceneOptimization);
  31590. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31591. var ShadowsOptimization = (function (_super) {
  31592. __extends(ShadowsOptimization, _super);
  31593. function ShadowsOptimization() {
  31594. _super.apply(this, arguments);
  31595. this.apply = function (scene) {
  31596. scene.shadowsEnabled = false;
  31597. return true;
  31598. };
  31599. }
  31600. return ShadowsOptimization;
  31601. })(SceneOptimization);
  31602. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31603. var PostProcessesOptimization = (function (_super) {
  31604. __extends(PostProcessesOptimization, _super);
  31605. function PostProcessesOptimization() {
  31606. _super.apply(this, arguments);
  31607. this.apply = function (scene) {
  31608. scene.postProcessesEnabled = false;
  31609. return true;
  31610. };
  31611. }
  31612. return PostProcessesOptimization;
  31613. })(SceneOptimization);
  31614. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31615. var LensFlaresOptimization = (function (_super) {
  31616. __extends(LensFlaresOptimization, _super);
  31617. function LensFlaresOptimization() {
  31618. _super.apply(this, arguments);
  31619. this.apply = function (scene) {
  31620. scene.lensFlaresEnabled = false;
  31621. return true;
  31622. };
  31623. }
  31624. return LensFlaresOptimization;
  31625. })(SceneOptimization);
  31626. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31627. var ParticlesOptimization = (function (_super) {
  31628. __extends(ParticlesOptimization, _super);
  31629. function ParticlesOptimization() {
  31630. _super.apply(this, arguments);
  31631. this.apply = function (scene) {
  31632. scene.particlesEnabled = false;
  31633. return true;
  31634. };
  31635. }
  31636. return ParticlesOptimization;
  31637. })(SceneOptimization);
  31638. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31639. var RenderTargetsOptimization = (function (_super) {
  31640. __extends(RenderTargetsOptimization, _super);
  31641. function RenderTargetsOptimization() {
  31642. _super.apply(this, arguments);
  31643. this.apply = function (scene) {
  31644. scene.renderTargetsEnabled = false;
  31645. return true;
  31646. };
  31647. }
  31648. return RenderTargetsOptimization;
  31649. })(SceneOptimization);
  31650. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31651. var MergeMeshesOptimization = (function (_super) {
  31652. __extends(MergeMeshesOptimization, _super);
  31653. function MergeMeshesOptimization() {
  31654. var _this = this;
  31655. _super.apply(this, arguments);
  31656. this._canBeMerged = function (abstractMesh) {
  31657. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31658. return false;
  31659. }
  31660. var mesh = abstractMesh;
  31661. if (!mesh.isVisible || !mesh.isEnabled()) {
  31662. return false;
  31663. }
  31664. if (mesh.instances.length > 0) {
  31665. return false;
  31666. }
  31667. if (mesh.skeleton || mesh.hasLODLevels) {
  31668. return false;
  31669. }
  31670. if (mesh.parent) {
  31671. return false;
  31672. }
  31673. return true;
  31674. };
  31675. this.apply = function (scene, updateSelectionTree) {
  31676. var globalPool = scene.meshes.slice(0);
  31677. var globalLength = globalPool.length;
  31678. for (var index = 0; index < globalLength; index++) {
  31679. var currentPool = new Array();
  31680. var current = globalPool[index];
  31681. // Checks
  31682. if (!_this._canBeMerged(current)) {
  31683. continue;
  31684. }
  31685. currentPool.push(current);
  31686. // Find compatible meshes
  31687. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31688. var otherMesh = globalPool[subIndex];
  31689. if (!_this._canBeMerged(otherMesh)) {
  31690. continue;
  31691. }
  31692. if (otherMesh.material !== current.material) {
  31693. continue;
  31694. }
  31695. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31696. continue;
  31697. }
  31698. currentPool.push(otherMesh);
  31699. globalLength--;
  31700. globalPool.splice(subIndex, 1);
  31701. subIndex--;
  31702. }
  31703. if (currentPool.length < 2) {
  31704. continue;
  31705. }
  31706. // Merge meshes
  31707. BABYLON.Mesh.MergeMeshes(currentPool);
  31708. }
  31709. if (updateSelectionTree != undefined) {
  31710. if (updateSelectionTree) {
  31711. scene.createOrUpdateSelectionOctree();
  31712. }
  31713. }
  31714. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31715. scene.createOrUpdateSelectionOctree();
  31716. }
  31717. return true;
  31718. };
  31719. }
  31720. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31721. get: function () {
  31722. return MergeMeshesOptimization._UpdateSelectionTree;
  31723. },
  31724. set: function (value) {
  31725. MergeMeshesOptimization._UpdateSelectionTree = value;
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. MergeMeshesOptimization._UpdateSelectionTree = false;
  31731. return MergeMeshesOptimization;
  31732. })(SceneOptimization);
  31733. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31734. // Options
  31735. var SceneOptimizerOptions = (function () {
  31736. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31737. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31738. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31739. this.targetFrameRate = targetFrameRate;
  31740. this.trackerDuration = trackerDuration;
  31741. this.optimizations = new Array();
  31742. }
  31743. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31744. var result = new SceneOptimizerOptions(targetFrameRate);
  31745. var priority = 0;
  31746. result.optimizations.push(new MergeMeshesOptimization(priority));
  31747. result.optimizations.push(new ShadowsOptimization(priority));
  31748. result.optimizations.push(new LensFlaresOptimization(priority));
  31749. // Next priority
  31750. priority++;
  31751. result.optimizations.push(new PostProcessesOptimization(priority));
  31752. result.optimizations.push(new ParticlesOptimization(priority));
  31753. // Next priority
  31754. priority++;
  31755. result.optimizations.push(new TextureOptimization(priority, 1024));
  31756. return result;
  31757. };
  31758. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31759. var result = new SceneOptimizerOptions(targetFrameRate);
  31760. var priority = 0;
  31761. result.optimizations.push(new MergeMeshesOptimization(priority));
  31762. result.optimizations.push(new ShadowsOptimization(priority));
  31763. result.optimizations.push(new LensFlaresOptimization(priority));
  31764. // Next priority
  31765. priority++;
  31766. result.optimizations.push(new PostProcessesOptimization(priority));
  31767. result.optimizations.push(new ParticlesOptimization(priority));
  31768. // Next priority
  31769. priority++;
  31770. result.optimizations.push(new TextureOptimization(priority, 512));
  31771. // Next priority
  31772. priority++;
  31773. result.optimizations.push(new RenderTargetsOptimization(priority));
  31774. // Next priority
  31775. priority++;
  31776. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31777. return result;
  31778. };
  31779. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31780. var result = new SceneOptimizerOptions(targetFrameRate);
  31781. var priority = 0;
  31782. result.optimizations.push(new MergeMeshesOptimization(priority));
  31783. result.optimizations.push(new ShadowsOptimization(priority));
  31784. result.optimizations.push(new LensFlaresOptimization(priority));
  31785. // Next priority
  31786. priority++;
  31787. result.optimizations.push(new PostProcessesOptimization(priority));
  31788. result.optimizations.push(new ParticlesOptimization(priority));
  31789. // Next priority
  31790. priority++;
  31791. result.optimizations.push(new TextureOptimization(priority, 256));
  31792. // Next priority
  31793. priority++;
  31794. result.optimizations.push(new RenderTargetsOptimization(priority));
  31795. // Next priority
  31796. priority++;
  31797. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31798. return result;
  31799. };
  31800. return SceneOptimizerOptions;
  31801. })();
  31802. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31803. // Scene optimizer tool
  31804. var SceneOptimizer = (function () {
  31805. function SceneOptimizer() {
  31806. }
  31807. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31808. // TODO: add an epsilon
  31809. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31810. if (onSuccess) {
  31811. onSuccess();
  31812. }
  31813. return;
  31814. }
  31815. // Apply current level of optimizations
  31816. var allDone = true;
  31817. var noOptimizationApplied = true;
  31818. for (var index = 0; index < options.optimizations.length; index++) {
  31819. var optimization = options.optimizations[index];
  31820. if (optimization.priority === currentPriorityLevel) {
  31821. noOptimizationApplied = false;
  31822. allDone = allDone && optimization.apply(scene);
  31823. }
  31824. }
  31825. // If no optimization was applied, this is a failure :(
  31826. if (noOptimizationApplied) {
  31827. if (onFailure) {
  31828. onFailure();
  31829. }
  31830. return;
  31831. }
  31832. // If all optimizations were done, move to next level
  31833. if (allDone) {
  31834. currentPriorityLevel++;
  31835. }
  31836. // Let's the system running for a specific amount of time before checking FPS
  31837. scene.executeWhenReady(function () {
  31838. setTimeout(function () {
  31839. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31840. }, options.trackerDuration);
  31841. });
  31842. };
  31843. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31844. if (!options) {
  31845. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31846. }
  31847. // Let's the system running for a specific amount of time before checking FPS
  31848. scene.executeWhenReady(function () {
  31849. setTimeout(function () {
  31850. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31851. }, options.trackerDuration);
  31852. });
  31853. };
  31854. return SceneOptimizer;
  31855. })();
  31856. BABYLON.SceneOptimizer = SceneOptimizer;
  31857. })(BABYLON || (BABYLON = {}));
  31858. var BABYLON;
  31859. (function (BABYLON) {
  31860. var Internals;
  31861. (function (Internals) {
  31862. var MeshLODLevel = (function () {
  31863. function MeshLODLevel(distance, mesh) {
  31864. this.distance = distance;
  31865. this.mesh = mesh;
  31866. }
  31867. return MeshLODLevel;
  31868. })();
  31869. Internals.MeshLODLevel = MeshLODLevel;
  31870. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31871. })(BABYLON || (BABYLON = {}));
  31872. var BABYLON;
  31873. (function (BABYLON) {
  31874. var RawTexture = (function (_super) {
  31875. __extends(RawTexture, _super);
  31876. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31877. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31878. if (invertY === void 0) { invertY = false; }
  31879. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31880. _super.call(this, null, scene, !generateMipMaps, invertY);
  31881. this.format = format;
  31882. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31883. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31884. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31885. }
  31886. RawTexture.prototype.update = function (data) {
  31887. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31888. };
  31889. // Statics
  31890. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31892. if (invertY === void 0) { invertY = false; }
  31893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31894. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31895. };
  31896. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31897. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31898. if (invertY === void 0) { invertY = false; }
  31899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31900. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31901. };
  31902. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31903. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31904. if (invertY === void 0) { invertY = false; }
  31905. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31906. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31907. };
  31908. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31909. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31910. if (invertY === void 0) { invertY = false; }
  31911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31912. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31913. };
  31914. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31915. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31916. if (invertY === void 0) { invertY = false; }
  31917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31918. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31919. };
  31920. return RawTexture;
  31921. })(BABYLON.Texture);
  31922. BABYLON.RawTexture = RawTexture;
  31923. })(BABYLON || (BABYLON = {}));
  31924. var BABYLON;
  31925. (function (BABYLON) {
  31926. var IndexedVector2 = (function (_super) {
  31927. __extends(IndexedVector2, _super);
  31928. function IndexedVector2(original, index) {
  31929. _super.call(this, original.x, original.y);
  31930. this.index = index;
  31931. }
  31932. return IndexedVector2;
  31933. })(BABYLON.Vector2);
  31934. var PolygonPoints = (function () {
  31935. function PolygonPoints() {
  31936. this.elements = new Array();
  31937. }
  31938. PolygonPoints.prototype.add = function (originalPoints) {
  31939. var _this = this;
  31940. var result = new Array();
  31941. originalPoints.forEach(function (point) {
  31942. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31943. var newPoint = new IndexedVector2(point, _this.elements.length);
  31944. result.push(newPoint);
  31945. _this.elements.push(newPoint);
  31946. }
  31947. });
  31948. return result;
  31949. };
  31950. PolygonPoints.prototype.computeBounds = function () {
  31951. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31952. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31953. this.elements.forEach(function (point) {
  31954. // x
  31955. if (point.x < lmin.x) {
  31956. lmin.x = point.x;
  31957. }
  31958. else if (point.x > lmax.x) {
  31959. lmax.x = point.x;
  31960. }
  31961. // y
  31962. if (point.y < lmin.y) {
  31963. lmin.y = point.y;
  31964. }
  31965. else if (point.y > lmax.y) {
  31966. lmax.y = point.y;
  31967. }
  31968. });
  31969. return {
  31970. min: lmin,
  31971. max: lmax,
  31972. width: lmax.x - lmin.x,
  31973. height: lmax.y - lmin.y
  31974. };
  31975. };
  31976. return PolygonPoints;
  31977. })();
  31978. var Polygon = (function () {
  31979. function Polygon() {
  31980. }
  31981. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31982. return [
  31983. new BABYLON.Vector2(xmin, ymin),
  31984. new BABYLON.Vector2(xmax, ymin),
  31985. new BABYLON.Vector2(xmax, ymax),
  31986. new BABYLON.Vector2(xmin, ymax)
  31987. ];
  31988. };
  31989. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31990. if (cx === void 0) { cx = 0; }
  31991. if (cy === void 0) { cy = 0; }
  31992. if (numberOfSides === void 0) { numberOfSides = 32; }
  31993. var result = new Array();
  31994. var angle = 0;
  31995. var increment = (Math.PI * 2) / numberOfSides;
  31996. for (var i = 0; i < numberOfSides; i++) {
  31997. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31998. angle -= increment;
  31999. }
  32000. return result;
  32001. };
  32002. Polygon.Parse = function (input) {
  32003. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32004. var i, result = [];
  32005. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32006. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32007. }
  32008. return result;
  32009. };
  32010. Polygon.StartingAt = function (x, y) {
  32011. return BABYLON.Path2.StartingAt(x, y);
  32012. };
  32013. return Polygon;
  32014. })();
  32015. BABYLON.Polygon = Polygon;
  32016. var PolygonMeshBuilder = (function () {
  32017. function PolygonMeshBuilder(name, contours, scene) {
  32018. this._points = new PolygonPoints();
  32019. this._outlinepoints = new PolygonPoints();
  32020. this._holes = [];
  32021. if (!("poly2tri" in window)) {
  32022. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32023. }
  32024. this._name = name;
  32025. this._scene = scene;
  32026. var points;
  32027. if (contours instanceof BABYLON.Path2) {
  32028. points = contours.getPoints();
  32029. }
  32030. else {
  32031. points = contours;
  32032. }
  32033. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32034. this._outlinepoints.add(points);
  32035. }
  32036. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32037. this._swctx.addHole(this._points.add(hole));
  32038. var holepoints = new PolygonPoints();
  32039. holepoints.add(hole);
  32040. this._holes.push(holepoints);
  32041. return this;
  32042. };
  32043. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32044. var _this = this;
  32045. if (updatable === void 0) { updatable = false; }
  32046. var result = new BABYLON.Mesh(this._name, this._scene);
  32047. var normals = [];
  32048. var positions = [];
  32049. var uvs = [];
  32050. var bounds = this._points.computeBounds();
  32051. this._points.elements.forEach(function (p) {
  32052. normals.push(0, 1.0, 0);
  32053. positions.push(p.x, 0, p.y);
  32054. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32055. });
  32056. var indices = [];
  32057. this._swctx.triangulate();
  32058. this._swctx.getTriangles().forEach(function (triangle) {
  32059. triangle.getPoints().forEach(function (point) {
  32060. indices.push(point.index);
  32061. });
  32062. });
  32063. if (depth > 0) {
  32064. var positionscount = (positions.length / 3); //get the current pointcount
  32065. this._points.elements.forEach(function (p) {
  32066. normals.push(0, -1.0, 0);
  32067. positions.push(p.x, -depth, p.y);
  32068. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32069. });
  32070. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32071. var p2;
  32072. var poscounter = 0;
  32073. this._swctx.getTriangles().forEach(function (triangle) {
  32074. triangle.getPoints().forEach(function (point) {
  32075. switch (poscounter) {
  32076. case 0:
  32077. p1 = point;
  32078. break;
  32079. case 1:
  32080. p2 = point;
  32081. break;
  32082. case 2:
  32083. indices.push(point.index + positionscount);
  32084. indices.push(p2.index + positionscount);
  32085. indices.push(p1.index + positionscount);
  32086. poscounter = -1;
  32087. break;
  32088. }
  32089. poscounter++;
  32090. //indices.push((<IndexedVector2>point).index + positionscount);
  32091. });
  32092. });
  32093. //Add the sides
  32094. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32095. this._holes.forEach(function (hole) {
  32096. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32097. });
  32098. }
  32099. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32100. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32101. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32102. result.setIndices(indices);
  32103. return result;
  32104. };
  32105. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32106. var StartIndex = positions.length / 3;
  32107. var ulength = 0;
  32108. for (var i = 0; i < points.elements.length; i++) {
  32109. var p = points.elements[i];
  32110. var p1;
  32111. if ((i + 1) > points.elements.length - 1) {
  32112. p1 = points.elements[0];
  32113. }
  32114. else {
  32115. p1 = points.elements[i + 1];
  32116. }
  32117. positions.push(p.x, 0, p.y);
  32118. positions.push(p.x, -depth, p.y);
  32119. positions.push(p1.x, 0, p1.y);
  32120. positions.push(p1.x, -depth, p1.y);
  32121. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32122. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32123. var v3 = v2.subtract(v1);
  32124. var v4 = new BABYLON.Vector3(0, 1, 0);
  32125. var vn = BABYLON.Vector3.Cross(v3, v4);
  32126. vn = vn.normalize();
  32127. uvs.push(ulength / bounds.width, 0);
  32128. uvs.push(ulength / bounds.width, 1);
  32129. ulength += v3.length();
  32130. uvs.push((ulength / bounds.width), 0);
  32131. uvs.push((ulength / bounds.width), 1);
  32132. if (!flip) {
  32133. normals.push(-vn.x, -vn.y, -vn.z);
  32134. normals.push(-vn.x, -vn.y, -vn.z);
  32135. normals.push(-vn.x, -vn.y, -vn.z);
  32136. normals.push(-vn.x, -vn.y, -vn.z);
  32137. indices.push(StartIndex);
  32138. indices.push(StartIndex + 1);
  32139. indices.push(StartIndex + 2);
  32140. indices.push(StartIndex + 1);
  32141. indices.push(StartIndex + 3);
  32142. indices.push(StartIndex + 2);
  32143. }
  32144. else {
  32145. normals.push(vn.x, vn.y, vn.z);
  32146. normals.push(vn.x, vn.y, vn.z);
  32147. normals.push(vn.x, vn.y, vn.z);
  32148. normals.push(vn.x, vn.y, vn.z);
  32149. indices.push(StartIndex);
  32150. indices.push(StartIndex + 2);
  32151. indices.push(StartIndex + 1);
  32152. indices.push(StartIndex + 1);
  32153. indices.push(StartIndex + 2);
  32154. indices.push(StartIndex + 3);
  32155. }
  32156. StartIndex += 4;
  32157. }
  32158. ;
  32159. };
  32160. return PolygonMeshBuilder;
  32161. })();
  32162. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32163. })(BABYLON || (BABYLON = {}));
  32164. var BABYLON;
  32165. (function (BABYLON) {
  32166. var Octree = (function () {
  32167. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32168. if (maxDepth === void 0) { maxDepth = 2; }
  32169. this.maxDepth = maxDepth;
  32170. this.dynamicContent = new Array();
  32171. this._maxBlockCapacity = maxBlockCapacity || 64;
  32172. this._selectionContent = new BABYLON.SmartArray(1024);
  32173. this._creationFunc = creationFunc;
  32174. }
  32175. // Methods
  32176. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32177. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32178. };
  32179. Octree.prototype.addMesh = function (entry) {
  32180. for (var index = 0; index < this.blocks.length; index++) {
  32181. var block = this.blocks[index];
  32182. block.addEntry(entry);
  32183. }
  32184. };
  32185. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32186. this._selectionContent.reset();
  32187. for (var index = 0; index < this.blocks.length; index++) {
  32188. var block = this.blocks[index];
  32189. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32190. }
  32191. if (allowDuplicate) {
  32192. this._selectionContent.concat(this.dynamicContent);
  32193. }
  32194. else {
  32195. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32196. }
  32197. return this._selectionContent;
  32198. };
  32199. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32200. this._selectionContent.reset();
  32201. for (var index = 0; index < this.blocks.length; index++) {
  32202. var block = this.blocks[index];
  32203. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32204. }
  32205. if (allowDuplicate) {
  32206. this._selectionContent.concat(this.dynamicContent);
  32207. }
  32208. else {
  32209. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32210. }
  32211. return this._selectionContent;
  32212. };
  32213. Octree.prototype.intersectsRay = function (ray) {
  32214. this._selectionContent.reset();
  32215. for (var index = 0; index < this.blocks.length; index++) {
  32216. var block = this.blocks[index];
  32217. block.intersectsRay(ray, this._selectionContent);
  32218. }
  32219. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32220. return this._selectionContent;
  32221. };
  32222. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32223. target.blocks = new Array();
  32224. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32225. // Segmenting space
  32226. for (var x = 0; x < 2; x++) {
  32227. for (var y = 0; y < 2; y++) {
  32228. for (var z = 0; z < 2; z++) {
  32229. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32230. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32231. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32232. block.addEntries(entries);
  32233. target.blocks.push(block);
  32234. }
  32235. }
  32236. }
  32237. };
  32238. Octree.CreationFuncForMeshes = function (entry, block) {
  32239. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32240. block.entries.push(entry);
  32241. }
  32242. };
  32243. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32244. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32245. block.entries.push(entry);
  32246. }
  32247. };
  32248. return Octree;
  32249. })();
  32250. BABYLON.Octree = Octree;
  32251. })(BABYLON || (BABYLON = {}));
  32252. var BABYLON;
  32253. (function (BABYLON) {
  32254. var OctreeBlock = (function () {
  32255. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32256. this.entries = new Array();
  32257. this._boundingVectors = new Array();
  32258. this._capacity = capacity;
  32259. this._depth = depth;
  32260. this._maxDepth = maxDepth;
  32261. this._creationFunc = creationFunc;
  32262. this._minPoint = minPoint;
  32263. this._maxPoint = maxPoint;
  32264. this._boundingVectors.push(minPoint.clone());
  32265. this._boundingVectors.push(maxPoint.clone());
  32266. this._boundingVectors.push(minPoint.clone());
  32267. this._boundingVectors[2].x = maxPoint.x;
  32268. this._boundingVectors.push(minPoint.clone());
  32269. this._boundingVectors[3].y = maxPoint.y;
  32270. this._boundingVectors.push(minPoint.clone());
  32271. this._boundingVectors[4].z = maxPoint.z;
  32272. this._boundingVectors.push(maxPoint.clone());
  32273. this._boundingVectors[5].z = minPoint.z;
  32274. this._boundingVectors.push(maxPoint.clone());
  32275. this._boundingVectors[6].x = minPoint.x;
  32276. this._boundingVectors.push(maxPoint.clone());
  32277. this._boundingVectors[7].y = minPoint.y;
  32278. }
  32279. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32280. // Property
  32281. get: function () {
  32282. return this._capacity;
  32283. },
  32284. enumerable: true,
  32285. configurable: true
  32286. });
  32287. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32288. get: function () {
  32289. return this._minPoint;
  32290. },
  32291. enumerable: true,
  32292. configurable: true
  32293. });
  32294. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32295. get: function () {
  32296. return this._maxPoint;
  32297. },
  32298. enumerable: true,
  32299. configurable: true
  32300. });
  32301. // Methods
  32302. OctreeBlock.prototype.addEntry = function (entry) {
  32303. if (this.blocks) {
  32304. for (var index = 0; index < this.blocks.length; index++) {
  32305. var block = this.blocks[index];
  32306. block.addEntry(entry);
  32307. }
  32308. return;
  32309. }
  32310. this._creationFunc(entry, this);
  32311. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32312. this.createInnerBlocks();
  32313. }
  32314. };
  32315. OctreeBlock.prototype.addEntries = function (entries) {
  32316. for (var index = 0; index < entries.length; index++) {
  32317. var mesh = entries[index];
  32318. this.addEntry(mesh);
  32319. }
  32320. };
  32321. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32322. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32323. if (this.blocks) {
  32324. for (var index = 0; index < this.blocks.length; index++) {
  32325. var block = this.blocks[index];
  32326. block.select(frustumPlanes, selection, allowDuplicate);
  32327. }
  32328. return;
  32329. }
  32330. if (allowDuplicate) {
  32331. selection.concat(this.entries);
  32332. }
  32333. else {
  32334. selection.concatWithNoDuplicate(this.entries);
  32335. }
  32336. }
  32337. };
  32338. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32339. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32340. if (this.blocks) {
  32341. for (var index = 0; index < this.blocks.length; index++) {
  32342. var block = this.blocks[index];
  32343. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32344. }
  32345. return;
  32346. }
  32347. if (allowDuplicate) {
  32348. selection.concat(this.entries);
  32349. }
  32350. else {
  32351. selection.concatWithNoDuplicate(this.entries);
  32352. }
  32353. }
  32354. };
  32355. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32356. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32357. if (this.blocks) {
  32358. for (var index = 0; index < this.blocks.length; index++) {
  32359. var block = this.blocks[index];
  32360. block.intersectsRay(ray, selection);
  32361. }
  32362. return;
  32363. }
  32364. selection.concatWithNoDuplicate(this.entries);
  32365. }
  32366. };
  32367. OctreeBlock.prototype.createInnerBlocks = function () {
  32368. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32369. };
  32370. return OctreeBlock;
  32371. })();
  32372. BABYLON.OctreeBlock = OctreeBlock;
  32373. })(BABYLON || (BABYLON = {}));
  32374. var BABYLON;
  32375. (function (BABYLON) {
  32376. var BlurPostProcess = (function (_super) {
  32377. __extends(BlurPostProcess, _super);
  32378. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32379. var _this = this;
  32380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32381. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32382. this.direction = direction;
  32383. this.blurWidth = blurWidth;
  32384. this.onApply = function (effect) {
  32385. effect.setFloat2("screenSize", _this.width, _this.height);
  32386. effect.setVector2("direction", _this.direction);
  32387. effect.setFloat("blurWidth", _this.blurWidth);
  32388. };
  32389. }
  32390. return BlurPostProcess;
  32391. })(BABYLON.PostProcess);
  32392. BABYLON.BlurPostProcess = BlurPostProcess;
  32393. })(BABYLON || (BABYLON = {}));
  32394. var BABYLON;
  32395. (function (BABYLON) {
  32396. var RefractionPostProcess = (function (_super) {
  32397. __extends(RefractionPostProcess, _super);
  32398. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32399. var _this = this;
  32400. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32401. this.color = color;
  32402. this.depth = depth;
  32403. this.colorLevel = colorLevel;
  32404. this.onActivate = function (cam) {
  32405. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32406. };
  32407. this.onApply = function (effect) {
  32408. effect.setColor3("baseColor", _this.color);
  32409. effect.setFloat("depth", _this.depth);
  32410. effect.setFloat("colorLevel", _this.colorLevel);
  32411. effect.setTexture("refractionSampler", _this._refRexture);
  32412. };
  32413. }
  32414. // Methods
  32415. RefractionPostProcess.prototype.dispose = function (camera) {
  32416. if (this._refRexture) {
  32417. this._refRexture.dispose();
  32418. }
  32419. _super.prototype.dispose.call(this, camera);
  32420. };
  32421. return RefractionPostProcess;
  32422. })(BABYLON.PostProcess);
  32423. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32424. })(BABYLON || (BABYLON = {}));
  32425. var BABYLON;
  32426. (function (BABYLON) {
  32427. var BlackAndWhitePostProcess = (function (_super) {
  32428. __extends(BlackAndWhitePostProcess, _super);
  32429. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32430. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32431. }
  32432. return BlackAndWhitePostProcess;
  32433. })(BABYLON.PostProcess);
  32434. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32435. })(BABYLON || (BABYLON = {}));
  32436. var BABYLON;
  32437. (function (BABYLON) {
  32438. var ConvolutionPostProcess = (function (_super) {
  32439. __extends(ConvolutionPostProcess, _super);
  32440. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32441. var _this = this;
  32442. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32443. this.kernel = kernel;
  32444. this.onApply = function (effect) {
  32445. effect.setFloat2("screenSize", _this.width, _this.height);
  32446. effect.setArray("kernel", _this.kernel);
  32447. };
  32448. }
  32449. // Statics
  32450. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32451. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32452. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32453. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32454. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32455. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32456. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32457. return ConvolutionPostProcess;
  32458. })(BABYLON.PostProcess);
  32459. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32460. })(BABYLON || (BABYLON = {}));
  32461. var BABYLON;
  32462. (function (BABYLON) {
  32463. var FilterPostProcess = (function (_super) {
  32464. __extends(FilterPostProcess, _super);
  32465. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32466. var _this = this;
  32467. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32468. this.kernelMatrix = kernelMatrix;
  32469. this.onApply = function (effect) {
  32470. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32471. };
  32472. }
  32473. return FilterPostProcess;
  32474. })(BABYLON.PostProcess);
  32475. BABYLON.FilterPostProcess = FilterPostProcess;
  32476. })(BABYLON || (BABYLON = {}));
  32477. var BABYLON;
  32478. (function (BABYLON) {
  32479. var FxaaPostProcess = (function (_super) {
  32480. __extends(FxaaPostProcess, _super);
  32481. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32482. var _this = this;
  32483. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32484. this.onSizeChanged = function () {
  32485. _this.texelWidth = 1.0 / _this.width;
  32486. _this.texelHeight = 1.0 / _this.height;
  32487. };
  32488. this.onApply = function (effect) {
  32489. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32490. };
  32491. }
  32492. return FxaaPostProcess;
  32493. })(BABYLON.PostProcess);
  32494. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32495. })(BABYLON || (BABYLON = {}));
  32496. var BABYLON;
  32497. (function (BABYLON) {
  32498. var StereoscopicInterlacePostProcess = (function (_super) {
  32499. __extends(StereoscopicInterlacePostProcess, _super);
  32500. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32501. var _this = this;
  32502. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32503. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32504. this.onSizeChanged = function () {
  32505. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32506. };
  32507. this.onApply = function (effect) {
  32508. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32509. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32510. };
  32511. }
  32512. return StereoscopicInterlacePostProcess;
  32513. })(BABYLON.PostProcess);
  32514. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32515. })(BABYLON || (BABYLON = {}));
  32516. var BABYLON;
  32517. (function (BABYLON) {
  32518. var LensFlare = (function () {
  32519. function LensFlare(size, position, color, imgUrl, system) {
  32520. this.size = size;
  32521. this.position = position;
  32522. this.dispose = function () {
  32523. if (this.texture) {
  32524. this.texture.dispose();
  32525. }
  32526. // Remove from scene
  32527. var index = this._system.lensFlares.indexOf(this);
  32528. this._system.lensFlares.splice(index, 1);
  32529. };
  32530. this.color = color || new BABYLON.Color3(1, 1, 1);
  32531. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32532. this._system = system;
  32533. system.lensFlares.push(this);
  32534. }
  32535. return LensFlare;
  32536. })();
  32537. BABYLON.LensFlare = LensFlare;
  32538. })(BABYLON || (BABYLON = {}));
  32539. var BABYLON;
  32540. (function (BABYLON) {
  32541. var LensFlareSystem = (function () {
  32542. function LensFlareSystem(name, emitter, scene) {
  32543. this.name = name;
  32544. this.lensFlares = new Array();
  32545. this.borderLimit = 300;
  32546. this.layerMask = 0x0FFFFFFF;
  32547. this._vertexDeclaration = [2];
  32548. this._vertexStrideSize = 2 * 4;
  32549. this._isEnabled = true;
  32550. this._scene = scene;
  32551. this._emitter = emitter;
  32552. scene.lensFlareSystems.push(this);
  32553. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32554. // VBO
  32555. var vertices = [];
  32556. vertices.push(1, 1);
  32557. vertices.push(-1, 1);
  32558. vertices.push(-1, -1);
  32559. vertices.push(1, -1);
  32560. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32561. // Indices
  32562. var indices = [];
  32563. indices.push(0);
  32564. indices.push(1);
  32565. indices.push(2);
  32566. indices.push(0);
  32567. indices.push(2);
  32568. indices.push(3);
  32569. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32570. // Effects
  32571. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32572. }
  32573. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32574. get: function () {
  32575. return this._isEnabled;
  32576. },
  32577. set: function (value) {
  32578. this._isEnabled = value;
  32579. },
  32580. enumerable: true,
  32581. configurable: true
  32582. });
  32583. LensFlareSystem.prototype.getScene = function () {
  32584. return this._scene;
  32585. };
  32586. LensFlareSystem.prototype.getEmitter = function () {
  32587. return this._emitter;
  32588. };
  32589. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32590. this._emitter = newEmitter;
  32591. };
  32592. LensFlareSystem.prototype.getEmitterPosition = function () {
  32593. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32594. };
  32595. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32596. var position = this.getEmitterPosition();
  32597. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32598. this._positionX = position.x;
  32599. this._positionY = position.y;
  32600. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32601. if (position.z > 0) {
  32602. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32603. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32604. return true;
  32605. }
  32606. }
  32607. return false;
  32608. };
  32609. LensFlareSystem.prototype._isVisible = function () {
  32610. if (!this._isEnabled) {
  32611. return false;
  32612. }
  32613. var emitterPosition = this.getEmitterPosition();
  32614. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32615. var distance = direction.length();
  32616. direction.normalize();
  32617. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32618. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32619. return !pickInfo.hit || pickInfo.distance > distance;
  32620. };
  32621. LensFlareSystem.prototype.render = function () {
  32622. if (!this._effect.isReady())
  32623. return false;
  32624. var engine = this._scene.getEngine();
  32625. var viewport = this._scene.activeCamera.viewport;
  32626. var globalViewport = viewport.toGlobal(engine);
  32627. // Position
  32628. if (!this.computeEffectivePosition(globalViewport)) {
  32629. return false;
  32630. }
  32631. // Visibility
  32632. if (!this._isVisible()) {
  32633. return false;
  32634. }
  32635. // Intensity
  32636. var awayX;
  32637. var awayY;
  32638. if (this._positionX < this.borderLimit + globalViewport.x) {
  32639. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32640. }
  32641. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32642. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32643. }
  32644. else {
  32645. awayX = 0;
  32646. }
  32647. if (this._positionY < this.borderLimit + globalViewport.y) {
  32648. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32649. }
  32650. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32651. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32652. }
  32653. else {
  32654. awayY = 0;
  32655. }
  32656. var away = (awayX > awayY) ? awayX : awayY;
  32657. if (away > this.borderLimit) {
  32658. away = this.borderLimit;
  32659. }
  32660. var intensity = 1.0 - (away / this.borderLimit);
  32661. if (intensity < 0) {
  32662. return false;
  32663. }
  32664. if (intensity > 1.0) {
  32665. intensity = 1.0;
  32666. }
  32667. // Position
  32668. var centerX = globalViewport.x + globalViewport.width / 2;
  32669. var centerY = globalViewport.y + globalViewport.height / 2;
  32670. var distX = centerX - this._positionX;
  32671. var distY = centerY - this._positionY;
  32672. // Effects
  32673. engine.enableEffect(this._effect);
  32674. engine.setState(false);
  32675. engine.setDepthBuffer(false);
  32676. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32677. // VBOs
  32678. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32679. // Flares
  32680. for (var index = 0; index < this.lensFlares.length; index++) {
  32681. var flare = this.lensFlares[index];
  32682. var x = centerX - (distX * flare.position);
  32683. var y = centerY - (distY * flare.position);
  32684. var cw = flare.size;
  32685. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32686. var cx = 2 * (x / globalViewport.width) - 1.0;
  32687. var cy = 1.0 - 2 * (y / globalViewport.height);
  32688. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32689. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32690. // Texture
  32691. this._effect.setTexture("textureSampler", flare.texture);
  32692. // Color
  32693. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32694. // Draw order
  32695. engine.draw(true, 0, 6);
  32696. }
  32697. engine.setDepthBuffer(true);
  32698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32699. return true;
  32700. };
  32701. LensFlareSystem.prototype.dispose = function () {
  32702. if (this._vertexBuffer) {
  32703. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32704. this._vertexBuffer = null;
  32705. }
  32706. if (this._indexBuffer) {
  32707. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32708. this._indexBuffer = null;
  32709. }
  32710. while (this.lensFlares.length) {
  32711. this.lensFlares[0].dispose();
  32712. }
  32713. // Remove from scene
  32714. var index = this._scene.lensFlareSystems.indexOf(this);
  32715. this._scene.lensFlareSystems.splice(index, 1);
  32716. };
  32717. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  32718. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  32719. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  32720. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  32721. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  32722. var parsedFlare = parsedLensFlareSystem.flares[index];
  32723. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  32724. }
  32725. return lensFlareSystem;
  32726. };
  32727. LensFlareSystem.prototype.serialize = function () {
  32728. var serializationObject = {};
  32729. serializationObject.emitterId = this.getEmitter().id;
  32730. serializationObject.borderLimit = this.borderLimit;
  32731. serializationObject.flares = [];
  32732. for (var index = 0; index < this.lensFlares.length; index++) {
  32733. var flare = this.lensFlares[index];
  32734. serializationObject.flares.push({
  32735. size: flare.size,
  32736. position: flare.position,
  32737. color: flare.color.asArray(),
  32738. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  32739. });
  32740. }
  32741. return serializationObject;
  32742. };
  32743. return LensFlareSystem;
  32744. })();
  32745. BABYLON.LensFlareSystem = LensFlareSystem;
  32746. })(BABYLON || (BABYLON = {}));
  32747. var BABYLON;
  32748. (function (BABYLON) {
  32749. // We're mainly based on the logic defined into the FreeCamera code
  32750. var DeviceOrientationCamera = (function (_super) {
  32751. __extends(DeviceOrientationCamera, _super);
  32752. function DeviceOrientationCamera(name, position, scene) {
  32753. var _this = this;
  32754. _super.call(this, name, position, scene);
  32755. this._offsetX = null;
  32756. this._offsetY = null;
  32757. this._orientationGamma = 0;
  32758. this._orientationBeta = 0;
  32759. this._initialOrientationGamma = 0;
  32760. this._initialOrientationBeta = 0;
  32761. this.angularSensibility = 10000.0;
  32762. this.moveSensibility = 50.0;
  32763. window.addEventListener("resize", function () {
  32764. _this._initialOrientationGamma = null;
  32765. }, false);
  32766. }
  32767. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32768. var _this = this;
  32769. if (this._attachedCanvas) {
  32770. return;
  32771. }
  32772. this._attachedCanvas = canvas;
  32773. if (!this._orientationChanged) {
  32774. this._orientationChanged = function (evt) {
  32775. if (!_this._initialOrientationGamma) {
  32776. _this._initialOrientationGamma = evt.gamma;
  32777. _this._initialOrientationBeta = evt.beta;
  32778. }
  32779. _this._orientationGamma = evt.gamma;
  32780. _this._orientationBeta = evt.beta;
  32781. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32782. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32783. };
  32784. }
  32785. window.addEventListener("deviceorientation", this._orientationChanged);
  32786. };
  32787. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32788. if (this._attachedCanvas !== canvas) {
  32789. return;
  32790. }
  32791. window.removeEventListener("deviceorientation", this._orientationChanged);
  32792. this._attachedCanvas = null;
  32793. this._orientationGamma = 0;
  32794. this._orientationBeta = 0;
  32795. this._initialOrientationGamma = 0;
  32796. this._initialOrientationBeta = 0;
  32797. };
  32798. DeviceOrientationCamera.prototype._checkInputs = function () {
  32799. if (!this._offsetX) {
  32800. return;
  32801. }
  32802. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32803. var speed = this._computeLocalCameraSpeed();
  32804. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32805. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32806. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32807. _super.prototype._checkInputs.call(this);
  32808. };
  32809. return DeviceOrientationCamera;
  32810. })(BABYLON.FreeCamera);
  32811. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32812. })(BABYLON || (BABYLON = {}));
  32813. var BABYLON;
  32814. (function (BABYLON) {
  32815. var Gamepads = (function () {
  32816. function Gamepads(ongamedpadconnected) {
  32817. var _this = this;
  32818. this.babylonGamepads = [];
  32819. this.oneGamepadConnected = false;
  32820. this.isMonitoring = false;
  32821. this.gamepadEventSupported = 'GamepadEvent' in window;
  32822. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32823. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32824. 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=";
  32825. this._callbackGamepadConnected = ongamedpadconnected;
  32826. if (this.gamepadSupportAvailable) {
  32827. // Checking if the gamepad connected event is supported (like in Firefox)
  32828. if (this.gamepadEventSupported) {
  32829. window.addEventListener('gamepadconnected', function (evt) {
  32830. _this._onGamepadConnected(evt);
  32831. }, false);
  32832. window.addEventListener('gamepaddisconnected', function (evt) {
  32833. _this._onGamepadDisconnected(evt);
  32834. }, false);
  32835. }
  32836. else {
  32837. this._startMonitoringGamepads();
  32838. }
  32839. if (!this.oneGamepadConnected) {
  32840. this._insertGamepadDOMInstructions();
  32841. }
  32842. }
  32843. else {
  32844. this._insertGamepadDOMNotSupported();
  32845. }
  32846. }
  32847. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32848. Gamepads.gamepadDOMInfo = document.createElement("div");
  32849. var buttonAImage = document.createElement("img");
  32850. buttonAImage.src = this.buttonADataURL;
  32851. var spanMessage = document.createElement("span");
  32852. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32853. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32854. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32855. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32856. Gamepads.gamepadDOMInfo.style.width = "100%";
  32857. Gamepads.gamepadDOMInfo.style.height = "48px";
  32858. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32859. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32860. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32861. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32862. buttonAImage.style.position = "relative";
  32863. buttonAImage.style.bottom = "8px";
  32864. spanMessage.style.position = "relative";
  32865. spanMessage.style.fontSize = "32px";
  32866. spanMessage.style.bottom = "32px";
  32867. spanMessage.style.color = "green";
  32868. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32869. };
  32870. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32871. Gamepads.gamepadDOMInfo = document.createElement("div");
  32872. var spanMessage = document.createElement("span");
  32873. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32874. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32875. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32876. Gamepads.gamepadDOMInfo.style.width = "100%";
  32877. Gamepads.gamepadDOMInfo.style.height = "40px";
  32878. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32879. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32880. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32881. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32882. spanMessage.style.position = "relative";
  32883. spanMessage.style.fontSize = "32px";
  32884. spanMessage.style.color = "red";
  32885. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32886. };
  32887. Gamepads.prototype.dispose = function () {
  32888. if (Gamepads.gamepadDOMInfo) {
  32889. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32890. }
  32891. };
  32892. Gamepads.prototype._onGamepadConnected = function (evt) {
  32893. var newGamepad = this._addNewGamepad(evt.gamepad);
  32894. if (this._callbackGamepadConnected)
  32895. this._callbackGamepadConnected(newGamepad);
  32896. this._startMonitoringGamepads();
  32897. };
  32898. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32899. if (!this.oneGamepadConnected) {
  32900. this.oneGamepadConnected = true;
  32901. if (Gamepads.gamepadDOMInfo) {
  32902. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32903. Gamepads.gamepadDOMInfo = null;
  32904. }
  32905. }
  32906. var newGamepad;
  32907. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32908. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32909. }
  32910. else {
  32911. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32912. }
  32913. this.babylonGamepads.push(newGamepad);
  32914. return newGamepad;
  32915. };
  32916. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32917. // Remove the gamepad from the list of gamepads to monitor.
  32918. for (var i in this.babylonGamepads) {
  32919. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32920. this.babylonGamepads.splice(i, 1);
  32921. break;
  32922. }
  32923. }
  32924. // If no gamepads are left, stop the polling loop.
  32925. if (this.babylonGamepads.length == 0) {
  32926. this._stopMonitoringGamepads();
  32927. }
  32928. };
  32929. Gamepads.prototype._startMonitoringGamepads = function () {
  32930. if (!this.isMonitoring) {
  32931. this.isMonitoring = true;
  32932. this._checkGamepadsStatus();
  32933. }
  32934. };
  32935. Gamepads.prototype._stopMonitoringGamepads = function () {
  32936. this.isMonitoring = false;
  32937. };
  32938. Gamepads.prototype._checkGamepadsStatus = function () {
  32939. var _this = this;
  32940. // updating gamepad objects
  32941. this._updateGamepadObjects();
  32942. for (var i in this.babylonGamepads) {
  32943. this.babylonGamepads[i].update();
  32944. }
  32945. if (this.isMonitoring) {
  32946. if (window.requestAnimationFrame) {
  32947. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32948. }
  32949. else if (window.mozRequestAnimationFrame) {
  32950. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32951. }
  32952. else if (window.webkitRequestAnimationFrame) {
  32953. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32954. }
  32955. }
  32956. };
  32957. // This function is called only on Chrome, which does not yet support
  32958. // connection/disconnection events, but requires you to monitor
  32959. // an array for changes.
  32960. Gamepads.prototype._updateGamepadObjects = function () {
  32961. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32962. for (var i = 0; i < gamepads.length; i++) {
  32963. if (gamepads[i]) {
  32964. if (!(gamepads[i].index in this.babylonGamepads)) {
  32965. var newGamepad = this._addNewGamepad(gamepads[i]);
  32966. if (this._callbackGamepadConnected) {
  32967. this._callbackGamepadConnected(newGamepad);
  32968. }
  32969. }
  32970. else {
  32971. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32972. }
  32973. }
  32974. }
  32975. };
  32976. return Gamepads;
  32977. })();
  32978. BABYLON.Gamepads = Gamepads;
  32979. var StickValues = (function () {
  32980. function StickValues(x, y) {
  32981. this.x = x;
  32982. this.y = y;
  32983. }
  32984. return StickValues;
  32985. })();
  32986. BABYLON.StickValues = StickValues;
  32987. var Gamepad = (function () {
  32988. function Gamepad(id, index, browserGamepad) {
  32989. this.id = id;
  32990. this.index = index;
  32991. this.browserGamepad = browserGamepad;
  32992. if (this.browserGamepad.axes.length >= 2) {
  32993. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32994. }
  32995. if (this.browserGamepad.axes.length >= 4) {
  32996. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32997. }
  32998. }
  32999. Gamepad.prototype.onleftstickchanged = function (callback) {
  33000. this._onleftstickchanged = callback;
  33001. };
  33002. Gamepad.prototype.onrightstickchanged = function (callback) {
  33003. this._onrightstickchanged = callback;
  33004. };
  33005. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33006. get: function () {
  33007. return this._leftStick;
  33008. },
  33009. set: function (newValues) {
  33010. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33011. this._onleftstickchanged(newValues);
  33012. }
  33013. this._leftStick = newValues;
  33014. },
  33015. enumerable: true,
  33016. configurable: true
  33017. });
  33018. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33019. get: function () {
  33020. return this._rightStick;
  33021. },
  33022. set: function (newValues) {
  33023. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33024. this._onrightstickchanged(newValues);
  33025. }
  33026. this._rightStick = newValues;
  33027. },
  33028. enumerable: true,
  33029. configurable: true
  33030. });
  33031. Gamepad.prototype.update = function () {
  33032. if (this._leftStick) {
  33033. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33034. }
  33035. if (this._rightStick) {
  33036. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33037. }
  33038. };
  33039. return Gamepad;
  33040. })();
  33041. BABYLON.Gamepad = Gamepad;
  33042. var GenericPad = (function (_super) {
  33043. __extends(GenericPad, _super);
  33044. function GenericPad(id, index, gamepad) {
  33045. _super.call(this, id, index, gamepad);
  33046. this.id = id;
  33047. this.index = index;
  33048. this.gamepad = gamepad;
  33049. this._buttons = new Array(gamepad.buttons.length);
  33050. }
  33051. GenericPad.prototype.onbuttondown = function (callback) {
  33052. this._onbuttondown = callback;
  33053. };
  33054. GenericPad.prototype.onbuttonup = function (callback) {
  33055. this._onbuttonup = callback;
  33056. };
  33057. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33058. if (newValue !== currentValue) {
  33059. if (this._onbuttondown && newValue === 1) {
  33060. this._onbuttondown(buttonIndex);
  33061. }
  33062. if (this._onbuttonup && newValue === 0) {
  33063. this._onbuttonup(buttonIndex);
  33064. }
  33065. }
  33066. return newValue;
  33067. };
  33068. GenericPad.prototype.update = function () {
  33069. _super.prototype.update.call(this);
  33070. for (var index = 0; index < this._buttons.length; index++) {
  33071. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33072. }
  33073. };
  33074. return GenericPad;
  33075. })(Gamepad);
  33076. BABYLON.GenericPad = GenericPad;
  33077. (function (Xbox360Button) {
  33078. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33079. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33080. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33081. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33082. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33083. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33084. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33085. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33086. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33087. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33088. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33089. var Xbox360Button = BABYLON.Xbox360Button;
  33090. (function (Xbox360Dpad) {
  33091. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33092. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33093. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33094. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33095. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33096. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33097. var Xbox360Pad = (function (_super) {
  33098. __extends(Xbox360Pad, _super);
  33099. function Xbox360Pad() {
  33100. _super.apply(this, arguments);
  33101. this._leftTrigger = 0;
  33102. this._rightTrigger = 0;
  33103. this._buttonA = 0;
  33104. this._buttonB = 0;
  33105. this._buttonX = 0;
  33106. this._buttonY = 0;
  33107. this._buttonBack = 0;
  33108. this._buttonStart = 0;
  33109. this._buttonLB = 0;
  33110. this._buttonRB = 0;
  33111. this._buttonLeftStick = 0;
  33112. this._buttonRightStick = 0;
  33113. this._dPadUp = 0;
  33114. this._dPadDown = 0;
  33115. this._dPadLeft = 0;
  33116. this._dPadRight = 0;
  33117. }
  33118. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33119. this._onlefttriggerchanged = callback;
  33120. };
  33121. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33122. this._onrighttriggerchanged = callback;
  33123. };
  33124. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33125. get: function () {
  33126. return this._leftTrigger;
  33127. },
  33128. set: function (newValue) {
  33129. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33130. this._onlefttriggerchanged(newValue);
  33131. }
  33132. this._leftTrigger = newValue;
  33133. },
  33134. enumerable: true,
  33135. configurable: true
  33136. });
  33137. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33138. get: function () {
  33139. return this._rightTrigger;
  33140. },
  33141. set: function (newValue) {
  33142. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33143. this._onrighttriggerchanged(newValue);
  33144. }
  33145. this._rightTrigger = newValue;
  33146. },
  33147. enumerable: true,
  33148. configurable: true
  33149. });
  33150. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33151. this._onbuttondown = callback;
  33152. };
  33153. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33154. this._onbuttonup = callback;
  33155. };
  33156. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33157. this._ondpaddown = callback;
  33158. };
  33159. Xbox360Pad.prototype.ondpadup = function (callback) {
  33160. this._ondpadup = callback;
  33161. };
  33162. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33163. if (newValue !== currentValue) {
  33164. if (this._onbuttondown && newValue === 1) {
  33165. this._onbuttondown(buttonType);
  33166. }
  33167. if (this._onbuttonup && newValue === 0) {
  33168. this._onbuttonup(buttonType);
  33169. }
  33170. }
  33171. return newValue;
  33172. };
  33173. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33174. if (newValue !== currentValue) {
  33175. if (this._ondpaddown && newValue === 1) {
  33176. this._ondpaddown(buttonType);
  33177. }
  33178. if (this._ondpadup && newValue === 0) {
  33179. this._ondpadup(buttonType);
  33180. }
  33181. }
  33182. return newValue;
  33183. };
  33184. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33185. get: function () {
  33186. return this._buttonA;
  33187. },
  33188. set: function (value) {
  33189. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33190. },
  33191. enumerable: true,
  33192. configurable: true
  33193. });
  33194. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33195. get: function () {
  33196. return this._buttonB;
  33197. },
  33198. set: function (value) {
  33199. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33200. },
  33201. enumerable: true,
  33202. configurable: true
  33203. });
  33204. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33205. get: function () {
  33206. return this._buttonX;
  33207. },
  33208. set: function (value) {
  33209. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33210. },
  33211. enumerable: true,
  33212. configurable: true
  33213. });
  33214. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33215. get: function () {
  33216. return this._buttonY;
  33217. },
  33218. set: function (value) {
  33219. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33220. },
  33221. enumerable: true,
  33222. configurable: true
  33223. });
  33224. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33225. get: function () {
  33226. return this._buttonStart;
  33227. },
  33228. set: function (value) {
  33229. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33230. },
  33231. enumerable: true,
  33232. configurable: true
  33233. });
  33234. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33235. get: function () {
  33236. return this._buttonBack;
  33237. },
  33238. set: function (value) {
  33239. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33240. },
  33241. enumerable: true,
  33242. configurable: true
  33243. });
  33244. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33245. get: function () {
  33246. return this._buttonLB;
  33247. },
  33248. set: function (value) {
  33249. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33250. },
  33251. enumerable: true,
  33252. configurable: true
  33253. });
  33254. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33255. get: function () {
  33256. return this._buttonRB;
  33257. },
  33258. set: function (value) {
  33259. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33260. },
  33261. enumerable: true,
  33262. configurable: true
  33263. });
  33264. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33265. get: function () {
  33266. return this._buttonLeftStick;
  33267. },
  33268. set: function (value) {
  33269. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33270. },
  33271. enumerable: true,
  33272. configurable: true
  33273. });
  33274. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33275. get: function () {
  33276. return this._buttonRightStick;
  33277. },
  33278. set: function (value) {
  33279. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33285. get: function () {
  33286. return this._dPadUp;
  33287. },
  33288. set: function (value) {
  33289. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33290. },
  33291. enumerable: true,
  33292. configurable: true
  33293. });
  33294. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33295. get: function () {
  33296. return this._dPadDown;
  33297. },
  33298. set: function (value) {
  33299. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33300. },
  33301. enumerable: true,
  33302. configurable: true
  33303. });
  33304. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33305. get: function () {
  33306. return this._dPadLeft;
  33307. },
  33308. set: function (value) {
  33309. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33315. get: function () {
  33316. return this._dPadRight;
  33317. },
  33318. set: function (value) {
  33319. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33320. },
  33321. enumerable: true,
  33322. configurable: true
  33323. });
  33324. Xbox360Pad.prototype.update = function () {
  33325. _super.prototype.update.call(this);
  33326. this.buttonA = this.browserGamepad.buttons[0].value;
  33327. this.buttonB = this.browserGamepad.buttons[1].value;
  33328. this.buttonX = this.browserGamepad.buttons[2].value;
  33329. this.buttonY = this.browserGamepad.buttons[3].value;
  33330. this.buttonLB = this.browserGamepad.buttons[4].value;
  33331. this.buttonRB = this.browserGamepad.buttons[5].value;
  33332. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33333. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33334. this.buttonBack = this.browserGamepad.buttons[8].value;
  33335. this.buttonStart = this.browserGamepad.buttons[9].value;
  33336. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33337. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33338. this.dPadUp = this.browserGamepad.buttons[12].value;
  33339. this.dPadDown = this.browserGamepad.buttons[13].value;
  33340. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33341. this.dPadRight = this.browserGamepad.buttons[15].value;
  33342. };
  33343. return Xbox360Pad;
  33344. })(Gamepad);
  33345. BABYLON.Xbox360Pad = Xbox360Pad;
  33346. })(BABYLON || (BABYLON = {}));
  33347. var BABYLON;
  33348. (function (BABYLON) {
  33349. // We're mainly based on the logic defined into the FreeCamera code
  33350. var GamepadCamera = (function (_super) {
  33351. __extends(GamepadCamera, _super);
  33352. function GamepadCamera(name, position, scene) {
  33353. var _this = this;
  33354. _super.call(this, name, position, scene);
  33355. this.angularSensibility = 200;
  33356. this.moveSensibility = 75;
  33357. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33358. }
  33359. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33360. // Only the first gamepad can control the camera
  33361. if (gamepad.index === 0) {
  33362. this._gamepad = gamepad;
  33363. }
  33364. };
  33365. GamepadCamera.prototype._checkInputs = function () {
  33366. if (this._gamepad) {
  33367. var LSValues = this._gamepad.leftStick;
  33368. var normalizedLX = LSValues.x / this.moveSensibility;
  33369. var normalizedLY = LSValues.y / this.moveSensibility;
  33370. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33371. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33372. var RSValues = this._gamepad.rightStick;
  33373. var normalizedRX = RSValues.x / this.angularSensibility;
  33374. var normalizedRY = RSValues.y / this.angularSensibility;
  33375. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33376. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33377. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33378. var speed = this._computeLocalCameraSpeed() * 50.0;
  33379. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33380. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33381. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33382. }
  33383. _super.prototype._checkInputs.call(this);
  33384. };
  33385. GamepadCamera.prototype.dispose = function () {
  33386. this._gamepads.dispose();
  33387. _super.prototype.dispose.call(this);
  33388. };
  33389. return GamepadCamera;
  33390. })(BABYLON.FreeCamera);
  33391. BABYLON.GamepadCamera = GamepadCamera;
  33392. })(BABYLON || (BABYLON = {}));
  33393. var BABYLON;
  33394. (function (BABYLON) {
  33395. var Analyser = (function () {
  33396. function Analyser(scene) {
  33397. this.SMOOTHING = 0.75;
  33398. this.FFT_SIZE = 512;
  33399. this.BARGRAPHAMPLITUDE = 256;
  33400. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33401. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33402. this._scene = scene;
  33403. this._audioEngine = BABYLON.Engine.audioEngine;
  33404. if (this._audioEngine.canUseWebAudio) {
  33405. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33406. this._webAudioAnalyser.minDecibels = -140;
  33407. this._webAudioAnalyser.maxDecibels = 0;
  33408. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33409. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33410. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33411. }
  33412. }
  33413. Analyser.prototype.getFrequencyBinCount = function () {
  33414. if (this._audioEngine.canUseWebAudio) {
  33415. return this._webAudioAnalyser.frequencyBinCount;
  33416. }
  33417. else {
  33418. return 0;
  33419. }
  33420. };
  33421. Analyser.prototype.getByteFrequencyData = function () {
  33422. if (this._audioEngine.canUseWebAudio) {
  33423. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33424. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33425. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33426. }
  33427. return this._byteFreqs;
  33428. };
  33429. Analyser.prototype.getByteTimeDomainData = function () {
  33430. if (this._audioEngine.canUseWebAudio) {
  33431. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33432. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33433. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33434. }
  33435. return this._byteTime;
  33436. };
  33437. Analyser.prototype.getFloatFrequencyData = function () {
  33438. if (this._audioEngine.canUseWebAudio) {
  33439. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33440. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33441. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33442. }
  33443. return this._floatFreqs;
  33444. };
  33445. Analyser.prototype.drawDebugCanvas = function () {
  33446. var _this = this;
  33447. if (this._audioEngine.canUseWebAudio) {
  33448. if (!this._debugCanvas) {
  33449. this._debugCanvas = document.createElement("canvas");
  33450. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33451. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33452. this._debugCanvas.style.position = "absolute";
  33453. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33454. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33455. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33456. document.body.appendChild(this._debugCanvas);
  33457. this._registerFunc = function () {
  33458. _this.drawDebugCanvas();
  33459. };
  33460. this._scene.registerBeforeRender(this._registerFunc);
  33461. }
  33462. if (this._registerFunc) {
  33463. var workingArray = this.getByteFrequencyData();
  33464. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33465. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33466. // Draw the frequency domain chart.
  33467. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33468. var value = workingArray[i];
  33469. var percent = value / this.BARGRAPHAMPLITUDE;
  33470. var height = this.DEBUGCANVASSIZE.height * percent;
  33471. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33472. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33473. var hue = i / this.getFrequencyBinCount() * 360;
  33474. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33475. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33476. }
  33477. }
  33478. }
  33479. };
  33480. Analyser.prototype.stopDebugCanvas = function () {
  33481. if (this._debugCanvas) {
  33482. this._scene.unregisterBeforeRender(this._registerFunc);
  33483. this._registerFunc = null;
  33484. document.body.removeChild(this._debugCanvas);
  33485. this._debugCanvas = null;
  33486. this._debugCanvasContext = null;
  33487. }
  33488. };
  33489. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33490. if (this._audioEngine.canUseWebAudio) {
  33491. inputAudioNode.connect(this._webAudioAnalyser);
  33492. this._webAudioAnalyser.connect(outputAudioNode);
  33493. }
  33494. };
  33495. Analyser.prototype.dispose = function () {
  33496. if (this._audioEngine.canUseWebAudio) {
  33497. this._webAudioAnalyser.disconnect();
  33498. }
  33499. };
  33500. return Analyser;
  33501. })();
  33502. BABYLON.Analyser = Analyser;
  33503. })(BABYLON || (BABYLON = {}));
  33504. var BABYLON;
  33505. (function (BABYLON) {
  33506. var AudioEngine = (function () {
  33507. function AudioEngine() {
  33508. this._audioContext = null;
  33509. this._audioContextInitialized = false;
  33510. this.canUseWebAudio = false;
  33511. this.WarnedWebAudioUnsupported = false;
  33512. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33513. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33514. this.canUseWebAudio = true;
  33515. }
  33516. }
  33517. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33518. get: function () {
  33519. if (!this._audioContextInitialized) {
  33520. this._initializeAudioContext();
  33521. }
  33522. return this._audioContext;
  33523. },
  33524. enumerable: true,
  33525. configurable: true
  33526. });
  33527. AudioEngine.prototype._initializeAudioContext = function () {
  33528. try {
  33529. if (this.canUseWebAudio) {
  33530. this._audioContext = new AudioContext();
  33531. // create a global volume gain node
  33532. this.masterGain = this._audioContext.createGain();
  33533. this.masterGain.gain.value = 1;
  33534. this.masterGain.connect(this._audioContext.destination);
  33535. this._audioContextInitialized = true;
  33536. }
  33537. }
  33538. catch (e) {
  33539. this.canUseWebAudio = false;
  33540. BABYLON.Tools.Error("Web Audio: " + e.message);
  33541. }
  33542. };
  33543. AudioEngine.prototype.dispose = function () {
  33544. if (this.canUseWebAudio && this._audioContextInitialized) {
  33545. if (this._connectedAnalyser) {
  33546. this._connectedAnalyser.stopDebugCanvas();
  33547. this._connectedAnalyser.dispose();
  33548. this.masterGain.disconnect();
  33549. this.masterGain.connect(this._audioContext.destination);
  33550. this._connectedAnalyser = null;
  33551. }
  33552. this.masterGain.gain.value = 1;
  33553. }
  33554. this.WarnedWebAudioUnsupported = false;
  33555. };
  33556. AudioEngine.prototype.getGlobalVolume = function () {
  33557. if (this.canUseWebAudio && this._audioContextInitialized) {
  33558. return this.masterGain.gain.value;
  33559. }
  33560. else {
  33561. return -1;
  33562. }
  33563. };
  33564. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33565. if (this.canUseWebAudio && this._audioContextInitialized) {
  33566. this.masterGain.gain.value = newVolume;
  33567. }
  33568. };
  33569. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33570. if (this._connectedAnalyser) {
  33571. this._connectedAnalyser.stopDebugCanvas();
  33572. }
  33573. if (this.canUseWebAudio && this._audioContextInitialized) {
  33574. this._connectedAnalyser = analyser;
  33575. this.masterGain.disconnect();
  33576. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33577. }
  33578. };
  33579. return AudioEngine;
  33580. })();
  33581. BABYLON.AudioEngine = AudioEngine;
  33582. })(BABYLON || (BABYLON = {}));
  33583. var BABYLON;
  33584. (function (BABYLON) {
  33585. var Sound = (function () {
  33586. /**
  33587. * Create a sound and attach it to a scene
  33588. * @param name Name of your sound
  33589. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33590. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33591. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33592. */
  33593. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33594. var _this = this;
  33595. this.autoplay = false;
  33596. this.loop = false;
  33597. this.useCustomAttenuation = false;
  33598. this.spatialSound = false;
  33599. this.refDistance = 1;
  33600. this.rolloffFactor = 1;
  33601. this.maxDistance = 100;
  33602. this.distanceModel = "linear";
  33603. this._panningModel = "equalpower";
  33604. this._playbackRate = 1;
  33605. this._streaming = false;
  33606. this._startTime = 0;
  33607. this._startOffset = 0;
  33608. this._position = BABYLON.Vector3.Zero();
  33609. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33610. this._volume = 1;
  33611. this._isLoaded = false;
  33612. this._isReadyToPlay = false;
  33613. this.isPlaying = false;
  33614. this.isPaused = false;
  33615. this._isDirectional = false;
  33616. // Used if you'd like to create a directional sound.
  33617. // If not set, the sound will be omnidirectional
  33618. this._coneInnerAngle = 360;
  33619. this._coneOuterAngle = 360;
  33620. this._coneOuterGain = 0;
  33621. this._isOutputConnected = false;
  33622. this.name = name;
  33623. this._scene = scene;
  33624. this._readyToPlayCallback = readyToPlayCallback;
  33625. // Default custom attenuation function is a linear attenuation
  33626. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33627. if (currentDistance < maxDistance) {
  33628. return currentVolume * (1 - currentDistance / maxDistance);
  33629. }
  33630. else {
  33631. return 0;
  33632. }
  33633. };
  33634. if (options) {
  33635. this.autoplay = options.autoplay || false;
  33636. this.loop = options.loop || false;
  33637. // if volume === 0, we need another way to check this option
  33638. if (options.volume !== undefined) {
  33639. this._volume = options.volume;
  33640. }
  33641. this.spatialSound = options.spatialSound || false;
  33642. this.maxDistance = options.maxDistance || 100;
  33643. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33644. this.rolloffFactor = options.rolloffFactor || 1;
  33645. this.refDistance = options.refDistance || 1;
  33646. this.distanceModel = options.distanceModel || "linear";
  33647. this._playbackRate = options.playbackRate || 1;
  33648. this._streaming = options.streaming || false;
  33649. }
  33650. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33651. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33652. this._soundGain.gain.value = this._volume;
  33653. this._inputAudioNode = this._soundGain;
  33654. this._ouputAudioNode = this._soundGain;
  33655. if (this.spatialSound) {
  33656. this._createSpatialParameters();
  33657. }
  33658. this._scene.mainSoundTrack.AddSound(this);
  33659. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33660. if (urlOrArrayBuffer) {
  33661. // If it's an URL
  33662. if (typeof (urlOrArrayBuffer) === "string") {
  33663. // Loading sound using XHR2
  33664. if (!this._streaming) {
  33665. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33666. }
  33667. else {
  33668. this._htmlAudioElement = new Audio();
  33669. this._htmlAudioElement.src = urlOrArrayBuffer;
  33670. this._htmlAudioElement.controls = false;
  33671. this._htmlAudioElement.loop = this.loop;
  33672. this._htmlAudioElement.crossOrigin = "anonymous";
  33673. this._isReadyToPlay = true;
  33674. document.body.appendChild(this._htmlAudioElement);
  33675. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33676. if (this._readyToPlayCallback) {
  33677. window.setTimeout(function () {
  33678. _this._readyToPlayCallback();
  33679. }, 1000);
  33680. }
  33681. if (this.autoplay) {
  33682. this.play();
  33683. }
  33684. }
  33685. }
  33686. else {
  33687. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33688. this._soundLoaded(urlOrArrayBuffer);
  33689. }
  33690. else {
  33691. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33692. }
  33693. }
  33694. }
  33695. }
  33696. else {
  33697. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33698. this._scene.mainSoundTrack.AddSound(this);
  33699. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33700. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33701. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33702. }
  33703. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33704. if (this._readyToPlayCallback) {
  33705. window.setTimeout(function () {
  33706. _this._readyToPlayCallback();
  33707. }, 1000);
  33708. }
  33709. }
  33710. }
  33711. Sound.prototype.dispose = function () {
  33712. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33713. if (this.isPlaying) {
  33714. this.stop();
  33715. }
  33716. this._isReadyToPlay = false;
  33717. if (this.soundTrackId === -1) {
  33718. this._scene.mainSoundTrack.RemoveSound(this);
  33719. }
  33720. else {
  33721. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33722. }
  33723. if (this._soundGain) {
  33724. this._soundGain.disconnect();
  33725. this._soundGain = null;
  33726. }
  33727. if (this._soundPanner) {
  33728. this._soundPanner.disconnect();
  33729. this._soundPanner = null;
  33730. }
  33731. if (this._soundSource) {
  33732. this._soundSource.disconnect();
  33733. this._soundSource = null;
  33734. }
  33735. this._audioBuffer = null;
  33736. if (this._htmlAudioElement) {
  33737. this._htmlAudioElement.pause();
  33738. this._htmlAudioElement.src = "";
  33739. document.body.removeChild(this._htmlAudioElement);
  33740. }
  33741. if (this._connectedMesh) {
  33742. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33743. this._connectedMesh = null;
  33744. }
  33745. }
  33746. };
  33747. Sound.prototype._soundLoaded = function (audioData) {
  33748. var _this = this;
  33749. this._isLoaded = true;
  33750. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33751. _this._audioBuffer = buffer;
  33752. _this._isReadyToPlay = true;
  33753. if (_this.autoplay) {
  33754. _this.play();
  33755. }
  33756. if (_this._readyToPlayCallback) {
  33757. _this._readyToPlayCallback();
  33758. }
  33759. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33760. };
  33761. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33762. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33763. this._audioBuffer = audioBuffer;
  33764. this._isReadyToPlay = true;
  33765. }
  33766. };
  33767. Sound.prototype.updateOptions = function (options) {
  33768. if (options) {
  33769. this.loop = options.loop || this.loop;
  33770. this.maxDistance = options.maxDistance || this.maxDistance;
  33771. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33772. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33773. this.refDistance = options.refDistance || this.refDistance;
  33774. this.distanceModel = options.distanceModel || this.distanceModel;
  33775. this._playbackRate = options.playbackRate || this._playbackRate;
  33776. this._updateSpatialParameters();
  33777. if (this.isPlaying) {
  33778. if (this._streaming) {
  33779. this._htmlAudioElement.playbackRate = this._playbackRate;
  33780. }
  33781. else {
  33782. this._soundSource.playbackRate.value = this._playbackRate;
  33783. }
  33784. }
  33785. }
  33786. };
  33787. Sound.prototype._createSpatialParameters = function () {
  33788. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33789. if (this._scene.headphone) {
  33790. this._panningModel = "HRTF";
  33791. }
  33792. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33793. this._updateSpatialParameters();
  33794. this._soundPanner.connect(this._ouputAudioNode);
  33795. this._inputAudioNode = this._soundPanner;
  33796. }
  33797. };
  33798. Sound.prototype._updateSpatialParameters = function () {
  33799. if (this.spatialSound) {
  33800. if (this.useCustomAttenuation) {
  33801. // Tricks to disable in a way embedded Web Audio attenuation
  33802. this._soundPanner.distanceModel = "linear";
  33803. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33804. this._soundPanner.refDistance = 1;
  33805. this._soundPanner.rolloffFactor = 1;
  33806. this._soundPanner.panningModel = this._panningModel;
  33807. }
  33808. else {
  33809. this._soundPanner.distanceModel = this.distanceModel;
  33810. this._soundPanner.maxDistance = this.maxDistance;
  33811. this._soundPanner.refDistance = this.refDistance;
  33812. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33813. this._soundPanner.panningModel = this._panningModel;
  33814. }
  33815. }
  33816. };
  33817. Sound.prototype.switchPanningModelToHRTF = function () {
  33818. this._panningModel = "HRTF";
  33819. this._switchPanningModel();
  33820. };
  33821. Sound.prototype.switchPanningModelToEqualPower = function () {
  33822. this._panningModel = "equalpower";
  33823. this._switchPanningModel();
  33824. };
  33825. Sound.prototype._switchPanningModel = function () {
  33826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33827. this._soundPanner.panningModel = this._panningModel;
  33828. }
  33829. };
  33830. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33831. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33832. if (this._isOutputConnected) {
  33833. this._ouputAudioNode.disconnect();
  33834. }
  33835. this._ouputAudioNode.connect(soundTrackAudioNode);
  33836. this._isOutputConnected = true;
  33837. }
  33838. };
  33839. /**
  33840. * Transform this sound into a directional source
  33841. * @param coneInnerAngle Size of the inner cone in degree
  33842. * @param coneOuterAngle Size of the outer cone in degree
  33843. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33844. */
  33845. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33846. if (coneOuterAngle < coneInnerAngle) {
  33847. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33848. return;
  33849. }
  33850. this._coneInnerAngle = coneInnerAngle;
  33851. this._coneOuterAngle = coneOuterAngle;
  33852. this._coneOuterGain = coneOuterGain;
  33853. this._isDirectional = true;
  33854. if (this.isPlaying && this.loop) {
  33855. this.stop();
  33856. this.play();
  33857. }
  33858. };
  33859. Sound.prototype.setPosition = function (newPosition) {
  33860. this._position = newPosition;
  33861. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33862. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33863. }
  33864. };
  33865. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33866. this._localDirection = newLocalDirection;
  33867. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33868. this._updateDirection();
  33869. }
  33870. };
  33871. Sound.prototype._updateDirection = function () {
  33872. var mat = this._connectedMesh.getWorldMatrix();
  33873. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33874. direction.normalize();
  33875. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33876. };
  33877. Sound.prototype.updateDistanceFromListener = function () {
  33878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33879. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33880. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33881. }
  33882. };
  33883. Sound.prototype.setAttenuationFunction = function (callback) {
  33884. this._customAttenuationFunction = callback;
  33885. };
  33886. /**
  33887. * Play the sound
  33888. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33889. */
  33890. Sound.prototype.play = function (time) {
  33891. var _this = this;
  33892. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33893. try {
  33894. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33895. if (!this._soundSource || !this._streamingSource) {
  33896. if (this.spatialSound) {
  33897. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33898. if (this._isDirectional) {
  33899. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33900. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33901. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33902. if (this._connectedMesh) {
  33903. this._updateDirection();
  33904. }
  33905. else {
  33906. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33907. }
  33908. }
  33909. }
  33910. }
  33911. if (this._streaming) {
  33912. if (!this._streamingSource) {
  33913. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33914. this._htmlAudioElement.onended = function () { _this._onended(); };
  33915. this._htmlAudioElement.playbackRate = this._playbackRate;
  33916. }
  33917. this._streamingSource.disconnect();
  33918. this._streamingSource.connect(this._inputAudioNode);
  33919. this._htmlAudioElement.play();
  33920. }
  33921. else {
  33922. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33923. this._soundSource.buffer = this._audioBuffer;
  33924. this._soundSource.connect(this._inputAudioNode);
  33925. this._soundSource.loop = this.loop;
  33926. this._soundSource.playbackRate.value = this._playbackRate;
  33927. this._soundSource.onended = function () { _this._onended(); };
  33928. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33929. }
  33930. this._startTime = startTime;
  33931. this.isPlaying = true;
  33932. this.isPaused = false;
  33933. }
  33934. catch (ex) {
  33935. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33936. }
  33937. }
  33938. };
  33939. Sound.prototype._onended = function () {
  33940. this.isPlaying = false;
  33941. if (this.onended) {
  33942. this.onended();
  33943. }
  33944. };
  33945. /**
  33946. * Stop the sound
  33947. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33948. */
  33949. Sound.prototype.stop = function (time) {
  33950. if (this.isPlaying) {
  33951. if (this._streaming) {
  33952. this._htmlAudioElement.pause();
  33953. // Test needed for Firefox or it will generate an Invalid State Error
  33954. if (this._htmlAudioElement.currentTime > 0) {
  33955. this._htmlAudioElement.currentTime = 0;
  33956. }
  33957. }
  33958. else {
  33959. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33960. this._soundSource.stop(stopTime);
  33961. }
  33962. this.isPlaying = false;
  33963. }
  33964. };
  33965. Sound.prototype.pause = function () {
  33966. if (this.isPlaying) {
  33967. if (this._streaming) {
  33968. this._htmlAudioElement.pause();
  33969. }
  33970. else {
  33971. this.stop(0);
  33972. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33973. }
  33974. this.isPaused = true;
  33975. }
  33976. };
  33977. Sound.prototype.setVolume = function (newVolume, time) {
  33978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33979. if (time) {
  33980. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33981. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33982. }
  33983. else {
  33984. this._soundGain.gain.value = newVolume;
  33985. }
  33986. }
  33987. this._volume = newVolume;
  33988. };
  33989. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33990. this._playbackRate = newPlaybackRate;
  33991. if (this.isPlaying) {
  33992. if (this._streaming) {
  33993. this._htmlAudioElement.playbackRate = this._playbackRate;
  33994. }
  33995. else {
  33996. this._soundSource.playbackRate.value = this._playbackRate;
  33997. }
  33998. }
  33999. };
  34000. Sound.prototype.getVolume = function () {
  34001. return this._volume;
  34002. };
  34003. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34004. var _this = this;
  34005. this._connectedMesh = meshToConnectTo;
  34006. if (!this.spatialSound) {
  34007. this.spatialSound = true;
  34008. this._createSpatialParameters();
  34009. if (this.isPlaying && this.loop) {
  34010. this.stop();
  34011. this.play();
  34012. }
  34013. }
  34014. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34015. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34016. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34017. };
  34018. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34019. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34020. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34021. this._updateDirection();
  34022. }
  34023. };
  34024. Sound.Parse = function (parsedSound, scene, rootUrl) {
  34025. var soundName = parsedSound.name;
  34026. var soundUrl = rootUrl + soundName;
  34027. var options = {
  34028. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34029. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34030. rolloffFactor: parsedSound.rolloffFactor,
  34031. refDistance: parsedSound.refDistance,
  34032. distanceModel: parsedSound.distanceModel,
  34033. playbackRate: parsedSound.playbackRate
  34034. };
  34035. var newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34036. scene._addPendingData(newSound);
  34037. if (parsedSound.position) {
  34038. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34039. newSound.setPosition(soundPosition);
  34040. }
  34041. if (parsedSound.isDirectional) {
  34042. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34043. if (parsedSound.localDirectionToMesh) {
  34044. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34045. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34046. }
  34047. }
  34048. if (parsedSound.connectedMeshId) {
  34049. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34050. if (connectedMesh) {
  34051. newSound.attachToMesh(connectedMesh);
  34052. }
  34053. }
  34054. return newSound;
  34055. };
  34056. return Sound;
  34057. })();
  34058. BABYLON.Sound = Sound;
  34059. })(BABYLON || (BABYLON = {}));
  34060. var BABYLON;
  34061. (function (BABYLON) {
  34062. var SoundTrack = (function () {
  34063. function SoundTrack(scene, options) {
  34064. this.id = -1;
  34065. this._isMainTrack = false;
  34066. this._isInitialized = false;
  34067. this._scene = scene;
  34068. this.soundCollection = new Array();
  34069. this._options = options;
  34070. if (!this._isMainTrack) {
  34071. this._scene.soundTracks.push(this);
  34072. this.id = this._scene.soundTracks.length - 1;
  34073. }
  34074. }
  34075. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34077. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34078. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34079. if (this._options) {
  34080. if (this._options.volume) {
  34081. this._outputAudioNode.gain.value = this._options.volume;
  34082. }
  34083. if (this._options.mainTrack) {
  34084. this._isMainTrack = this._options.mainTrack;
  34085. }
  34086. }
  34087. this._isInitialized = true;
  34088. }
  34089. };
  34090. SoundTrack.prototype.dispose = function () {
  34091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34092. if (this._connectedAnalyser) {
  34093. this._connectedAnalyser.stopDebugCanvas();
  34094. }
  34095. while (this.soundCollection.length) {
  34096. this.soundCollection[0].dispose();
  34097. }
  34098. if (this._outputAudioNode) {
  34099. this._outputAudioNode.disconnect();
  34100. }
  34101. this._outputAudioNode = null;
  34102. }
  34103. };
  34104. SoundTrack.prototype.AddSound = function (sound) {
  34105. if (!this._isInitialized) {
  34106. this._initializeSoundTrackAudioGraph();
  34107. }
  34108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34109. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34110. }
  34111. if (sound.soundTrackId) {
  34112. if (sound.soundTrackId === -1) {
  34113. this._scene.mainSoundTrack.RemoveSound(sound);
  34114. }
  34115. else {
  34116. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34117. }
  34118. }
  34119. this.soundCollection.push(sound);
  34120. sound.soundTrackId = this.id;
  34121. };
  34122. SoundTrack.prototype.RemoveSound = function (sound) {
  34123. var index = this.soundCollection.indexOf(sound);
  34124. if (index !== -1) {
  34125. this.soundCollection.splice(index, 1);
  34126. }
  34127. };
  34128. SoundTrack.prototype.setVolume = function (newVolume) {
  34129. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34130. this._outputAudioNode.gain.value = newVolume;
  34131. }
  34132. };
  34133. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34134. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34135. for (var i = 0; i < this.soundCollection.length; i++) {
  34136. this.soundCollection[i].switchPanningModelToHRTF();
  34137. }
  34138. }
  34139. };
  34140. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34141. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34142. for (var i = 0; i < this.soundCollection.length; i++) {
  34143. this.soundCollection[i].switchPanningModelToEqualPower();
  34144. }
  34145. }
  34146. };
  34147. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34148. if (this._connectedAnalyser) {
  34149. this._connectedAnalyser.stopDebugCanvas();
  34150. }
  34151. this._connectedAnalyser = analyser;
  34152. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34153. this._outputAudioNode.disconnect();
  34154. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34155. }
  34156. };
  34157. return SoundTrack;
  34158. })();
  34159. BABYLON.SoundTrack = SoundTrack;
  34160. })(BABYLON || (BABYLON = {}));
  34161. var BABYLON;
  34162. (function (BABYLON) {
  34163. var DepthRenderer = (function () {
  34164. function DepthRenderer(scene, type) {
  34165. var _this = this;
  34166. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34167. this._viewMatrix = BABYLON.Matrix.Zero();
  34168. this._projectionMatrix = BABYLON.Matrix.Zero();
  34169. this._transformMatrix = BABYLON.Matrix.Zero();
  34170. this._worldViewProjection = BABYLON.Matrix.Zero();
  34171. this._scene = scene;
  34172. var engine = scene.getEngine();
  34173. // Render target
  34174. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34175. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34176. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34177. this._depthMap.refreshRate = 1;
  34178. this._depthMap.renderParticles = false;
  34179. this._depthMap.renderList = null;
  34180. // set default depth value to 1.0 (far away)
  34181. this._depthMap.onClear = function (engine) {
  34182. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34183. };
  34184. // Custom render function
  34185. var renderSubMesh = function (subMesh) {
  34186. var mesh = subMesh.getRenderingMesh();
  34187. var scene = _this._scene;
  34188. var engine = scene.getEngine();
  34189. // Culling
  34190. engine.setState(subMesh.getMaterial().backFaceCulling);
  34191. // Managing instances
  34192. var batch = mesh._getInstancesRenderList(subMesh._id);
  34193. if (batch.mustReturn) {
  34194. return;
  34195. }
  34196. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34197. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34198. engine.enableEffect(_this._effect);
  34199. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34200. var material = subMesh.getMaterial();
  34201. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34202. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34203. // Alpha test
  34204. if (material && material.needAlphaTesting()) {
  34205. var alphaTexture = material.getAlphaTestTexture();
  34206. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34207. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34208. }
  34209. // Bones
  34210. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34211. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34212. }
  34213. // Draw
  34214. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34215. }
  34216. };
  34217. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34218. var index;
  34219. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34220. renderSubMesh(opaqueSubMeshes.data[index]);
  34221. }
  34222. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34223. renderSubMesh(alphaTestSubMeshes.data[index]);
  34224. }
  34225. };
  34226. }
  34227. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34228. var defines = [];
  34229. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34230. var mesh = subMesh.getMesh();
  34231. var scene = mesh.getScene();
  34232. var material = subMesh.getMaterial();
  34233. // Alpha test
  34234. if (material && material.needAlphaTesting()) {
  34235. defines.push("#define ALPHATEST");
  34236. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34237. attribs.push(BABYLON.VertexBuffer.UVKind);
  34238. defines.push("#define UV1");
  34239. }
  34240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34241. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34242. defines.push("#define UV2");
  34243. }
  34244. }
  34245. // Bones
  34246. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34249. if (mesh.numBoneInfluencers > 4) {
  34250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34252. }
  34253. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34254. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34255. }
  34256. else {
  34257. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34258. }
  34259. // Instances
  34260. if (useInstances) {
  34261. defines.push("#define INSTANCES");
  34262. attribs.push("world0");
  34263. attribs.push("world1");
  34264. attribs.push("world2");
  34265. attribs.push("world3");
  34266. }
  34267. // Get correct effect
  34268. var join = defines.join("\n");
  34269. if (this._cachedDefines !== join) {
  34270. this._cachedDefines = join;
  34271. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34272. }
  34273. return this._effect.isReady();
  34274. };
  34275. DepthRenderer.prototype.getDepthMap = function () {
  34276. return this._depthMap;
  34277. };
  34278. // Methods
  34279. DepthRenderer.prototype.dispose = function () {
  34280. this._depthMap.dispose();
  34281. };
  34282. return DepthRenderer;
  34283. })();
  34284. BABYLON.DepthRenderer = DepthRenderer;
  34285. })(BABYLON || (BABYLON = {}));
  34286. var BABYLON;
  34287. (function (BABYLON) {
  34288. var SSAORenderingPipeline = (function (_super) {
  34289. __extends(SSAORenderingPipeline, _super);
  34290. /**
  34291. * @constructor
  34292. * @param {string} name - The rendering pipeline name
  34293. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34294. * @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 }
  34295. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34296. */
  34297. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34298. var _this = this;
  34299. _super.call(this, scene.getEngine(), name);
  34300. // Members
  34301. /**
  34302. * The PassPostProcess id in the pipeline that contains the original scene color
  34303. * @type {string}
  34304. */
  34305. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34306. /**
  34307. * The SSAO PostProcess id in the pipeline
  34308. * @type {string}
  34309. */
  34310. this.SSAORenderEffect = "SSAORenderEffect";
  34311. /**
  34312. * The horizontal blur PostProcess id in the pipeline
  34313. * @type {string}
  34314. */
  34315. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34316. /**
  34317. * The vertical blur PostProcess id in the pipeline
  34318. * @type {string}
  34319. */
  34320. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34321. /**
  34322. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34323. * @type {string}
  34324. */
  34325. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34326. /**
  34327. * The output strength of the SSAO post-process. Default value is 1.0.
  34328. * @type {number}
  34329. */
  34330. this.totalStrength = 1.0;
  34331. /**
  34332. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34333. * @type {number}
  34334. */
  34335. this.radius = 0.0001;
  34336. /**
  34337. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34338. * Must not be equal to fallOff and superior to fallOff.
  34339. * Default value is 0.975
  34340. * @type {number}
  34341. */
  34342. this.area = 0.0075;
  34343. /**
  34344. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34345. * Must not be equal to area and inferior to area.
  34346. * Default value is 0.0
  34347. * @type {number}
  34348. */
  34349. this.fallOff = 0.000001;
  34350. /**
  34351. * The base color of the SSAO post-process
  34352. * The final result is "base + ssao" between [0, 1]
  34353. * @type {number}
  34354. */
  34355. this.base = 0.5;
  34356. this._firstUpdate = true;
  34357. this._scene = scene;
  34358. // Set up assets
  34359. this._createRandomTexture();
  34360. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34361. var ssaoRatio = ratio.ssaoRatio || ratio;
  34362. var combineRatio = ratio.combineRatio || ratio;
  34363. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34364. this._createSSAOPostProcess(ssaoRatio);
  34365. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34366. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34367. this._createSSAOCombinePostProcess(combineRatio);
  34368. // Set up pipeline
  34369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34370. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34374. // Finish
  34375. scene.postProcessRenderPipelineManager.addPipeline(this);
  34376. if (cameras)
  34377. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34378. }
  34379. // Public Methods
  34380. /**
  34381. * Returns the horizontal blur PostProcess
  34382. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34383. */
  34384. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34385. return this._blurHPostProcess;
  34386. };
  34387. /**
  34388. * Returns the vertical blur PostProcess
  34389. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34390. */
  34391. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34392. return this._blurVPostProcess;
  34393. };
  34394. /**
  34395. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34396. */
  34397. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34398. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34399. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34400. this._originalColorPostProcess = undefined;
  34401. this._ssaoPostProcess = undefined;
  34402. this._blurHPostProcess = undefined;
  34403. this._blurVPostProcess = undefined;
  34404. this._ssaoCombinePostProcess = undefined;
  34405. this._randomTexture.dispose();
  34406. if (disableDepthRender)
  34407. this._scene.disableDepthRenderer();
  34408. };
  34409. // Private Methods
  34410. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34411. var _this = this;
  34412. var numSamples = 16;
  34413. var sampleSphere = [
  34414. 0.5381, 0.1856, -0.4319,
  34415. 0.1379, 0.2486, 0.4430,
  34416. 0.3371, 0.5679, -0.0057,
  34417. -0.6999, -0.0451, -0.0019,
  34418. 0.0689, -0.1598, -0.8547,
  34419. 0.0560, 0.0069, -0.1843,
  34420. -0.0146, 0.1402, 0.0762,
  34421. 0.0100, -0.1924, -0.0344,
  34422. -0.3577, -0.5301, -0.4358,
  34423. -0.3169, 0.1063, 0.0158,
  34424. 0.0103, -0.5869, 0.0046,
  34425. -0.0897, -0.4940, 0.3287,
  34426. 0.7119, -0.0154, -0.0918,
  34427. -0.0533, 0.0596, -0.5411,
  34428. 0.0352, -0.0631, 0.5460,
  34429. -0.4776, 0.2847, -0.0271
  34430. ];
  34431. var samplesFactor = 1.0 / numSamples;
  34432. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34433. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34434. "area", "fallOff", "base"
  34435. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34436. this._ssaoPostProcess.onApply = function (effect) {
  34437. if (_this._firstUpdate) {
  34438. effect.setArray3("sampleSphere", sampleSphere);
  34439. effect.setFloat("samplesFactor", samplesFactor);
  34440. effect.setFloat("randTextureTiles", 4.0);
  34441. _this._firstUpdate = false;
  34442. }
  34443. effect.setFloat("totalStrength", _this.totalStrength);
  34444. effect.setFloat("radius", _this.radius);
  34445. effect.setFloat("area", _this.area);
  34446. effect.setFloat("fallOff", _this.fallOff);
  34447. effect.setFloat("base", _this.base);
  34448. effect.setTexture("textureSampler", _this._depthTexture);
  34449. effect.setTexture("randomSampler", _this._randomTexture);
  34450. };
  34451. };
  34452. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34453. var _this = this;
  34454. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34455. this._ssaoCombinePostProcess.onApply = function (effect) {
  34456. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34457. };
  34458. };
  34459. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34460. var size = 512;
  34461. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34462. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34463. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34464. var context = this._randomTexture.getContext();
  34465. var rand = function (min, max) {
  34466. return Math.random() * (max - min) + min;
  34467. };
  34468. var randVector = BABYLON.Vector3.Zero();
  34469. for (var x = 0; x < size; x++) {
  34470. for (var y = 0; y < size; y++) {
  34471. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34472. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34473. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34474. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34475. context.fillRect(x, y, 1, 1);
  34476. }
  34477. }
  34478. this._randomTexture.update(false);
  34479. };
  34480. return SSAORenderingPipeline;
  34481. })(BABYLON.PostProcessRenderPipeline);
  34482. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34483. })(BABYLON || (BABYLON = {}));
  34484. var BABYLON;
  34485. (function (BABYLON) {
  34486. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34487. var VolumetricLightScatteringPostProcess = (function (_super) {
  34488. __extends(VolumetricLightScatteringPostProcess, _super);
  34489. /**
  34490. * @constructor
  34491. * @param {string} name - The post-process name
  34492. * @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)
  34493. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34494. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34495. * @param {number} samples - The post-process quality, default 100
  34496. * @param {number} samplingMode - The post-process filtering mode
  34497. * @param {BABYLON.Engine} engine - The babylon engine
  34498. * @param {boolean} reusable - If the post-process is reusable
  34499. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34500. */
  34501. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34502. var _this = this;
  34503. if (samples === void 0) { samples = 100; }
  34504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34505. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34506. this._screenCoordinates = BABYLON.Vector2.Zero();
  34507. /**
  34508. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34509. * @type {boolean}
  34510. */
  34511. this.useCustomMeshPosition = false;
  34512. /**
  34513. * If the post-process should inverse the light scattering direction
  34514. * @type {boolean}
  34515. */
  34516. this.invert = true;
  34517. /**
  34518. * Set to true to use the diffuseColor instead of the diffuseTexture
  34519. * @type {boolean}
  34520. */
  34521. this.useDiffuseColor = false;
  34522. /**
  34523. * Array containing the excluded meshes not rendered in the internal pass
  34524. */
  34525. this.excludedMeshes = new Array();
  34526. /**
  34527. * Controls the overall intensity of the post-process
  34528. * @type {number}
  34529. */
  34530. this.exposure = 0.3;
  34531. /**
  34532. * Dissipates each sample's contribution in range [0, 1]
  34533. * @type {number}
  34534. */
  34535. this.decay = 0.96815;
  34536. /**
  34537. * Controls the overall intensity of each sample
  34538. * @type {number}
  34539. */
  34540. this.weight = 0.58767;
  34541. /**
  34542. * Controls the density of each sample
  34543. * @type {number}
  34544. */
  34545. this.density = 0.926;
  34546. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34547. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34548. // Configure mesh
  34549. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34550. // Configure
  34551. this._createPass(scene, ratio.passRatio || ratio);
  34552. this.onActivate = function (camera) {
  34553. if (!_this.isSupported) {
  34554. _this.dispose(camera);
  34555. }
  34556. _this.onActivate = null;
  34557. };
  34558. this.onApply = function (effect) {
  34559. _this._updateMeshScreenCoordinates(scene);
  34560. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34561. effect.setFloat("exposure", _this.exposure);
  34562. effect.setFloat("decay", _this.decay);
  34563. effect.setFloat("weight", _this.weight);
  34564. effect.setFloat("density", _this.density);
  34565. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34566. };
  34567. }
  34568. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34569. var mesh = subMesh.getMesh();
  34570. var defines = [];
  34571. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34572. var material = subMesh.getMaterial();
  34573. var needUV = false;
  34574. // Render this.mesh as default
  34575. if (mesh === this.mesh) {
  34576. if (this.useDiffuseColor) {
  34577. defines.push("#define DIFFUSE_COLOR_RENDER");
  34578. }
  34579. else if (material) {
  34580. if (material.diffuseTexture !== undefined) {
  34581. defines.push("#define BASIC_RENDER");
  34582. }
  34583. else {
  34584. defines.push("#define DIFFUSE_COLOR_RENDER");
  34585. }
  34586. }
  34587. defines.push("#define NEED_UV");
  34588. needUV = true;
  34589. }
  34590. // Alpha test
  34591. if (material) {
  34592. if (material.needAlphaTesting()) {
  34593. defines.push("#define ALPHATEST");
  34594. }
  34595. if (material.opacityTexture !== undefined) {
  34596. defines.push("#define OPACITY");
  34597. if (material.opacityTexture.getAlphaFromRGB) {
  34598. defines.push("#define OPACITYRGB");
  34599. }
  34600. if (!needUV) {
  34601. defines.push("#define NEED_UV");
  34602. }
  34603. }
  34604. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34605. attribs.push(BABYLON.VertexBuffer.UVKind);
  34606. defines.push("#define UV1");
  34607. }
  34608. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34609. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34610. defines.push("#define UV2");
  34611. }
  34612. }
  34613. // Bones
  34614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34617. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34618. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34619. }
  34620. else {
  34621. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34622. }
  34623. // Instances
  34624. if (useInstances) {
  34625. defines.push("#define INSTANCES");
  34626. attribs.push("world0");
  34627. attribs.push("world1");
  34628. attribs.push("world2");
  34629. attribs.push("world3");
  34630. }
  34631. // Get correct effect
  34632. var join = defines.join("\n");
  34633. if (this._cachedDefines !== join) {
  34634. this._cachedDefines = join;
  34635. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34636. }
  34637. return this._volumetricLightScatteringPass.isReady();
  34638. };
  34639. /**
  34640. * Sets the new light position for light scattering effect
  34641. * @param {BABYLON.Vector3} The new custom light position
  34642. */
  34643. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34644. this._customMeshPosition = position;
  34645. };
  34646. /**
  34647. * Returns the light position for light scattering effect
  34648. * @return {BABYLON.Vector3} The custom light position
  34649. */
  34650. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34651. return this._customMeshPosition;
  34652. };
  34653. /**
  34654. * Disposes the internal assets and detaches the post-process from the camera
  34655. */
  34656. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34657. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34658. if (rttIndex !== -1) {
  34659. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34660. }
  34661. this._volumetricLightScatteringRTT.dispose();
  34662. _super.prototype.dispose.call(this, camera);
  34663. };
  34664. /**
  34665. * Returns the render target texture used by the post-process
  34666. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34667. */
  34668. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34669. return this._volumetricLightScatteringRTT;
  34670. };
  34671. // Private methods
  34672. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34673. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34674. return true;
  34675. }
  34676. return false;
  34677. };
  34678. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34679. var _this = this;
  34680. var engine = scene.getEngine();
  34681. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34682. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34683. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34684. this._volumetricLightScatteringRTT.renderList = null;
  34685. this._volumetricLightScatteringRTT.renderParticles = false;
  34686. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34687. // Custom render function for submeshes
  34688. var renderSubMesh = function (subMesh) {
  34689. var mesh = subMesh.getRenderingMesh();
  34690. if (_this._meshExcluded(mesh)) {
  34691. return;
  34692. }
  34693. var scene = mesh.getScene();
  34694. var engine = scene.getEngine();
  34695. // Culling
  34696. engine.setState(subMesh.getMaterial().backFaceCulling);
  34697. // Managing instances
  34698. var batch = mesh._getInstancesRenderList(subMesh._id);
  34699. if (batch.mustReturn) {
  34700. return;
  34701. }
  34702. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34703. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34704. engine.enableEffect(_this._volumetricLightScatteringPass);
  34705. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34706. var material = subMesh.getMaterial();
  34707. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34708. // Alpha test
  34709. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34710. var alphaTexture = material.getAlphaTestTexture();
  34711. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34712. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34713. }
  34714. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34715. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34716. if (alphaTexture) {
  34717. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34718. }
  34719. }
  34720. if (material.opacityTexture !== undefined) {
  34721. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34722. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34723. }
  34724. }
  34725. // Bones
  34726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34727. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34728. }
  34729. // Draw
  34730. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34731. }
  34732. };
  34733. // Render target texture callbacks
  34734. var savedSceneClearColor;
  34735. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34736. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34737. savedSceneClearColor = scene.clearColor;
  34738. scene.clearColor = sceneClearColor;
  34739. };
  34740. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34741. scene.clearColor = savedSceneClearColor;
  34742. };
  34743. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34744. var engine = scene.getEngine();
  34745. var index;
  34746. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34747. renderSubMesh(opaqueSubMeshes.data[index]);
  34748. }
  34749. engine.setAlphaTesting(true);
  34750. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34751. renderSubMesh(alphaTestSubMeshes.data[index]);
  34752. }
  34753. engine.setAlphaTesting(false);
  34754. if (transparentSubMeshes.length) {
  34755. // Sort sub meshes
  34756. for (index = 0; index < transparentSubMeshes.length; index++) {
  34757. var submesh = transparentSubMeshes.data[index];
  34758. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34759. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34760. }
  34761. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34762. sortedArray.sort(function (a, b) {
  34763. // Alpha index first
  34764. if (a._alphaIndex > b._alphaIndex) {
  34765. return 1;
  34766. }
  34767. if (a._alphaIndex < b._alphaIndex) {
  34768. return -1;
  34769. }
  34770. // Then distance to camera
  34771. if (a._distanceToCamera < b._distanceToCamera) {
  34772. return 1;
  34773. }
  34774. if (a._distanceToCamera > b._distanceToCamera) {
  34775. return -1;
  34776. }
  34777. return 0;
  34778. });
  34779. // Render sub meshes
  34780. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34781. for (index = 0; index < sortedArray.length; index++) {
  34782. renderSubMesh(sortedArray[index]);
  34783. }
  34784. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34785. }
  34786. };
  34787. };
  34788. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34789. var transform = scene.getTransformMatrix();
  34790. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34791. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34792. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34793. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34794. if (this.invert)
  34795. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34796. };
  34797. // Static methods
  34798. /**
  34799. * Creates a default mesh for the Volumeric Light Scattering post-process
  34800. * @param {string} The mesh name
  34801. * @param {BABYLON.Scene} The scene where to create the mesh
  34802. * @return {BABYLON.Mesh} the default mesh
  34803. */
  34804. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34805. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34806. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34807. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34808. return mesh;
  34809. };
  34810. return VolumetricLightScatteringPostProcess;
  34811. })(BABYLON.PostProcess);
  34812. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34813. })(BABYLON || (BABYLON = {}));
  34814. // BABYLON.JS Chromatic Aberration GLSL Shader
  34815. // Author: Olivier Guyot
  34816. // Separates very slightly R, G and B colors on the edges of the screen
  34817. // Inspired by Francois Tarlier & Martins Upitis
  34818. var BABYLON;
  34819. (function (BABYLON) {
  34820. var LensRenderingPipeline = (function (_super) {
  34821. __extends(LensRenderingPipeline, _super);
  34822. /**
  34823. * @constructor
  34824. *
  34825. * Effect parameters are as follow:
  34826. * {
  34827. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34828. * edge_blur: number; // from 0 to x (1 for realism)
  34829. * distortion: number; // from 0 to x (1 for realism)
  34830. * grain_amount: number; // from 0 to 1
  34831. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34832. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34833. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34834. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34835. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34836. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34837. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34838. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34839. * }
  34840. * Note: if an effect parameter is unset, effect is disabled
  34841. *
  34842. * @param {string} name - The rendering pipeline name
  34843. * @param {object} parameters - An object containing all parameters (see above)
  34844. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34845. * @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)
  34846. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34847. */
  34848. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34849. var _this = this;
  34850. if (ratio === void 0) { ratio = 1.0; }
  34851. _super.call(this, scene.getEngine(), name);
  34852. // Lens effects can be of the following:
  34853. // - chromatic aberration (slight shift of RGB colors)
  34854. // - blur on the edge of the lens
  34855. // - lens distortion
  34856. // - depth-of-field blur & highlights enhancing
  34857. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34858. // - grain effect (noise or custom texture)
  34859. // Two additional texture samplers are needed:
  34860. // - depth map (for depth-of-field)
  34861. // - grain texture
  34862. /**
  34863. * The chromatic aberration PostProcess id in the pipeline
  34864. * @type {string}
  34865. */
  34866. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34867. /**
  34868. * The highlights enhancing PostProcess id in the pipeline
  34869. * @type {string}
  34870. */
  34871. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34872. /**
  34873. * The depth-of-field PostProcess id in the pipeline
  34874. * @type {string}
  34875. */
  34876. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34877. this._scene = scene;
  34878. // Fetch texture samplers
  34879. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34880. if (parameters.grain_texture) {
  34881. this._grainTexture = parameters.grain_texture;
  34882. }
  34883. else {
  34884. this._createGrainTexture();
  34885. }
  34886. // save parameters
  34887. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34888. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34889. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34890. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34891. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34892. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34893. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34894. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34895. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34896. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34897. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34898. // Create effects
  34899. this._createChromaticAberrationPostProcess(ratio);
  34900. this._createHighlightsPostProcess(ratio);
  34901. this._createDepthOfFieldPostProcess(ratio / 4);
  34902. // Set up pipeline
  34903. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34905. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34906. if (this._highlightsGain === -1) {
  34907. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34908. }
  34909. // Finish
  34910. scene.postProcessRenderPipelineManager.addPipeline(this);
  34911. if (cameras) {
  34912. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34913. }
  34914. }
  34915. // public methods (self explanatory)
  34916. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34917. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34918. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34919. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34920. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34921. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34922. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34923. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34924. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34925. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34926. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34927. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34928. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34929. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34930. };
  34931. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34932. this._highlightsPostProcess.updateEffect();
  34933. };
  34934. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34935. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34936. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34937. this._highlightsGain = amount;
  34938. };
  34939. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34940. if (this._highlightsGain === -1) {
  34941. this._highlightsGain = 1.0;
  34942. }
  34943. this._highlightsThreshold = amount;
  34944. };
  34945. LensRenderingPipeline.prototype.disableHighlights = function () {
  34946. this._highlightsGain = -1;
  34947. };
  34948. /**
  34949. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34950. */
  34951. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34952. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34953. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34954. this._chromaticAberrationPostProcess = undefined;
  34955. this._highlightsPostProcess = undefined;
  34956. this._depthOfFieldPostProcess = undefined;
  34957. this._grainTexture.dispose();
  34958. if (disableDepthRender)
  34959. this._scene.disableDepthRenderer();
  34960. };
  34961. // colors shifting and distortion
  34962. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34963. var _this = this;
  34964. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34965. [], // samplers
  34966. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34967. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34968. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34969. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34970. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34971. };
  34972. };
  34973. // highlights enhancing
  34974. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34975. var _this = this;
  34976. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34977. [], // samplers
  34978. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34979. this._highlightsPostProcess.onApply = function (effect) {
  34980. effect.setFloat('gain', _this._highlightsGain);
  34981. effect.setFloat('threshold', _this._highlightsThreshold);
  34982. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34983. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34984. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34985. };
  34986. };
  34987. // colors shifting and distortion
  34988. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34989. var _this = this;
  34990. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34991. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34992. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34993. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34994. this._depthOfFieldPostProcess.onApply = function (effect) {
  34995. effect.setTexture("depthSampler", _this._depthTexture);
  34996. effect.setTexture("grainSampler", _this._grainTexture);
  34997. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34998. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34999. effect.setFloat('grain_amount', _this._grainAmount);
  35000. effect.setBool('blur_noise', _this._blurNoise);
  35001. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35002. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35003. effect.setFloat('distortion', _this._distortion);
  35004. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35005. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35006. effect.setFloat('aperture', _this._dofAperture);
  35007. effect.setFloat('darken', _this._dofDarken);
  35008. effect.setFloat('edge_blur', _this._edgeBlur);
  35009. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35010. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35011. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35012. };
  35013. };
  35014. // creates a black and white random noise texture, 512x512
  35015. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35016. var size = 512;
  35017. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35018. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35019. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35020. var context = this._grainTexture.getContext();
  35021. var rand = function (min, max) {
  35022. return Math.random() * (max - min) + min;
  35023. };
  35024. var value;
  35025. for (var x = 0; x < size; x++) {
  35026. for (var y = 0; y < size; y++) {
  35027. value = Math.floor(rand(0.42, 0.58) * 255);
  35028. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35029. context.fillRect(x, y, 1, 1);
  35030. }
  35031. }
  35032. this._grainTexture.update(false);
  35033. };
  35034. return LensRenderingPipeline;
  35035. })(BABYLON.PostProcessRenderPipeline);
  35036. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35037. })(BABYLON || (BABYLON = {}));
  35038. //
  35039. // This post-process allows the modification of rendered colors by using
  35040. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35041. //
  35042. // The object needs to be provided an url to a texture containing the color
  35043. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35044. // Use an image editing software to tweak the LUT to match your needs.
  35045. //
  35046. // For an example of a color LUT, see here:
  35047. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35048. // For explanations on color grading, see here:
  35049. // http://udn.epicgames.com/Three/ColorGrading.html
  35050. //
  35051. var BABYLON;
  35052. (function (BABYLON) {
  35053. var ColorCorrectionPostProcess = (function (_super) {
  35054. __extends(ColorCorrectionPostProcess, _super);
  35055. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35056. var _this = this;
  35057. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35058. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35059. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35060. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35061. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35062. this.onApply = function (effect) {
  35063. effect.setTexture("colorTable", _this._colorTableTexture);
  35064. };
  35065. }
  35066. return ColorCorrectionPostProcess;
  35067. })(BABYLON.PostProcess);
  35068. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35069. })(BABYLON || (BABYLON = {}));
  35070. var BABYLON;
  35071. (function (BABYLON) {
  35072. var AnaglyphFreeCamera = (function (_super) {
  35073. __extends(AnaglyphFreeCamera, _super);
  35074. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35075. _super.call(this, name, position, scene);
  35076. this.interaxialDistance = interaxialDistance;
  35077. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35078. }
  35079. return AnaglyphFreeCamera;
  35080. })(BABYLON.FreeCamera);
  35081. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35082. var AnaglyphArcRotateCamera = (function (_super) {
  35083. __extends(AnaglyphArcRotateCamera, _super);
  35084. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35085. _super.call(this, name, alpha, beta, radius, target, scene);
  35086. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35087. }
  35088. return AnaglyphArcRotateCamera;
  35089. })(BABYLON.ArcRotateCamera);
  35090. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35091. var AnaglyphGamepadCamera = (function (_super) {
  35092. __extends(AnaglyphGamepadCamera, _super);
  35093. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35094. _super.call(this, name, position, scene);
  35095. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35096. }
  35097. return AnaglyphGamepadCamera;
  35098. })(BABYLON.GamepadCamera);
  35099. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35100. var StereoscopicFreeCamera = (function (_super) {
  35101. __extends(StereoscopicFreeCamera, _super);
  35102. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35103. _super.call(this, name, position, scene);
  35104. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35105. }
  35106. return StereoscopicFreeCamera;
  35107. })(BABYLON.FreeCamera);
  35108. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35109. var StereoscopicArcRotateCamera = (function (_super) {
  35110. __extends(StereoscopicArcRotateCamera, _super);
  35111. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35112. _super.call(this, name, alpha, beta, radius, target, scene);
  35113. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35114. }
  35115. return StereoscopicArcRotateCamera;
  35116. })(BABYLON.ArcRotateCamera);
  35117. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35118. var StereoscopicGamepadCamera = (function (_super) {
  35119. __extends(StereoscopicGamepadCamera, _super);
  35120. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35121. _super.call(this, name, position, scene);
  35122. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35123. }
  35124. return StereoscopicGamepadCamera;
  35125. })(BABYLON.GamepadCamera);
  35126. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35127. })(BABYLON || (BABYLON = {}));
  35128. var BABYLON;
  35129. (function (BABYLON) {
  35130. var HDRRenderingPipeline = (function (_super) {
  35131. __extends(HDRRenderingPipeline, _super);
  35132. /**
  35133. * @constructor
  35134. * @param {string} name - The rendering pipeline name
  35135. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35136. * @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)
  35137. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35138. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35139. */
  35140. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35141. var _this = this;
  35142. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35143. _super.call(this, scene.getEngine(), name);
  35144. /**
  35145. * Public members
  35146. */
  35147. // Gaussian Blur
  35148. /**
  35149. * Gaussian blur coefficient
  35150. * @type {number}
  35151. */
  35152. this.gaussCoeff = 0.3;
  35153. /**
  35154. * Gaussian blur mean
  35155. * @type {number}
  35156. */
  35157. this.gaussMean = 1.0;
  35158. /**
  35159. * Gaussian blur standard deviation
  35160. * @type {number}
  35161. */
  35162. this.gaussStandDev = 0.8;
  35163. /**
  35164. * Gaussian blur multiplier. Multiplies the blur effect
  35165. * @type {number}
  35166. */
  35167. this.gaussMultiplier = 4.0;
  35168. // HDR
  35169. /**
  35170. * Exposure, controls the overall intensity of the pipeline
  35171. * @type {number}
  35172. */
  35173. this.exposure = 1.0;
  35174. /**
  35175. * Minimum luminance that the post-process can output. Luminance is >= 0
  35176. * @type {number}
  35177. */
  35178. this.minimumLuminance = 1.0;
  35179. /**
  35180. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35181. * @type {number}
  35182. */
  35183. this.maximumLuminance = 1e20;
  35184. /**
  35185. * Increase rate for luminance: eye adaptation speed to dark
  35186. * @type {number}
  35187. */
  35188. this.luminanceIncreaserate = 0.5;
  35189. /**
  35190. * Decrease rate for luminance: eye adaptation speed to bright
  35191. * @type {number}
  35192. */
  35193. this.luminanceDecreaseRate = 0.5;
  35194. // Bright pass
  35195. /**
  35196. * Minimum luminance needed to compute HDR
  35197. * @type {number}
  35198. */
  35199. this.brightThreshold = 0.8;
  35200. this._needUpdate = true;
  35201. this._scene = scene;
  35202. // Bright pass
  35203. this._createBrightPassPostProcess(scene, ratio);
  35204. // Down sample X4
  35205. this._createDownSampleX4PostProcess(scene, ratio);
  35206. // Create gaussian blur post-processes
  35207. this._createGaussianBlurPostProcess(scene, ratio);
  35208. // Texture adder
  35209. this._createTextureAdderPostProcess(scene, ratio);
  35210. // Luminance generator
  35211. this._createLuminanceGeneratorPostProcess(scene);
  35212. // HDR
  35213. this._createHDRPostProcess(scene, ratio);
  35214. // Pass postprocess
  35215. if (originalPostProcess === null) {
  35216. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35217. }
  35218. else {
  35219. this._originalPostProcess = originalPostProcess;
  35220. }
  35221. // Configure pipeline
  35222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35228. var addDownSamplerPostProcess = function (id) {
  35229. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35230. };
  35231. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35232. addDownSamplerPostProcess(i);
  35233. }
  35234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35235. // Finish
  35236. scene.postProcessRenderPipelineManager.addPipeline(this);
  35237. if (cameras !== null) {
  35238. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35239. }
  35240. this.update();
  35241. }
  35242. /**
  35243. * Tells the pipeline to update its post-processes
  35244. */
  35245. HDRRenderingPipeline.prototype.update = function () {
  35246. this._needUpdate = true;
  35247. };
  35248. /**
  35249. * Returns the current calculated luminance
  35250. */
  35251. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35252. return this._hdrCurrentLuminance;
  35253. };
  35254. /**
  35255. * Returns the currently drawn luminance
  35256. */
  35257. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35258. return this._hdrOutputLuminance;
  35259. };
  35260. /**
  35261. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35262. */
  35263. HDRRenderingPipeline.prototype.dispose = function () {
  35264. this._originalPostProcess = undefined;
  35265. this._brightPassPostProcess = undefined;
  35266. this._downSampleX4PostProcess = undefined;
  35267. this._guassianBlurHPostProcess = undefined;
  35268. this._guassianBlurVPostProcess = undefined;
  35269. this._textureAdderPostProcess = undefined;
  35270. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35271. this._downSamplePostProcesses[i] = undefined;
  35272. }
  35273. this._hdrPostProcess = undefined;
  35274. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35275. };
  35276. /**
  35277. * Creates the HDR post-process and computes the luminance adaptation
  35278. */
  35279. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35280. var _this = this;
  35281. var hdrLastLuminance = 0.0;
  35282. this._hdrOutputLuminance = -1.0;
  35283. this._hdrCurrentLuminance = 1.0;
  35284. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35285. this._hdrPostProcess.onApply = function (effect) {
  35286. if (_this._hdrOutputLuminance < 0.0) {
  35287. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35288. }
  35289. else {
  35290. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35291. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35292. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35293. }
  35294. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35295. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35296. }
  35297. else {
  35298. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35299. }
  35300. }
  35301. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35302. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35303. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35304. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35305. effect.setFloat("exposure", _this.exposure);
  35306. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35307. _this._needUpdate = false;
  35308. };
  35309. };
  35310. /**
  35311. * Texture Adder post-process
  35312. */
  35313. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35314. var _this = this;
  35315. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35316. this._textureAdderPostProcess.onApply = function (effect) {
  35317. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35318. };
  35319. };
  35320. /**
  35321. * Down sample X4 post-process
  35322. */
  35323. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35324. var _this = this;
  35325. var downSampleX4Offsets = new Array(32);
  35326. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35327. this._downSampleX4PostProcess.onApply = function (effect) {
  35328. if (_this._needUpdate) {
  35329. var id = 0;
  35330. for (var i = -2; i < 2; i++) {
  35331. for (var j = -2; j < 2; j++) {
  35332. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35333. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35334. id += 2;
  35335. }
  35336. }
  35337. }
  35338. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35339. };
  35340. };
  35341. /**
  35342. * Bright pass post-process
  35343. */
  35344. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35345. var _this = this;
  35346. var brightOffsets = new Array(8);
  35347. var brightPassCallback = function (effect) {
  35348. if (_this._needUpdate) {
  35349. var sU = (1.0 / _this._brightPassPostProcess.width);
  35350. var sV = (1.0 / _this._brightPassPostProcess.height);
  35351. brightOffsets[0] = -0.5 * sU;
  35352. brightOffsets[1] = 0.5 * sV;
  35353. brightOffsets[2] = 0.5 * sU;
  35354. brightOffsets[3] = 0.5 * sV;
  35355. brightOffsets[4] = -0.5 * sU;
  35356. brightOffsets[5] = -0.5 * sV;
  35357. brightOffsets[6] = 0.5 * sU;
  35358. brightOffsets[7] = -0.5 * sV;
  35359. }
  35360. effect.setArray2("dsOffsets", brightOffsets);
  35361. effect.setFloat("brightThreshold", _this.brightThreshold);
  35362. };
  35363. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35364. this._brightPassPostProcess.onApply = brightPassCallback;
  35365. };
  35366. /**
  35367. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35368. */
  35369. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35370. var _this = this;
  35371. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35372. var luminanceOffsets = new Array(8);
  35373. var downSampleOffsets = new Array(18);
  35374. var halfDestPixelSize;
  35375. this._downSamplePostProcesses = new Array(lumSteps);
  35376. // Utils for luminance
  35377. var luminanceUpdateSourceOffsets = function (width, height) {
  35378. var sU = (1.0 / width);
  35379. var sV = (1.0 / height);
  35380. luminanceOffsets[0] = -0.5 * sU;
  35381. luminanceOffsets[1] = 0.5 * sV;
  35382. luminanceOffsets[2] = 0.5 * sU;
  35383. luminanceOffsets[3] = 0.5 * sV;
  35384. luminanceOffsets[4] = -0.5 * sU;
  35385. luminanceOffsets[5] = -0.5 * sV;
  35386. luminanceOffsets[6] = 0.5 * sU;
  35387. luminanceOffsets[7] = -0.5 * sV;
  35388. };
  35389. var luminanceUpdateDestOffsets = function (width, height) {
  35390. var id = 0;
  35391. for (var x = -1; x < 2; x++) {
  35392. for (var y = -1; y < 2; y++) {
  35393. downSampleOffsets[id] = (x) / width;
  35394. downSampleOffsets[id + 1] = (y) / height;
  35395. id += 2;
  35396. }
  35397. }
  35398. };
  35399. // Luminance callback
  35400. var luminanceCallback = function (effect) {
  35401. if (_this._needUpdate) {
  35402. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35403. }
  35404. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35405. effect.setArray2("lumOffsets", luminanceOffsets);
  35406. };
  35407. // Down sample callbacks
  35408. var downSampleCallback = function (indice) {
  35409. var i = indice;
  35410. return function (effect) {
  35411. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35412. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35413. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35414. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35415. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35416. effect.setArray2("dsOffsets", downSampleOffsets);
  35417. };
  35418. };
  35419. var downSampleAfterRenderCallback = function (effect) {
  35420. // Unpack result
  35421. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35422. 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);
  35423. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35424. };
  35425. // Create luminance post-process
  35426. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35427. 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);
  35428. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35429. // Create down sample post-processes
  35430. for (var i = lumSteps - 2; i >= 0; i--) {
  35431. var length = Math.pow(3, i);
  35432. ratio = { width: length, height: length };
  35433. var defines = "#define DOWN_SAMPLE\n";
  35434. if (i === 0) {
  35435. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35436. }
  35437. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35438. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35439. if (i === 0) {
  35440. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35441. }
  35442. }
  35443. };
  35444. /**
  35445. * Gaussian blur post-processes. Horizontal and Vertical
  35446. */
  35447. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35448. var _this = this;
  35449. var blurOffsetsW = new Array(9);
  35450. var blurOffsetsH = new Array(9);
  35451. var blurWeights = new Array(9);
  35452. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35453. // Utils for gaussian blur
  35454. var calculateBlurOffsets = function (height) {
  35455. var lastOutputDimensions = {
  35456. width: scene.getEngine().getRenderWidth(),
  35457. height: scene.getEngine().getRenderHeight()
  35458. };
  35459. for (var i = 0; i < 9; i++) {
  35460. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35461. if (height) {
  35462. blurOffsetsH[i] = value;
  35463. }
  35464. else {
  35465. blurOffsetsW[i] = value;
  35466. }
  35467. }
  35468. };
  35469. var calculateWeights = function () {
  35470. var x = 0.0;
  35471. for (var i = 0; i < 9; i++) {
  35472. x = (i - 4.0) / 4.0;
  35473. 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));
  35474. }
  35475. };
  35476. // Callback
  35477. var gaussianBlurCallback = function (height) {
  35478. return function (effect) {
  35479. if (_this._needUpdate) {
  35480. calculateWeights();
  35481. calculateBlurOffsets(height);
  35482. }
  35483. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35484. effect.setArray("blurWeights", blurWeights);
  35485. effect.setFloat("multiplier", _this.gaussMultiplier);
  35486. };
  35487. };
  35488. // Create horizontal gaussian blur post-processes
  35489. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35490. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35491. // Create vertical gaussian blur post-process
  35492. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35493. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35494. };
  35495. // Luminance generator
  35496. HDRRenderingPipeline.LUM_STEPS = 6;
  35497. return HDRRenderingPipeline;
  35498. })(BABYLON.PostProcessRenderPipeline);
  35499. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35500. })(BABYLON || (BABYLON = {}));
  35501. var BABYLON;
  35502. (function (BABYLON) {
  35503. var FaceAdjacencies = (function () {
  35504. function FaceAdjacencies() {
  35505. this.edges = new Array();
  35506. this.edgesConnectedCount = 0;
  35507. }
  35508. return FaceAdjacencies;
  35509. })();
  35510. var EdgesRenderer = (function () {
  35511. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35512. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35513. if (epsilon === void 0) { epsilon = 0.95; }
  35514. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35515. this._linesPositions = new Array();
  35516. this._linesNormals = new Array();
  35517. this._linesIndices = new Array();
  35518. this._buffers = new Array();
  35519. this._checkVerticesInsteadOfIndices = false;
  35520. this._source = source;
  35521. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35522. this._epsilon = epsilon;
  35523. this._prepareRessources();
  35524. this._generateEdgesLines();
  35525. }
  35526. EdgesRenderer.prototype._prepareRessources = function () {
  35527. if (this._lineShader) {
  35528. return;
  35529. }
  35530. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35531. attributes: ["position", "normal"],
  35532. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35533. });
  35534. this._lineShader.disableDepthWrite = true;
  35535. this._lineShader.backFaceCulling = false;
  35536. };
  35537. EdgesRenderer.prototype.dispose = function () {
  35538. this._vb0.dispose();
  35539. this._vb1.dispose();
  35540. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35541. this._lineShader.dispose();
  35542. };
  35543. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35544. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35545. return 0;
  35546. }
  35547. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35548. return 1;
  35549. }
  35550. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35551. return 2;
  35552. }
  35553. return -1;
  35554. };
  35555. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35556. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35557. return 0;
  35558. }
  35559. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35560. return 1;
  35561. }
  35562. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35563. return 2;
  35564. }
  35565. return -1;
  35566. };
  35567. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35568. var needToCreateLine;
  35569. if (edge === undefined) {
  35570. needToCreateLine = true;
  35571. }
  35572. else {
  35573. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35574. needToCreateLine = dotProduct < this._epsilon;
  35575. }
  35576. if (needToCreateLine) {
  35577. var offset = this._linesPositions.length / 3;
  35578. var normal = p0.subtract(p1);
  35579. normal.normalize();
  35580. // Positions
  35581. this._linesPositions.push(p0.x);
  35582. this._linesPositions.push(p0.y);
  35583. this._linesPositions.push(p0.z);
  35584. this._linesPositions.push(p0.x);
  35585. this._linesPositions.push(p0.y);
  35586. this._linesPositions.push(p0.z);
  35587. this._linesPositions.push(p1.x);
  35588. this._linesPositions.push(p1.y);
  35589. this._linesPositions.push(p1.z);
  35590. this._linesPositions.push(p1.x);
  35591. this._linesPositions.push(p1.y);
  35592. this._linesPositions.push(p1.z);
  35593. // Normals
  35594. this._linesNormals.push(p1.x);
  35595. this._linesNormals.push(p1.y);
  35596. this._linesNormals.push(p1.z);
  35597. this._linesNormals.push(-1);
  35598. this._linesNormals.push(p1.x);
  35599. this._linesNormals.push(p1.y);
  35600. this._linesNormals.push(p1.z);
  35601. this._linesNormals.push(1);
  35602. this._linesNormals.push(p0.x);
  35603. this._linesNormals.push(p0.y);
  35604. this._linesNormals.push(p0.z);
  35605. this._linesNormals.push(-1);
  35606. this._linesNormals.push(p0.x);
  35607. this._linesNormals.push(p0.y);
  35608. this._linesNormals.push(p0.z);
  35609. this._linesNormals.push(1);
  35610. // Indices
  35611. this._linesIndices.push(offset);
  35612. this._linesIndices.push(offset + 1);
  35613. this._linesIndices.push(offset + 2);
  35614. this._linesIndices.push(offset);
  35615. this._linesIndices.push(offset + 2);
  35616. this._linesIndices.push(offset + 3);
  35617. }
  35618. };
  35619. EdgesRenderer.prototype._generateEdgesLines = function () {
  35620. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35621. var indices = this._source.getIndices();
  35622. // First let's find adjacencies
  35623. var adjacencies = new Array();
  35624. var faceNormals = new Array();
  35625. var index;
  35626. var faceAdjacencies;
  35627. // Prepare faces
  35628. for (index = 0; index < indices.length; index += 3) {
  35629. faceAdjacencies = new FaceAdjacencies();
  35630. var p0Index = indices[index];
  35631. var p1Index = indices[index + 1];
  35632. var p2Index = indices[index + 2];
  35633. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35634. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35635. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35636. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35637. faceNormal.normalize();
  35638. faceNormals.push(faceNormal);
  35639. adjacencies.push(faceAdjacencies);
  35640. }
  35641. // Scan
  35642. for (index = 0; index < adjacencies.length; index++) {
  35643. faceAdjacencies = adjacencies[index];
  35644. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35645. var otherFaceAdjacencies = adjacencies[otherIndex];
  35646. if (faceAdjacencies.edgesConnectedCount === 3) {
  35647. break;
  35648. }
  35649. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35650. continue;
  35651. }
  35652. var otherP0 = indices[otherIndex * 3];
  35653. var otherP1 = indices[otherIndex * 3 + 1];
  35654. var otherP2 = indices[otherIndex * 3 + 2];
  35655. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35656. var otherEdgeIndex;
  35657. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35658. continue;
  35659. }
  35660. switch (edgeIndex) {
  35661. case 0:
  35662. if (this._checkVerticesInsteadOfIndices) {
  35663. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35664. }
  35665. else {
  35666. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35667. }
  35668. break;
  35669. case 1:
  35670. if (this._checkVerticesInsteadOfIndices) {
  35671. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35672. }
  35673. else {
  35674. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35675. }
  35676. break;
  35677. case 2:
  35678. if (this._checkVerticesInsteadOfIndices) {
  35679. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35680. }
  35681. else {
  35682. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35683. }
  35684. break;
  35685. }
  35686. if (otherEdgeIndex === -1) {
  35687. continue;
  35688. }
  35689. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35690. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35691. faceAdjacencies.edgesConnectedCount++;
  35692. otherFaceAdjacencies.edgesConnectedCount++;
  35693. if (faceAdjacencies.edgesConnectedCount === 3) {
  35694. break;
  35695. }
  35696. }
  35697. }
  35698. }
  35699. // Create lines
  35700. for (index = 0; index < adjacencies.length; index++) {
  35701. // 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
  35702. var current = adjacencies[index];
  35703. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35704. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35705. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35706. }
  35707. // Merge into a single mesh
  35708. var engine = this._source.getScene().getEngine();
  35709. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35710. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35711. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35712. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35713. this._ib = engine.createIndexBuffer(this._linesIndices);
  35714. this._indicesCount = this._linesIndices.length;
  35715. };
  35716. EdgesRenderer.prototype.render = function () {
  35717. if (!this._lineShader.isReady()) {
  35718. return;
  35719. }
  35720. var scene = this._source.getScene();
  35721. var engine = scene.getEngine();
  35722. this._lineShader._preBind();
  35723. // VBOs
  35724. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35725. scene.resetCachedMaterial();
  35726. this._lineShader.setColor4("color", this._source.edgesColor);
  35727. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35728. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35729. this._lineShader.bind(this._source.getWorldMatrix());
  35730. // Draw order
  35731. engine.draw(true, 0, this._indicesCount);
  35732. this._lineShader.unbind();
  35733. engine.setDepthWrite(true);
  35734. };
  35735. return EdgesRenderer;
  35736. })();
  35737. BABYLON.EdgesRenderer = EdgesRenderer;
  35738. })(BABYLON || (BABYLON = {}));
  35739. var BABYLON;
  35740. (function (BABYLON) {
  35741. (function (TonemappingOperator) {
  35742. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35743. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35744. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35745. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35746. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35747. var TonemappingOperator = BABYLON.TonemappingOperator;
  35748. ;
  35749. var TonemapPostProcess = (function (_super) {
  35750. __extends(TonemapPostProcess, _super);
  35751. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35752. var _this = this;
  35753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35754. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35755. this._operator = operator;
  35756. this._exposureAdjustment = exposureAdjustment;
  35757. var params = ["_ExposureAdjustment"];
  35758. var defines = "#define ";
  35759. if (operator === TonemappingOperator.Hable)
  35760. defines += "HABLE_TONEMAPPING";
  35761. else if (operator === TonemappingOperator.Reinhard)
  35762. defines += "REINHARD_TONEMAPPING";
  35763. else if (operator === TonemappingOperator.HejiDawson)
  35764. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35765. else if (operator === TonemappingOperator.Photographic)
  35766. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35767. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35768. this.onApply = function (effect) {
  35769. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35770. };
  35771. }
  35772. return TonemapPostProcess;
  35773. })(BABYLON.PostProcess);
  35774. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35775. })(BABYLON || (BABYLON = {}));
  35776. var BABYLON;
  35777. (function (BABYLON) {
  35778. var ReflectionProbe = (function () {
  35779. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35780. var _this = this;
  35781. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35782. this.name = name;
  35783. this._viewMatrix = BABYLON.Matrix.Identity();
  35784. this._target = BABYLON.Vector3.Zero();
  35785. this._add = BABYLON.Vector3.Zero();
  35786. this.position = BABYLON.Vector3.Zero();
  35787. this._scene = scene;
  35788. this._scene.reflectionProbes.push(this);
  35789. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35790. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35791. switch (faceIndex) {
  35792. case 0:
  35793. _this._add.copyFromFloats(1, 0, 0);
  35794. break;
  35795. case 1:
  35796. _this._add.copyFromFloats(-1, 0, 0);
  35797. break;
  35798. case 2:
  35799. _this._add.copyFromFloats(0, -1, 0);
  35800. break;
  35801. case 3:
  35802. _this._add.copyFromFloats(0, 1, 0);
  35803. break;
  35804. case 4:
  35805. _this._add.copyFromFloats(0, 0, 1);
  35806. break;
  35807. case 5:
  35808. _this._add.copyFromFloats(0, 0, -1);
  35809. break;
  35810. }
  35811. if (_this._attachedMesh) {
  35812. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35813. }
  35814. _this.position.addToRef(_this._add, _this._target);
  35815. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35816. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35817. };
  35818. this._renderTargetTexture.onAfterUnbind = function () {
  35819. scene.updateTransformMatrix(true);
  35820. };
  35821. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35822. }
  35823. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35824. get: function () {
  35825. return this._renderTargetTexture.refreshRate;
  35826. },
  35827. set: function (value) {
  35828. this._renderTargetTexture.refreshRate = value;
  35829. },
  35830. enumerable: true,
  35831. configurable: true
  35832. });
  35833. ReflectionProbe.prototype.getScene = function () {
  35834. return this._scene;
  35835. };
  35836. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35837. get: function () {
  35838. return this._renderTargetTexture;
  35839. },
  35840. enumerable: true,
  35841. configurable: true
  35842. });
  35843. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35844. get: function () {
  35845. return this._renderTargetTexture.renderList;
  35846. },
  35847. enumerable: true,
  35848. configurable: true
  35849. });
  35850. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35851. this._attachedMesh = mesh;
  35852. };
  35853. ReflectionProbe.prototype.dispose = function () {
  35854. var index = this._scene.reflectionProbes.indexOf(this);
  35855. if (index !== -1) {
  35856. // Remove from the scene if found
  35857. this._scene.reflectionProbes.splice(index, 1);
  35858. }
  35859. if (this._renderTargetTexture) {
  35860. this._renderTargetTexture.dispose();
  35861. this._renderTargetTexture = null;
  35862. }
  35863. };
  35864. return ReflectionProbe;
  35865. })();
  35866. BABYLON.ReflectionProbe = ReflectionProbe;
  35867. })(BABYLON || (BABYLON = {}));
  35868. var BABYLON;
  35869. (function (BABYLON) {
  35870. var SolidParticle = (function () {
  35871. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35872. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35873. this.position = BABYLON.Vector3.Zero(); // position
  35874. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35875. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35876. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35877. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35878. this.alive = true; // alive
  35879. this.idx = particleIndex;
  35880. this._pos = positionIndex;
  35881. this._model = model;
  35882. this.shapeId = shapeId;
  35883. this.idxInShape = idxInShape;
  35884. }
  35885. return SolidParticle;
  35886. })();
  35887. BABYLON.SolidParticle = SolidParticle;
  35888. var ModelShape = (function () {
  35889. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35890. this.shapeID = id;
  35891. this._shape = shape;
  35892. this._shapeUV = shapeUV;
  35893. this._positionFunction = posFunction;
  35894. this._vertexFunction = vtxFunction;
  35895. }
  35896. return ModelShape;
  35897. })();
  35898. BABYLON.ModelShape = ModelShape;
  35899. })(BABYLON || (BABYLON = {}));
  35900. var BABYLON;
  35901. (function (BABYLON) {
  35902. var SolidParticleSystem = (function () {
  35903. function SolidParticleSystem(name, scene, options) {
  35904. // public members
  35905. this.particles = new Array();
  35906. this.nbParticles = 0;
  35907. this.billboard = false;
  35908. this.counter = 0;
  35909. this.vars = {};
  35910. this._positions = new Array();
  35911. this._indices = new Array();
  35912. this._normals = new Array();
  35913. this._colors = new Array();
  35914. this._uvs = new Array();
  35915. this._index = 0; // indices index
  35916. this._updatable = true;
  35917. this._pickable = false;
  35918. this._alwaysVisible = false;
  35919. this._shapeCounter = 0;
  35920. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35921. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35922. this._computeParticleColor = true;
  35923. this._computeParticleTexture = true;
  35924. this._computeParticleRotation = true;
  35925. this._computeParticleVertex = false;
  35926. this._cam_axisZ = BABYLON.Vector3.Zero();
  35927. this._cam_axisY = BABYLON.Vector3.Zero();
  35928. this._cam_axisX = BABYLON.Vector3.Zero();
  35929. this._axisX = BABYLON.Axis.X;
  35930. this._axisY = BABYLON.Axis.Y;
  35931. this._axisZ = BABYLON.Axis.Z;
  35932. this._fakeCamPos = BABYLON.Vector3.Zero();
  35933. this._rotMatrix = new BABYLON.Matrix();
  35934. this._invertMatrix = new BABYLON.Matrix();
  35935. this._rotated = BABYLON.Vector3.Zero();
  35936. this._quaternion = new BABYLON.Quaternion();
  35937. this._vertex = BABYLON.Vector3.Zero();
  35938. this._normal = BABYLON.Vector3.Zero();
  35939. this._yaw = 0.0;
  35940. this._pitch = 0.0;
  35941. this._roll = 0.0;
  35942. this._halfroll = 0.0;
  35943. this._halfpitch = 0.0;
  35944. this._halfyaw = 0.0;
  35945. this._sinRoll = 0.0;
  35946. this._cosRoll = 0.0;
  35947. this._sinPitch = 0.0;
  35948. this._cosPitch = 0.0;
  35949. this._sinYaw = 0.0;
  35950. this._cosYaw = 0.0;
  35951. this._w = 0.0;
  35952. this.name = name;
  35953. this._scene = scene;
  35954. this._camera = scene.activeCamera;
  35955. this._pickable = options ? options.isPickable : false;
  35956. if (options && options.updatable) {
  35957. this._updatable = options.updatable;
  35958. }
  35959. else {
  35960. this._updatable = true;
  35961. }
  35962. if (this._pickable) {
  35963. this.pickedParticles = [];
  35964. }
  35965. }
  35966. // build the SPS mesh : returns the mesh
  35967. SolidParticleSystem.prototype.buildMesh = function () {
  35968. if (this.nbParticles === 0) {
  35969. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35970. this.addShape(triangle, 1);
  35971. triangle.dispose();
  35972. }
  35973. this._positions32 = new Float32Array(this._positions);
  35974. this._uvs32 = new Float32Array(this._uvs);
  35975. this._colors32 = new Float32Array(this._colors);
  35976. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35977. this._normals32 = new Float32Array(this._normals);
  35978. this._fixedNormal32 = new Float32Array(this._normals);
  35979. var vertexData = new BABYLON.VertexData();
  35980. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35981. vertexData.indices = this._indices;
  35982. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35983. if (this._uvs32) {
  35984. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35985. ;
  35986. }
  35987. if (this._colors32) {
  35988. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35989. }
  35990. var mesh = new BABYLON.Mesh(name, this._scene);
  35991. vertexData.applyToMesh(mesh, this._updatable);
  35992. this.mesh = mesh;
  35993. this.mesh.isPickable = this._pickable;
  35994. // free memory
  35995. this._positions = null;
  35996. this._normals = null;
  35997. this._uvs = null;
  35998. this._colors = null;
  35999. if (!this._updatable) {
  36000. this.particles.length = 0;
  36001. }
  36002. return mesh;
  36003. };
  36004. //reset copy
  36005. SolidParticleSystem.prototype._resetCopy = function () {
  36006. this._copy.position.x = 0;
  36007. this._copy.position.y = 0;
  36008. this._copy.position.z = 0;
  36009. this._copy.rotation.x = 0;
  36010. this._copy.rotation.y = 0;
  36011. this._copy.rotation.z = 0;
  36012. this._copy.quaternion = null;
  36013. this._copy.scale.x = 1;
  36014. this._copy.scale.y = 1;
  36015. this._copy.scale.z = 1;
  36016. this._copy.uvs.x = 0;
  36017. this._copy.uvs.y = 0;
  36018. this._copy.uvs.z = 1;
  36019. this._copy.uvs.w = 1;
  36020. this._copy.color = null;
  36021. };
  36022. // _meshBuilder : inserts the shape model in the global SPS mesh
  36023. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36024. var i;
  36025. var u = 0;
  36026. var c = 0;
  36027. this._resetCopy();
  36028. if (options && options.positionFunction) {
  36029. options.positionFunction(this._copy, idx, idxInShape);
  36030. }
  36031. if (this._copy.quaternion) {
  36032. this._quaternion.x = this._copy.quaternion.x;
  36033. this._quaternion.y = this._copy.quaternion.y;
  36034. this._quaternion.z = this._copy.quaternion.z;
  36035. this._quaternion.w = this._copy.quaternion.w;
  36036. }
  36037. else {
  36038. this._yaw = this._copy.rotation.y;
  36039. this._pitch = this._copy.rotation.x;
  36040. this._roll = this._copy.rotation.z;
  36041. this._quaternionRotationYPR();
  36042. }
  36043. this._quaternionToRotationMatrix();
  36044. for (i = 0; i < shape.length; i++) {
  36045. this._vertex.x = shape[i].x;
  36046. this._vertex.y = shape[i].y;
  36047. this._vertex.z = shape[i].z;
  36048. if (options && options.vertexFunction) {
  36049. options.vertexFunction(this._copy, this._vertex, i);
  36050. }
  36051. this._vertex.x *= this._copy.scale.x;
  36052. this._vertex.y *= this._copy.scale.y;
  36053. this._vertex.z *= this._copy.scale.z;
  36054. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36055. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36056. if (meshUV) {
  36057. 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);
  36058. u += 2;
  36059. }
  36060. if (this._copy.color) {
  36061. this._color = this._copy.color;
  36062. }
  36063. else if (meshCol && meshCol[c]) {
  36064. this._color.r = meshCol[c];
  36065. this._color.g = meshCol[c + 1];
  36066. this._color.b = meshCol[c + 2];
  36067. this._color.a = meshCol[c + 3];
  36068. }
  36069. else {
  36070. this._color.r = 1;
  36071. this._color.g = 1;
  36072. this._color.b = 1;
  36073. this._color.a = 1;
  36074. }
  36075. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36076. c += 4;
  36077. }
  36078. for (i = 0; i < meshInd.length; i++) {
  36079. indices.push(p + meshInd[i]);
  36080. }
  36081. if (this._pickable) {
  36082. var nbfaces = meshInd.length / 3;
  36083. for (i = 0; i < nbfaces; i++) {
  36084. this.pickedParticles.push({ idx: idx, faceId: i });
  36085. }
  36086. }
  36087. };
  36088. // returns a shape array from positions array
  36089. SolidParticleSystem.prototype._posToShape = function (positions) {
  36090. var shape = [];
  36091. for (var i = 0; i < positions.length; i += 3) {
  36092. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36093. }
  36094. return shape;
  36095. };
  36096. // returns a shapeUV array from a Vector4 uvs
  36097. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36098. var shapeUV = [];
  36099. if (uvs) {
  36100. for (var i = 0; i < uvs.length; i++)
  36101. shapeUV.push(uvs[i]);
  36102. }
  36103. return shapeUV;
  36104. };
  36105. // adds a new particle object in the particles array
  36106. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36107. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36108. };
  36109. // add solid particles from a shape model in the particles array
  36110. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36111. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36112. var meshInd = mesh.getIndices();
  36113. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36114. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36115. var shape = this._posToShape(meshPos);
  36116. var shapeUV = this._uvsToShapeUV(meshUV);
  36117. var posfunc = options ? options.positionFunction : null;
  36118. var vtxfunc = options ? options.vertexFunction : null;
  36119. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36120. // particles
  36121. var idx = this.nbParticles;
  36122. for (var i = 0; i < nb; i++) {
  36123. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36124. if (this._updatable) {
  36125. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36126. }
  36127. this._index += shape.length;
  36128. idx++;
  36129. }
  36130. this.nbParticles += nb;
  36131. this._shapeCounter++;
  36132. return this._shapeCounter;
  36133. };
  36134. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36135. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36136. this._resetCopy();
  36137. if (particle._model._positionFunction) {
  36138. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36139. }
  36140. if (this._copy.quaternion) {
  36141. this._quaternion.x = this._copy.quaternion.x;
  36142. this._quaternion.y = this._copy.quaternion.y;
  36143. this._quaternion.z = this._copy.quaternion.z;
  36144. this._quaternion.w = this._copy.quaternion.w;
  36145. }
  36146. else {
  36147. this._yaw = this._copy.rotation.y;
  36148. this._pitch = this._copy.rotation.x;
  36149. this._roll = this._copy.rotation.z;
  36150. this._quaternionRotationYPR();
  36151. }
  36152. this._quaternionToRotationMatrix();
  36153. this._shape = particle._model._shape;
  36154. for (var pt = 0; pt < this._shape.length; pt++) {
  36155. this._vertex.x = this._shape[pt].x;
  36156. this._vertex.y = this._shape[pt].y;
  36157. this._vertex.z = this._shape[pt].z;
  36158. if (particle._model._vertexFunction) {
  36159. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36160. }
  36161. this._vertex.x *= this._copy.scale.x;
  36162. this._vertex.y *= this._copy.scale.y;
  36163. this._vertex.z *= this._copy.scale.z;
  36164. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36165. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36166. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36167. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36168. }
  36169. particle.position.x = 0;
  36170. particle.position.y = 0;
  36171. particle.position.z = 0;
  36172. particle.rotation.x = 0;
  36173. particle.rotation.y = 0;
  36174. particle.rotation.z = 0;
  36175. particle.quaternion = null;
  36176. particle.scale.x = 1;
  36177. particle.scale.y = 1;
  36178. particle.scale.z = 1;
  36179. };
  36180. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36181. SolidParticleSystem.prototype.rebuildMesh = function () {
  36182. for (var p = 0; p < this.particles.length; p++) {
  36183. this._rebuildParticle(this.particles[p]);
  36184. }
  36185. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36186. };
  36187. // sets all the particles : updates the VBO
  36188. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36189. if (start === void 0) { start = 0; }
  36190. if (end === void 0) { end = this.nbParticles - 1; }
  36191. if (update === void 0) { update = true; }
  36192. if (!this._updatable) {
  36193. return;
  36194. }
  36195. // custom beforeUpdate
  36196. this.beforeUpdateParticles(start, end, update);
  36197. this._cam_axisX.x = 1;
  36198. this._cam_axisX.y = 0;
  36199. this._cam_axisX.z = 0;
  36200. this._cam_axisY.x = 0;
  36201. this._cam_axisY.y = 1;
  36202. this._cam_axisY.z = 0;
  36203. this._cam_axisZ.x = 0;
  36204. this._cam_axisZ.y = 0;
  36205. this._cam_axisZ.z = 1;
  36206. // if the particles will always face the camera
  36207. if (this.billboard) {
  36208. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36209. this._yaw = this.mesh.rotation.y;
  36210. this._pitch = this.mesh.rotation.x;
  36211. this._roll = this.mesh.rotation.z;
  36212. this._quaternionRotationYPR();
  36213. this._quaternionToRotationMatrix();
  36214. this._rotMatrix.invertToRef(this._invertMatrix);
  36215. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36216. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36217. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36218. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36219. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36220. this._cam_axisY.normalize();
  36221. this._cam_axisX.normalize();
  36222. this._cam_axisZ.normalize();
  36223. }
  36224. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36225. var idx = 0;
  36226. var index = 0;
  36227. var colidx = 0;
  36228. var colorIndex = 0;
  36229. var uvidx = 0;
  36230. var uvIndex = 0;
  36231. // particle loop
  36232. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36233. for (var p = start; p <= end; p++) {
  36234. this._particle = this.particles[p];
  36235. this._shape = this._particle._model._shape;
  36236. this._shapeUV = this._particle._model._shapeUV;
  36237. // call to custom user function to update the particle properties
  36238. this.updateParticle(this._particle);
  36239. // particle rotation matrix
  36240. if (this.billboard) {
  36241. this._particle.rotation.x = 0.0;
  36242. this._particle.rotation.y = 0.0;
  36243. }
  36244. if (this._computeParticleRotation) {
  36245. if (this._particle.quaternion) {
  36246. this._quaternion.x = this._particle.quaternion.x;
  36247. this._quaternion.y = this._particle.quaternion.y;
  36248. this._quaternion.z = this._particle.quaternion.z;
  36249. this._quaternion.w = this._particle.quaternion.w;
  36250. }
  36251. else {
  36252. this._yaw = this._particle.rotation.y;
  36253. this._pitch = this._particle.rotation.x;
  36254. this._roll = this._particle.rotation.z;
  36255. this._quaternionRotationYPR();
  36256. }
  36257. this._quaternionToRotationMatrix();
  36258. }
  36259. for (var pt = 0; pt < this._shape.length; pt++) {
  36260. idx = index + pt * 3;
  36261. colidx = colorIndex + pt * 4;
  36262. uvidx = uvIndex + pt * 2;
  36263. this._vertex.x = this._shape[pt].x;
  36264. this._vertex.y = this._shape[pt].y;
  36265. this._vertex.z = this._shape[pt].z;
  36266. if (this._computeParticleVertex) {
  36267. this.updateParticleVertex(this._particle, this._vertex, pt);
  36268. }
  36269. // positions
  36270. this._vertex.x *= this._particle.scale.x;
  36271. this._vertex.y *= this._particle.scale.y;
  36272. this._vertex.z *= this._particle.scale.z;
  36273. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36274. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36275. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36276. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36277. 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;
  36278. 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;
  36279. 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;
  36280. // normals : if the particles can't be morphed then just rotate the normals
  36281. if (!this._computeParticleVertex && !this.billboard) {
  36282. this._normal.x = this._fixedNormal32[idx];
  36283. this._normal.y = this._fixedNormal32[idx + 1];
  36284. this._normal.z = this._fixedNormal32[idx + 2];
  36285. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36286. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36287. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36288. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36289. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36290. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  36291. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  36292. }
  36293. if (this._computeParticleColor) {
  36294. this._colors32[colidx] = this._particle.color.r;
  36295. this._colors32[colidx + 1] = this._particle.color.g;
  36296. this._colors32[colidx + 2] = this._particle.color.b;
  36297. this._colors32[colidx + 3] = this._particle.color.a;
  36298. }
  36299. if (this._computeParticleTexture) {
  36300. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36301. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36302. }
  36303. }
  36304. index = idx + 3;
  36305. colorIndex = colidx + 4;
  36306. uvIndex = uvidx + 2;
  36307. }
  36308. if (update) {
  36309. if (this._computeParticleColor) {
  36310. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36311. }
  36312. if (this._computeParticleTexture) {
  36313. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36314. }
  36315. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36316. if (!this.mesh.areNormalsFrozen) {
  36317. if (this._computeParticleVertex || this.billboard) {
  36318. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36319. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36320. for (var i = 0; i < this._normals32.length; i++) {
  36321. this._fixedNormal32[i] = this._normals32[i];
  36322. }
  36323. }
  36324. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36325. }
  36326. }
  36327. this.afterUpdateParticles(start, end, update);
  36328. };
  36329. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36330. this._halfroll = this._roll * 0.5;
  36331. this._halfpitch = this._pitch * 0.5;
  36332. this._halfyaw = this._yaw * 0.5;
  36333. this._sinRoll = Math.sin(this._halfroll);
  36334. this._cosRoll = Math.cos(this._halfroll);
  36335. this._sinPitch = Math.sin(this._halfpitch);
  36336. this._cosPitch = Math.cos(this._halfpitch);
  36337. this._sinYaw = Math.sin(this._halfyaw);
  36338. this._cosYaw = Math.cos(this._halfyaw);
  36339. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36340. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36341. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36342. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36343. };
  36344. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36345. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36346. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36347. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36348. this._rotMatrix.m[3] = 0;
  36349. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36350. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36351. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36352. this._rotMatrix.m[7] = 0;
  36353. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36354. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36355. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36356. this._rotMatrix.m[11] = 0;
  36357. this._rotMatrix.m[12] = 0;
  36358. this._rotMatrix.m[13] = 0;
  36359. this._rotMatrix.m[14] = 0;
  36360. this._rotMatrix.m[15] = 1.0;
  36361. };
  36362. // dispose the SPS
  36363. SolidParticleSystem.prototype.dispose = function () {
  36364. this.mesh.dispose();
  36365. this.vars = null;
  36366. // drop references to internal big arrays for the GC
  36367. this._positions = null;
  36368. this._indices = null;
  36369. this._normals = null;
  36370. this._uvs = null;
  36371. this._colors = null;
  36372. this._positions32 = null;
  36373. this._normals32 = null;
  36374. this._fixedNormal32 = null;
  36375. this._uvs32 = null;
  36376. this._colors32 = null;
  36377. this.pickedParticles = null;
  36378. };
  36379. // Visibilty helpers
  36380. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36381. this.mesh.refreshBoundingInfo();
  36382. };
  36383. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36384. // getter and setter
  36385. get: function () {
  36386. return this._alwaysVisible;
  36387. },
  36388. set: function (val) {
  36389. this._alwaysVisible = val;
  36390. this.mesh.alwaysSelectAsActiveMesh = val;
  36391. },
  36392. enumerable: true,
  36393. configurable: true
  36394. });
  36395. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36396. // getters
  36397. get: function () {
  36398. return this._computeParticleRotation;
  36399. },
  36400. // Optimizer setters
  36401. set: function (val) {
  36402. this._computeParticleRotation = val;
  36403. },
  36404. enumerable: true,
  36405. configurable: true
  36406. });
  36407. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36408. get: function () {
  36409. return this._computeParticleColor;
  36410. },
  36411. set: function (val) {
  36412. this._computeParticleColor = val;
  36413. },
  36414. enumerable: true,
  36415. configurable: true
  36416. });
  36417. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36418. get: function () {
  36419. return this._computeParticleTexture;
  36420. },
  36421. set: function (val) {
  36422. this._computeParticleTexture = val;
  36423. },
  36424. enumerable: true,
  36425. configurable: true
  36426. });
  36427. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36428. get: function () {
  36429. return this._computeParticleVertex;
  36430. },
  36431. set: function (val) {
  36432. this._computeParticleVertex = val;
  36433. },
  36434. enumerable: true,
  36435. configurable: true
  36436. });
  36437. // =======================================================================
  36438. // Particle behavior logic
  36439. // these following methods may be overwritten by the user to fit his needs
  36440. // init : sets all particles first values and calls updateParticle to set them in space
  36441. // can be overwritten by the user
  36442. SolidParticleSystem.prototype.initParticles = function () {
  36443. };
  36444. // recycles a particle : can by overwritten by the user
  36445. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36446. return particle;
  36447. };
  36448. // updates a particle : can be overwritten by the user
  36449. // will be called on each particle by setParticles() :
  36450. // ex : just set a particle position or velocity and recycle conditions
  36451. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36452. return particle;
  36453. };
  36454. // updates a vertex of a particle : can be overwritten by the user
  36455. // will be called on each vertex particle by setParticles() :
  36456. // particle : the current particle
  36457. // vertex : the current index of the current particle
  36458. // pt : the index of the current vertex in the particle shape
  36459. // ex : just set a vertex particle position
  36460. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36461. return vertex;
  36462. };
  36463. // will be called before any other treatment by setParticles()
  36464. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36465. };
  36466. // will be called after all setParticles() treatments
  36467. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36468. };
  36469. return SolidParticleSystem;
  36470. })();
  36471. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36472. })(BABYLON || (BABYLON = {}));
  36473. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  36474. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*S+o*D)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*S-n*Z+o*W)*b,t.m[15]=(i*D-n*N+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;\nt.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36475. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36476. module.exports = BABYLON;
  36477. };