babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.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, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.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, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.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 normalized 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 = axis1.normalize();
  870. var w = axis3.normalize();
  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 = Tmp.Vector3[0];
  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 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // 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. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3037. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3038. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3039. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3040. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3041. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3042. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero(),
  3045. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3046. return Tmp;
  3047. })();
  3048. BABYLON.Tmp = Tmp;
  3049. })(BABYLON || (BABYLON = {}));
  3050. var BABYLON;
  3051. (function (BABYLON) {
  3052. function generateSerializableMember(type, sourceName) {
  3053. return function (target, propertyKey) {
  3054. if (!target.__serializableMembers) {
  3055. target.__serializableMembers = {};
  3056. }
  3057. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3058. };
  3059. }
  3060. function serialize(sourceName) {
  3061. return generateSerializableMember(0, sourceName); // value member
  3062. }
  3063. BABYLON.serialize = serialize;
  3064. function serializeAsTexture(sourceName) {
  3065. return generateSerializableMember(1, sourceName); // texture member
  3066. }
  3067. BABYLON.serializeAsTexture = serializeAsTexture;
  3068. function serializeAsColor3(sourceName) {
  3069. return generateSerializableMember(2, sourceName); // color3 member
  3070. }
  3071. BABYLON.serializeAsColor3 = serializeAsColor3;
  3072. function serializeAsFresnelParameters(sourceName) {
  3073. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3074. }
  3075. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3076. function serializeAsVector2(sourceName) {
  3077. return generateSerializableMember(4, sourceName); // vector2 member
  3078. }
  3079. BABYLON.serializeAsVector2 = serializeAsVector2;
  3080. function serializeAsVector3(sourceName) {
  3081. return generateSerializableMember(5, sourceName); // vector3 member
  3082. }
  3083. BABYLON.serializeAsVector3 = serializeAsVector3;
  3084. function serializeAsMeshReference(sourceName) {
  3085. return generateSerializableMember(6, sourceName); // mesh reference member
  3086. }
  3087. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3088. var SerializationHelper = (function () {
  3089. function SerializationHelper() {
  3090. }
  3091. SerializationHelper.Serialize = function (entity, serializationObject) {
  3092. if (!serializationObject) {
  3093. serializationObject = {};
  3094. }
  3095. // Tags
  3096. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3097. // Properties
  3098. for (var property in entity.__serializableMembers) {
  3099. var propertyDescriptor = entity.__serializableMembers[property];
  3100. var targetPropertyName = propertyDescriptor.sourceName || property;
  3101. var propertyType = propertyDescriptor.type;
  3102. var sourceProperty = entity[property];
  3103. if (sourceProperty !== undefined && sourceProperty !== null) {
  3104. switch (propertyType) {
  3105. case 0:
  3106. serializationObject[targetPropertyName] = sourceProperty;
  3107. break;
  3108. case 1:
  3109. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3110. break;
  3111. case 2:
  3112. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3113. break;
  3114. case 3:
  3115. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3116. break;
  3117. case 4:
  3118. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3119. break;
  3120. case 5:
  3121. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3122. break;
  3123. case 6:
  3124. serializationObject[targetPropertyName] = sourceProperty.id;
  3125. break;
  3126. }
  3127. }
  3128. }
  3129. return serializationObject;
  3130. };
  3131. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3132. var destination = creationFunction();
  3133. // Tags
  3134. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3135. // Properties
  3136. for (var property in destination.__serializableMembers) {
  3137. var propertyDescriptor = destination.__serializableMembers[property];
  3138. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3139. var propertyType = propertyDescriptor.type;
  3140. if (sourceProperty !== undefined && sourceProperty !== null) {
  3141. switch (propertyType) {
  3142. case 0:
  3143. destination[property] = sourceProperty;
  3144. break;
  3145. case 1:
  3146. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3147. break;
  3148. case 2:
  3149. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3150. break;
  3151. case 3:
  3152. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3153. break;
  3154. case 4:
  3155. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3156. break;
  3157. case 5:
  3158. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3159. break;
  3160. case 6:
  3161. destination[property] = scene.getLastMeshByID(sourceProperty);
  3162. break;
  3163. }
  3164. }
  3165. }
  3166. return destination;
  3167. };
  3168. SerializationHelper.Clone = function (creationFunction, source) {
  3169. var destination = creationFunction();
  3170. // Tags
  3171. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3172. // Properties
  3173. for (var property in destination.__serializableMembers) {
  3174. var propertyDescriptor = destination.__serializableMembers[property];
  3175. var sourceProperty = source[property];
  3176. var propertyType = propertyDescriptor.type;
  3177. if (sourceProperty !== undefined && sourceProperty !== null) {
  3178. switch (propertyType) {
  3179. case 0: // Value
  3180. case 6:
  3181. destination[property] = sourceProperty;
  3182. break;
  3183. case 1: // Texture
  3184. case 2: // Color3
  3185. case 3: // FresnelParameters
  3186. case 4: // Vector2
  3187. case 5:
  3188. destination[property] = sourceProperty.clone();
  3189. break;
  3190. }
  3191. }
  3192. }
  3193. return destination;
  3194. };
  3195. return SerializationHelper;
  3196. })();
  3197. BABYLON.SerializationHelper = SerializationHelper;
  3198. })(BABYLON || (BABYLON = {}));
  3199. var BABYLON;
  3200. (function (BABYLON) {
  3201. var Database = (function () {
  3202. function Database(urlToScene, callbackManifestChecked) {
  3203. // Handling various flavors of prefixed version of IndexedDB
  3204. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3205. this.callbackManifestChecked = callbackManifestChecked;
  3206. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3207. this.db = null;
  3208. this.enableSceneOffline = false;
  3209. this.enableTexturesOffline = false;
  3210. this.manifestVersionFound = 0;
  3211. this.mustUpdateRessources = false;
  3212. this.hasReachedQuota = false;
  3213. if (!Database.IDBStorageEnabled) {
  3214. this.callbackManifestChecked(true);
  3215. }
  3216. else {
  3217. this.checkManifestFile();
  3218. }
  3219. }
  3220. Database.prototype.checkManifestFile = function () {
  3221. var _this = this;
  3222. function noManifestFile() {
  3223. that.enableSceneOffline = false;
  3224. that.enableTexturesOffline = false;
  3225. that.callbackManifestChecked(false);
  3226. }
  3227. var that = this;
  3228. var timeStampUsed = false;
  3229. var manifestURL = this.currentSceneUrl + ".manifest";
  3230. var xhr = new XMLHttpRequest();
  3231. if (navigator.onLine) {
  3232. // Adding a timestamp to by-pass browsers' cache
  3233. timeStampUsed = true;
  3234. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3235. }
  3236. xhr.open("GET", manifestURL, true);
  3237. xhr.addEventListener("load", function () {
  3238. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3239. try {
  3240. var manifestFile = JSON.parse(xhr.response);
  3241. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3242. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3243. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3244. _this.manifestVersionFound = manifestFile.version;
  3245. }
  3246. if (_this.callbackManifestChecked) {
  3247. _this.callbackManifestChecked(true);
  3248. }
  3249. }
  3250. catch (ex) {
  3251. noManifestFile();
  3252. }
  3253. }
  3254. else {
  3255. noManifestFile();
  3256. }
  3257. }, false);
  3258. xhr.addEventListener("error", function (event) {
  3259. if (timeStampUsed) {
  3260. timeStampUsed = false;
  3261. // Let's retry without the timeStamp
  3262. // It could fail when coupled with HTML5 Offline API
  3263. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3264. xhr.open("GET", retryManifestURL, true);
  3265. xhr.send();
  3266. }
  3267. else {
  3268. noManifestFile();
  3269. }
  3270. }, false);
  3271. try {
  3272. xhr.send();
  3273. }
  3274. catch (ex) {
  3275. BABYLON.Tools.Error("Error on XHR send request.");
  3276. that.callbackManifestChecked(false);
  3277. }
  3278. };
  3279. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3280. var _this = this;
  3281. function handleError() {
  3282. that.isSupported = false;
  3283. if (errorCallback)
  3284. errorCallback();
  3285. }
  3286. var that = this;
  3287. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3288. // Your browser doesn't support IndexedDB
  3289. this.isSupported = false;
  3290. if (errorCallback)
  3291. errorCallback();
  3292. }
  3293. else {
  3294. // If the DB hasn't been opened or created yet
  3295. if (!this.db) {
  3296. this.hasReachedQuota = false;
  3297. this.isSupported = true;
  3298. var request = this.idbFactory.open("babylonjs", 1);
  3299. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3300. request.onerror = function (event) {
  3301. handleError();
  3302. };
  3303. // executes when a version change transaction cannot complete due to other active transactions
  3304. request.onblocked = function (event) {
  3305. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3306. handleError();
  3307. };
  3308. // DB has been opened successfully
  3309. request.onsuccess = function (event) {
  3310. _this.db = request.result;
  3311. successCallback();
  3312. };
  3313. // Initialization of the DB. Creating Scenes & Textures stores
  3314. request.onupgradeneeded = function (event) {
  3315. _this.db = (event.target).result;
  3316. try {
  3317. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3318. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3319. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3323. handleError();
  3324. }
  3325. };
  3326. }
  3327. else {
  3328. if (successCallback)
  3329. successCallback();
  3330. }
  3331. }
  3332. };
  3333. Database.prototype.loadImageFromDB = function (url, image) {
  3334. var _this = this;
  3335. var completeURL = Database.ReturnFullUrlLocation(url);
  3336. var saveAndLoadImage = function () {
  3337. if (!_this.hasReachedQuota && _this.db !== null) {
  3338. // the texture is not yet in the DB, let's try to save it
  3339. _this._saveImageIntoDBAsync(completeURL, image);
  3340. }
  3341. else {
  3342. image.src = url;
  3343. }
  3344. };
  3345. if (!this.mustUpdateRessources) {
  3346. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3347. }
  3348. else {
  3349. saveAndLoadImage();
  3350. }
  3351. };
  3352. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3353. if (this.isSupported && this.db !== null) {
  3354. var texture;
  3355. var transaction = this.db.transaction(["textures"]);
  3356. transaction.onabort = function (event) {
  3357. image.src = url;
  3358. };
  3359. transaction.oncomplete = function (event) {
  3360. var blobTextureURL;
  3361. if (texture) {
  3362. var URL = window.URL || window.webkitURL;
  3363. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3364. image.onerror = function () {
  3365. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3366. image.src = url;
  3367. };
  3368. image.src = blobTextureURL;
  3369. }
  3370. else {
  3371. notInDBCallback();
  3372. }
  3373. };
  3374. var getRequest = transaction.objectStore("textures").get(url);
  3375. getRequest.onsuccess = function (event) {
  3376. texture = (event.target).result;
  3377. };
  3378. getRequest.onerror = function (event) {
  3379. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3380. image.src = url;
  3381. };
  3382. }
  3383. else {
  3384. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3385. image.src = url;
  3386. }
  3387. };
  3388. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3389. var _this = this;
  3390. if (this.isSupported) {
  3391. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3392. var generateBlobUrl = function () {
  3393. var blobTextureURL;
  3394. if (blob) {
  3395. var URL = window.URL || window.webkitURL;
  3396. try {
  3397. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3398. }
  3399. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3400. catch (ex) {
  3401. blobTextureURL = URL.createObjectURL(blob);
  3402. }
  3403. }
  3404. image.src = blobTextureURL;
  3405. };
  3406. if (Database.IsUASupportingBlobStorage) {
  3407. var xhr = new XMLHttpRequest(), blob;
  3408. xhr.open("GET", url, true);
  3409. xhr.responseType = "blob";
  3410. xhr.addEventListener("load", function () {
  3411. if (xhr.status === 200) {
  3412. // Blob as response (XHR2)
  3413. blob = xhr.response;
  3414. var transaction = _this.db.transaction(["textures"], "readwrite");
  3415. // the transaction could abort because of a QuotaExceededError error
  3416. transaction.onabort = function (event) {
  3417. try {
  3418. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3419. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3420. this.hasReachedQuota = true;
  3421. }
  3422. }
  3423. catch (ex) { }
  3424. generateBlobUrl();
  3425. };
  3426. transaction.oncomplete = function (event) {
  3427. generateBlobUrl();
  3428. };
  3429. var newTexture = { textureUrl: url, data: blob };
  3430. try {
  3431. // Put the blob into the dabase
  3432. var addRequest = transaction.objectStore("textures").put(newTexture);
  3433. addRequest.onsuccess = function (event) {
  3434. };
  3435. addRequest.onerror = function (event) {
  3436. generateBlobUrl();
  3437. };
  3438. }
  3439. catch (ex) {
  3440. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3441. if (ex.code === 25) {
  3442. Database.IsUASupportingBlobStorage = false;
  3443. }
  3444. image.src = url;
  3445. }
  3446. }
  3447. else {
  3448. image.src = url;
  3449. }
  3450. }, false);
  3451. xhr.addEventListener("error", function (event) {
  3452. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3453. image.src = url;
  3454. }, false);
  3455. xhr.send();
  3456. }
  3457. else {
  3458. image.src = url;
  3459. }
  3460. }
  3461. else {
  3462. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3463. image.src = url;
  3464. }
  3465. };
  3466. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3467. var _this = this;
  3468. var updateVersion = function (event) {
  3469. // the version is not yet in the DB or we need to update it
  3470. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3471. };
  3472. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3473. };
  3474. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3475. var _this = this;
  3476. if (this.isSupported) {
  3477. var version;
  3478. try {
  3479. var transaction = this.db.transaction(["versions"]);
  3480. transaction.oncomplete = function (event) {
  3481. if (version) {
  3482. // If the version in the JSON file is > than the version in DB
  3483. if (_this.manifestVersionFound > version.data) {
  3484. _this.mustUpdateRessources = true;
  3485. updateInDBCallback();
  3486. }
  3487. else {
  3488. callback(version.data);
  3489. }
  3490. }
  3491. else {
  3492. _this.mustUpdateRessources = true;
  3493. updateInDBCallback();
  3494. }
  3495. };
  3496. transaction.onabort = function (event) {
  3497. callback(-1);
  3498. };
  3499. var getRequest = transaction.objectStore("versions").get(url);
  3500. getRequest.onsuccess = function (event) {
  3501. version = (event.target).result;
  3502. };
  3503. getRequest.onerror = function (event) {
  3504. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3505. callback(-1);
  3506. };
  3507. }
  3508. catch (ex) {
  3509. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3510. callback(-1);
  3511. }
  3512. }
  3513. else {
  3514. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3515. callback(-1);
  3516. }
  3517. };
  3518. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3519. var _this = this;
  3520. if (this.isSupported && !this.hasReachedQuota) {
  3521. try {
  3522. // Open a transaction to the database
  3523. var transaction = this.db.transaction(["versions"], "readwrite");
  3524. // the transaction could abort because of a QuotaExceededError error
  3525. transaction.onabort = function (event) {
  3526. try {
  3527. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3528. _this.hasReachedQuota = true;
  3529. }
  3530. }
  3531. catch (ex) { }
  3532. callback(-1);
  3533. };
  3534. transaction.oncomplete = function (event) {
  3535. callback(_this.manifestVersionFound);
  3536. };
  3537. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3538. // Put the scene into the database
  3539. var addRequest = transaction.objectStore("versions").put(newVersion);
  3540. addRequest.onsuccess = function (event) {
  3541. };
  3542. addRequest.onerror = function (event) {
  3543. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3544. };
  3545. }
  3546. catch (ex) {
  3547. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3548. callback(-1);
  3549. }
  3550. }
  3551. else {
  3552. callback(-1);
  3553. }
  3554. };
  3555. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3556. var _this = this;
  3557. var completeUrl = Database.ReturnFullUrlLocation(url);
  3558. var saveAndLoadFile = function (event) {
  3559. // the scene is not yet in the DB, let's try to save it
  3560. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3561. };
  3562. this._checkVersionFromDB(completeUrl, function (version) {
  3563. if (version !== -1) {
  3564. if (!_this.mustUpdateRessources) {
  3565. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3566. }
  3567. else {
  3568. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3569. }
  3570. }
  3571. else {
  3572. errorCallback();
  3573. }
  3574. });
  3575. };
  3576. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3577. if (this.isSupported) {
  3578. var targetStore;
  3579. if (url.indexOf(".babylon") !== -1) {
  3580. targetStore = "scenes";
  3581. }
  3582. else {
  3583. targetStore = "textures";
  3584. }
  3585. var file;
  3586. var transaction = this.db.transaction([targetStore]);
  3587. transaction.oncomplete = function (event) {
  3588. if (file) {
  3589. callback(file.data);
  3590. }
  3591. else {
  3592. notInDBCallback();
  3593. }
  3594. };
  3595. transaction.onabort = function (event) {
  3596. notInDBCallback();
  3597. };
  3598. var getRequest = transaction.objectStore(targetStore).get(url);
  3599. getRequest.onsuccess = function (event) {
  3600. file = (event.target).result;
  3601. };
  3602. getRequest.onerror = function (event) {
  3603. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3604. notInDBCallback();
  3605. };
  3606. }
  3607. else {
  3608. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3609. callback();
  3610. }
  3611. };
  3612. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3613. var _this = this;
  3614. if (this.isSupported) {
  3615. var targetStore;
  3616. if (url.indexOf(".babylon") !== -1) {
  3617. targetStore = "scenes";
  3618. }
  3619. else {
  3620. targetStore = "textures";
  3621. }
  3622. // Create XHR
  3623. var xhr = new XMLHttpRequest(), fileData;
  3624. xhr.open("GET", url, true);
  3625. if (useArrayBuffer) {
  3626. xhr.responseType = "arraybuffer";
  3627. }
  3628. xhr.onprogress = progressCallback;
  3629. xhr.addEventListener("load", function () {
  3630. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3631. // Blob as response (XHR2)
  3632. //fileData = xhr.responseText;
  3633. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3634. if (!_this.hasReachedQuota) {
  3635. // Open a transaction to the database
  3636. var transaction = _this.db.transaction([targetStore], "readwrite");
  3637. // the transaction could abort because of a QuotaExceededError error
  3638. transaction.onabort = function (event) {
  3639. try {
  3640. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3641. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3642. this.hasReachedQuota = true;
  3643. }
  3644. }
  3645. catch (ex) { }
  3646. callback(fileData);
  3647. };
  3648. transaction.oncomplete = function (event) {
  3649. callback(fileData);
  3650. };
  3651. var newFile;
  3652. if (targetStore === "scenes") {
  3653. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3654. }
  3655. else {
  3656. newFile = { textureUrl: url, data: fileData };
  3657. }
  3658. try {
  3659. // Put the scene into the database
  3660. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3661. addRequest.onsuccess = function (event) {
  3662. };
  3663. addRequest.onerror = function (event) {
  3664. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3665. };
  3666. }
  3667. catch (ex) {
  3668. callback(fileData);
  3669. }
  3670. }
  3671. else {
  3672. callback(fileData);
  3673. }
  3674. }
  3675. else {
  3676. callback();
  3677. }
  3678. }, false);
  3679. xhr.addEventListener("error", function (event) {
  3680. BABYLON.Tools.Error("error on XHR request.");
  3681. callback();
  3682. }, false);
  3683. xhr.send();
  3684. }
  3685. else {
  3686. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3687. callback();
  3688. }
  3689. };
  3690. Database.IsUASupportingBlobStorage = true;
  3691. Database.IDBStorageEnabled = true;
  3692. Database.parseURL = function (url) {
  3693. var a = document.createElement('a');
  3694. a.href = url;
  3695. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3696. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3697. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3698. return absLocation;
  3699. };
  3700. Database.ReturnFullUrlLocation = function (url) {
  3701. if (url.indexOf("http:/") === -1) {
  3702. return (Database.parseURL(window.location.href) + url);
  3703. }
  3704. else {
  3705. return url;
  3706. }
  3707. };
  3708. return Database;
  3709. })();
  3710. BABYLON.Database = Database;
  3711. })(BABYLON || (BABYLON = {}));
  3712. var BABYLON;
  3713. (function (BABYLON) {
  3714. var Internals;
  3715. (function (Internals) {
  3716. /*
  3717. * Based on jsTGALoader - Javascript loader for TGA file
  3718. * By Vincent Thibault
  3719. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3720. */
  3721. var TGATools = (function () {
  3722. function TGATools() {
  3723. }
  3724. TGATools.GetTGAHeader = function (data) {
  3725. var offset = 0;
  3726. var header = {
  3727. id_length: data[offset++],
  3728. colormap_type: data[offset++],
  3729. image_type: data[offset++],
  3730. colormap_index: data[offset++] | data[offset++] << 8,
  3731. colormap_length: data[offset++] | data[offset++] << 8,
  3732. colormap_size: data[offset++],
  3733. origin: [
  3734. data[offset++] | data[offset++] << 8,
  3735. data[offset++] | data[offset++] << 8
  3736. ],
  3737. width: data[offset++] | data[offset++] << 8,
  3738. height: data[offset++] | data[offset++] << 8,
  3739. pixel_size: data[offset++],
  3740. flags: data[offset++]
  3741. };
  3742. return header;
  3743. };
  3744. TGATools.UploadContent = function (gl, data) {
  3745. // Not enough data to contain header ?
  3746. if (data.length < 19) {
  3747. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3748. return;
  3749. }
  3750. // Read Header
  3751. var offset = 18;
  3752. var header = TGATools.GetTGAHeader(data);
  3753. // Assume it's a valid Targa file.
  3754. if (header.id_length + offset > data.length) {
  3755. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3756. return;
  3757. }
  3758. // Skip not needed data
  3759. offset += header.id_length;
  3760. var use_rle = false;
  3761. var use_pal = false;
  3762. var use_rgb = false;
  3763. var use_grey = false;
  3764. // Get some informations.
  3765. switch (header.image_type) {
  3766. case TGATools._TYPE_RLE_INDEXED:
  3767. use_rle = true;
  3768. case TGATools._TYPE_INDEXED:
  3769. use_pal = true;
  3770. break;
  3771. case TGATools._TYPE_RLE_RGB:
  3772. use_rle = true;
  3773. case TGATools._TYPE_RGB:
  3774. use_rgb = true;
  3775. break;
  3776. case TGATools._TYPE_RLE_GREY:
  3777. use_rle = true;
  3778. case TGATools._TYPE_GREY:
  3779. use_grey = true;
  3780. break;
  3781. }
  3782. var pixel_data;
  3783. var numAlphaBits = header.flags & 0xf;
  3784. var pixel_size = header.pixel_size >> 3;
  3785. var pixel_total = header.width * header.height * pixel_size;
  3786. // Read palettes
  3787. var palettes;
  3788. if (use_pal) {
  3789. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3790. }
  3791. // Read LRE
  3792. if (use_rle) {
  3793. pixel_data = new Uint8Array(pixel_total);
  3794. var c, count, i;
  3795. var localOffset = 0;
  3796. var pixels = new Uint8Array(pixel_size);
  3797. while (offset < pixel_total && localOffset < pixel_total) {
  3798. c = data[offset++];
  3799. count = (c & 0x7f) + 1;
  3800. // RLE pixels
  3801. if (c & 0x80) {
  3802. // Bind pixel tmp array
  3803. for (i = 0; i < pixel_size; ++i) {
  3804. pixels[i] = data[offset++];
  3805. }
  3806. // Copy pixel array
  3807. for (i = 0; i < count; ++i) {
  3808. pixel_data.set(pixels, localOffset + i * pixel_size);
  3809. }
  3810. localOffset += pixel_size * count;
  3811. }
  3812. else {
  3813. count *= pixel_size;
  3814. for (i = 0; i < count; ++i) {
  3815. pixel_data[localOffset + i] = data[offset++];
  3816. }
  3817. localOffset += count;
  3818. }
  3819. }
  3820. }
  3821. else {
  3822. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3823. }
  3824. // Load to texture
  3825. var x_start, y_start, x_step, y_step, y_end, x_end;
  3826. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3827. default:
  3828. case TGATools._ORIGIN_UL:
  3829. x_start = 0;
  3830. x_step = 1;
  3831. x_end = header.width;
  3832. y_start = 0;
  3833. y_step = 1;
  3834. y_end = header.height;
  3835. break;
  3836. case TGATools._ORIGIN_BL:
  3837. x_start = 0;
  3838. x_step = 1;
  3839. x_end = header.width;
  3840. y_start = header.height - 1;
  3841. y_step = -1;
  3842. y_end = -1;
  3843. break;
  3844. case TGATools._ORIGIN_UR:
  3845. x_start = header.width - 1;
  3846. x_step = -1;
  3847. x_end = -1;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BR:
  3853. x_start = header.width - 1;
  3854. x_step = -1;
  3855. x_end = -1;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. }
  3861. // Load the specify method
  3862. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3863. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3864. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3865. };
  3866. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3867. var image = pixel_data, colormap = palettes;
  3868. var width = header.width, height = header.height;
  3869. var color, i = 0, x, y;
  3870. var imageData = new Uint8Array(width * height * 4);
  3871. for (y = y_start; y !== y_end; y += y_step) {
  3872. for (x = x_start; x !== x_end; x += x_step, i++) {
  3873. color = image[i];
  3874. imageData[(x + width * y) * 4 + 3] = 255;
  3875. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3876. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3877. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3878. }
  3879. }
  3880. return imageData;
  3881. };
  3882. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3889. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3890. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3891. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3892. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3893. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3905. imageData[(x + width * y) * 4 + 3] = 255;
  3906. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3907. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3908. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3909. }
  3910. }
  3911. return imageData;
  3912. };
  3913. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3914. var image = pixel_data;
  3915. var width = header.width, height = header.height;
  3916. var i = 0, x, y;
  3917. var imageData = new Uint8Array(width * height * 4);
  3918. for (y = y_start; y !== y_end; y += y_step) {
  3919. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3923. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3924. }
  3925. }
  3926. return imageData;
  3927. };
  3928. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3929. var image = pixel_data;
  3930. var width = header.width, height = header.height;
  3931. var color, i = 0, x, y;
  3932. var imageData = new Uint8Array(width * height * 4);
  3933. for (y = y_start; y !== y_end; y += y_step) {
  3934. for (x = x_start; x !== x_end; x += x_step, i++) {
  3935. color = image[i];
  3936. imageData[(x + width * y) * 4 + 0] = color;
  3937. imageData[(x + width * y) * 4 + 1] = color;
  3938. imageData[(x + width * y) * 4 + 2] = color;
  3939. imageData[(x + width * y) * 4 + 3] = 255;
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3951. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3952. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3953. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3954. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3955. }
  3956. }
  3957. return imageData;
  3958. };
  3959. TGATools._TYPE_NO_DATA = 0;
  3960. TGATools._TYPE_INDEXED = 1;
  3961. TGATools._TYPE_RGB = 2;
  3962. TGATools._TYPE_GREY = 3;
  3963. TGATools._TYPE_RLE_INDEXED = 9;
  3964. TGATools._TYPE_RLE_RGB = 10;
  3965. TGATools._TYPE_RLE_GREY = 11;
  3966. TGATools._ORIGIN_MASK = 0x30;
  3967. TGATools._ORIGIN_SHIFT = 0x04;
  3968. TGATools._ORIGIN_BL = 0x00;
  3969. TGATools._ORIGIN_BR = 0x01;
  3970. TGATools._ORIGIN_UL = 0x02;
  3971. TGATools._ORIGIN_UR = 0x03;
  3972. return TGATools;
  3973. })();
  3974. Internals.TGATools = TGATools;
  3975. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3976. })(BABYLON || (BABYLON = {}));
  3977. var BABYLON;
  3978. (function (BABYLON) {
  3979. var SmartArray = (function () {
  3980. function SmartArray(capacity) {
  3981. this.length = 0;
  3982. this._duplicateId = 0;
  3983. this.data = new Array(capacity);
  3984. this._id = SmartArray._GlobalId++;
  3985. }
  3986. SmartArray.prototype.push = function (value) {
  3987. this.data[this.length++] = value;
  3988. if (this.length > this.data.length) {
  3989. this.data.length *= 2;
  3990. }
  3991. if (!value.__smartArrayFlags) {
  3992. value.__smartArrayFlags = {};
  3993. }
  3994. value.__smartArrayFlags[this._id] = this._duplicateId;
  3995. };
  3996. SmartArray.prototype.pushNoDuplicate = function (value) {
  3997. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3998. return;
  3999. }
  4000. this.push(value);
  4001. };
  4002. SmartArray.prototype.sort = function (compareFn) {
  4003. this.data.sort(compareFn);
  4004. };
  4005. SmartArray.prototype.reset = function () {
  4006. this.length = 0;
  4007. this._duplicateId++;
  4008. };
  4009. SmartArray.prototype.concat = function (array) {
  4010. if (array.length === 0) {
  4011. return;
  4012. }
  4013. if (this.length + array.length > this.data.length) {
  4014. this.data.length = (this.length + array.length) * 2;
  4015. }
  4016. for (var index = 0; index < array.length; index++) {
  4017. this.data[this.length++] = (array.data || array)[index];
  4018. }
  4019. };
  4020. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4021. if (array.length === 0) {
  4022. return;
  4023. }
  4024. if (this.length + array.length > this.data.length) {
  4025. this.data.length = (this.length + array.length) * 2;
  4026. }
  4027. for (var index = 0; index < array.length; index++) {
  4028. var item = (array.data || array)[index];
  4029. this.pushNoDuplicate(item);
  4030. }
  4031. };
  4032. SmartArray.prototype.indexOf = function (value) {
  4033. var position = this.data.indexOf(value);
  4034. if (position >= this.length) {
  4035. return -1;
  4036. }
  4037. return position;
  4038. };
  4039. // Statics
  4040. SmartArray._GlobalId = 0;
  4041. return SmartArray;
  4042. })();
  4043. BABYLON.SmartArray = SmartArray;
  4044. })(BABYLON || (BABYLON = {}));
  4045. var BABYLON;
  4046. (function (BABYLON) {
  4047. var SmartCollection = (function () {
  4048. function SmartCollection(capacity) {
  4049. if (capacity === void 0) { capacity = 10; }
  4050. this.count = 0;
  4051. this._initialCapacity = capacity;
  4052. this.items = {};
  4053. this._keys = new Array(this._initialCapacity);
  4054. }
  4055. SmartCollection.prototype.add = function (key, item) {
  4056. if (this.items[key] != undefined) {
  4057. return -1;
  4058. }
  4059. this.items[key] = item;
  4060. //literal keys are always strings, but we keep source type of key in _keys array
  4061. this._keys[this.count++] = key;
  4062. if (this.count > this._keys.length) {
  4063. this._keys.length *= 2;
  4064. }
  4065. return this.count;
  4066. };
  4067. SmartCollection.prototype.remove = function (key) {
  4068. if (this.items[key] == undefined) {
  4069. return -1;
  4070. }
  4071. return this.removeItemOfIndex(this.indexOf(key));
  4072. };
  4073. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4074. if (index < this.count && index > -1) {
  4075. delete this.items[this._keys[index]];
  4076. //here, shifting by hand is better optimised than .splice
  4077. while (index < this.count) {
  4078. this._keys[index] = this._keys[index + 1];
  4079. index++;
  4080. }
  4081. }
  4082. else {
  4083. return -1;
  4084. }
  4085. return --this.count;
  4086. };
  4087. SmartCollection.prototype.indexOf = function (key) {
  4088. for (var i = 0; i !== this.count; i++) {
  4089. if (this._keys[i] === key) {
  4090. return i;
  4091. }
  4092. }
  4093. return -1;
  4094. };
  4095. SmartCollection.prototype.item = function (key) {
  4096. return this.items[key];
  4097. };
  4098. SmartCollection.prototype.getAllKeys = function () {
  4099. if (this.count > 0) {
  4100. var keys = new Array(this.count);
  4101. for (var i = 0; i < this.count; i++) {
  4102. keys[i] = this._keys[i];
  4103. }
  4104. return keys;
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getKeyByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this._keys[index];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.getItemByIndex = function (index) {
  4119. if (index < this.count && index > -1) {
  4120. return this.items[this._keys[index]];
  4121. }
  4122. else {
  4123. return undefined;
  4124. }
  4125. };
  4126. SmartCollection.prototype.empty = function () {
  4127. if (this.count > 0) {
  4128. this.count = 0;
  4129. this.items = {};
  4130. this._keys = new Array(this._initialCapacity);
  4131. }
  4132. };
  4133. SmartCollection.prototype.forEach = function (block) {
  4134. var key;
  4135. for (key in this.items) {
  4136. if (this.items.hasOwnProperty(key)) {
  4137. block(this.items[key]);
  4138. }
  4139. }
  4140. };
  4141. return SmartCollection;
  4142. })();
  4143. BABYLON.SmartCollection = SmartCollection;
  4144. })(BABYLON || (BABYLON = {}));
  4145. var BABYLON;
  4146. (function (BABYLON) {
  4147. // Screenshots
  4148. var screenshotCanvas;
  4149. var cloneValue = function (source, destinationObject) {
  4150. if (!source)
  4151. return null;
  4152. if (source instanceof BABYLON.Mesh) {
  4153. return null;
  4154. }
  4155. if (source instanceof BABYLON.SubMesh) {
  4156. return source.clone(destinationObject);
  4157. }
  4158. else if (source.clone) {
  4159. return source.clone();
  4160. }
  4161. return null;
  4162. };
  4163. var Tools = (function () {
  4164. function Tools() {
  4165. }
  4166. Tools.Instantiate = function (className) {
  4167. var arr = className.split(".");
  4168. var fn = (window || this);
  4169. for (var i = 0, len = arr.length; i < len; i++) {
  4170. fn = fn[arr[i]];
  4171. }
  4172. if (typeof fn !== "function") {
  4173. return null;
  4174. }
  4175. return fn;
  4176. };
  4177. Tools.ToHex = function (i) {
  4178. var str = i.toString(16);
  4179. if (i <= 15) {
  4180. return ("0" + str).toUpperCase();
  4181. }
  4182. return str.toUpperCase();
  4183. };
  4184. Tools.SetImmediate = function (action) {
  4185. if (window.setImmediate) {
  4186. window.setImmediate(action);
  4187. }
  4188. else {
  4189. setTimeout(action, 1);
  4190. }
  4191. };
  4192. Tools.IsExponentOfTwo = function (value) {
  4193. var count = 1;
  4194. do {
  4195. count *= 2;
  4196. } while (count < value);
  4197. return count === value;
  4198. };
  4199. Tools.GetExponentOfTwo = function (value, max) {
  4200. var count = 1;
  4201. do {
  4202. count *= 2;
  4203. } while (count < value);
  4204. if (count > max)
  4205. count = max;
  4206. return count;
  4207. };
  4208. Tools.GetFilename = function (path) {
  4209. var index = path.lastIndexOf("/");
  4210. if (index < 0)
  4211. return path;
  4212. return path.substring(index + 1);
  4213. };
  4214. Tools.GetDOMTextContent = function (element) {
  4215. var result = "";
  4216. var child = element.firstChild;
  4217. while (child) {
  4218. if (child.nodeType === 3) {
  4219. result += child.textContent;
  4220. }
  4221. child = child.nextSibling;
  4222. }
  4223. return result;
  4224. };
  4225. Tools.ToDegrees = function (angle) {
  4226. return angle * 180 / Math.PI;
  4227. };
  4228. Tools.ToRadians = function (angle) {
  4229. return angle * Math.PI / 180;
  4230. };
  4231. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4232. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4233. var output = "";
  4234. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4235. var i = 0;
  4236. var bytes = new Uint8Array(buffer);
  4237. while (i < bytes.length) {
  4238. chr1 = bytes[i++];
  4239. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4240. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4241. enc1 = chr1 >> 2;
  4242. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4243. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4244. enc4 = chr3 & 63;
  4245. if (isNaN(chr2)) {
  4246. enc3 = enc4 = 64;
  4247. }
  4248. else if (isNaN(chr3)) {
  4249. enc4 = 64;
  4250. }
  4251. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4252. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4253. }
  4254. return "data:image/png;base64," + output;
  4255. };
  4256. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4257. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4258. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4259. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4260. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4261. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4262. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4263. }
  4264. return {
  4265. minimum: minimum,
  4266. maximum: maximum
  4267. };
  4268. };
  4269. Tools.ExtractMinAndMax = function (positions, start, count) {
  4270. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4271. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4272. for (var index = start; index < start + count; index++) {
  4273. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4274. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4275. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4276. }
  4277. return {
  4278. minimum: minimum,
  4279. maximum: maximum
  4280. };
  4281. };
  4282. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4283. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4284. return undefined;
  4285. return Array.isArray(obj) ? obj : [obj];
  4286. };
  4287. // Misc.
  4288. Tools.GetPointerPrefix = function () {
  4289. var eventPrefix = "pointer";
  4290. // Check if pointer events are supported
  4291. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4292. eventPrefix = "mouse";
  4293. }
  4294. return eventPrefix;
  4295. };
  4296. Tools.QueueNewFrame = function (func) {
  4297. if (window.requestAnimationFrame)
  4298. window.requestAnimationFrame(func);
  4299. else if (window.msRequestAnimationFrame)
  4300. window.msRequestAnimationFrame(func);
  4301. else if (window.webkitRequestAnimationFrame)
  4302. window.webkitRequestAnimationFrame(func);
  4303. else if (window.mozRequestAnimationFrame)
  4304. window.mozRequestAnimationFrame(func);
  4305. else if (window.oRequestAnimationFrame)
  4306. window.oRequestAnimationFrame(func);
  4307. else {
  4308. window.setTimeout(func, 16);
  4309. }
  4310. };
  4311. Tools.RequestFullscreen = function (element) {
  4312. if (element.requestFullscreen)
  4313. element.requestFullscreen();
  4314. else if (element.msRequestFullscreen)
  4315. element.msRequestFullscreen();
  4316. else if (element.webkitRequestFullscreen)
  4317. element.webkitRequestFullscreen();
  4318. else if (element.mozRequestFullScreen)
  4319. element.mozRequestFullScreen();
  4320. };
  4321. Tools.ExitFullscreen = function () {
  4322. if (document.exitFullscreen) {
  4323. document.exitFullscreen();
  4324. }
  4325. else if (document.mozCancelFullScreen) {
  4326. document.mozCancelFullScreen();
  4327. }
  4328. else if (document.webkitCancelFullScreen) {
  4329. document.webkitCancelFullScreen();
  4330. }
  4331. else if (document.msCancelFullScreen) {
  4332. document.msCancelFullScreen();
  4333. }
  4334. };
  4335. // External files
  4336. Tools.CleanUrl = function (url) {
  4337. url = url.replace(/#/mg, "%23");
  4338. return url;
  4339. };
  4340. Tools.LoadImage = function (url, onload, onerror, database) {
  4341. if (url instanceof ArrayBuffer) {
  4342. url = Tools.EncodeArrayBufferTobase64(url);
  4343. }
  4344. url = Tools.CleanUrl(url);
  4345. var img = new Image();
  4346. if (url.substr(0, 5) !== "data:") {
  4347. if (Tools.CorsBehavior) {
  4348. switch (typeof (Tools.CorsBehavior)) {
  4349. case "function":
  4350. var result = Tools.CorsBehavior(url);
  4351. if (result) {
  4352. img.crossOrigin = result;
  4353. }
  4354. break;
  4355. case "string":
  4356. default:
  4357. img.crossOrigin = Tools.CorsBehavior;
  4358. break;
  4359. }
  4360. }
  4361. }
  4362. img.onload = function () {
  4363. onload(img);
  4364. };
  4365. img.onerror = function (err) {
  4366. Tools.Error("Error while trying to load texture: " + url);
  4367. if (Tools.UseFallbackTexture) {
  4368. 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";
  4369. onload(img);
  4370. }
  4371. else {
  4372. onerror();
  4373. }
  4374. };
  4375. var noIndexedDB = function () {
  4376. img.src = url;
  4377. };
  4378. var loadFromIndexedDB = function () {
  4379. database.loadImageFromDB(url, img);
  4380. };
  4381. //ANY database to do!
  4382. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4383. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4384. }
  4385. else {
  4386. if (url.indexOf("file:") === -1) {
  4387. noIndexedDB();
  4388. }
  4389. else {
  4390. try {
  4391. var textureName = url.substring(5);
  4392. var blobURL;
  4393. try {
  4394. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4395. }
  4396. catch (ex) {
  4397. // Chrome doesn't support oneTimeOnly parameter
  4398. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4399. }
  4400. img.src = blobURL;
  4401. }
  4402. catch (e) {
  4403. img.src = null;
  4404. }
  4405. }
  4406. }
  4407. return img;
  4408. };
  4409. //ANY
  4410. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4411. url = Tools.CleanUrl(url);
  4412. var noIndexedDB = function () {
  4413. var request = new XMLHttpRequest();
  4414. var loadUrl = Tools.BaseUrl + url;
  4415. request.open('GET', loadUrl, true);
  4416. if (useArrayBuffer) {
  4417. request.responseType = "arraybuffer";
  4418. }
  4419. request.onprogress = progressCallBack;
  4420. request.onreadystatechange = function () {
  4421. if (request.readyState === 4) {
  4422. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4423. callback(!useArrayBuffer ? request.responseText : request.response);
  4424. }
  4425. else {
  4426. if (onError) {
  4427. onError();
  4428. }
  4429. else {
  4430. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4431. }
  4432. }
  4433. }
  4434. };
  4435. request.send(null);
  4436. };
  4437. var loadFromIndexedDB = function () {
  4438. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4439. };
  4440. if (url.indexOf("file:") !== -1) {
  4441. var fileName = url.substring(5);
  4442. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4443. }
  4444. else {
  4445. // Caching all files
  4446. if (database && database.enableSceneOffline) {
  4447. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4448. }
  4449. else {
  4450. noIndexedDB();
  4451. }
  4452. }
  4453. };
  4454. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4455. var reader = new FileReader();
  4456. reader.onload = function (e) {
  4457. //target doesn't have result from ts 1.3
  4458. callback(e.target['result']);
  4459. };
  4460. reader.onprogress = progressCallback;
  4461. reader.readAsDataURL(fileToLoad);
  4462. };
  4463. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4464. var reader = new FileReader();
  4465. reader.onerror = function (e) {
  4466. Tools.Log("Error while reading file: " + fileToLoad.name);
  4467. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4468. };
  4469. reader.onload = function (e) {
  4470. //target doesn't have result from ts 1.3
  4471. callback(e.target['result']);
  4472. };
  4473. reader.onprogress = progressCallBack;
  4474. if (!useArrayBuffer) {
  4475. // Asynchronous read
  4476. reader.readAsText(fileToLoad);
  4477. }
  4478. else {
  4479. reader.readAsArrayBuffer(fileToLoad);
  4480. }
  4481. };
  4482. //returns a downloadable url to a file content.
  4483. Tools.FileAsURL = function (content) {
  4484. var fileBlob = new Blob([content]);
  4485. var url = window.URL || window.webkitURL;
  4486. var link = url.createObjectURL(fileBlob);
  4487. return link;
  4488. };
  4489. // Misc.
  4490. Tools.Clamp = function (value, min, max) {
  4491. if (min === void 0) { min = 0; }
  4492. if (max === void 0) { max = 1; }
  4493. return Math.min(max, Math.max(min, value));
  4494. };
  4495. // Returns -1 when value is a negative number and
  4496. // +1 when value is a positive number.
  4497. Tools.Sign = function (value) {
  4498. value = +value; // convert to a number
  4499. if (value === 0 || isNaN(value))
  4500. return value;
  4501. return value > 0 ? 1 : -1;
  4502. };
  4503. Tools.Format = function (value, decimals) {
  4504. if (decimals === void 0) { decimals = 2; }
  4505. return value.toFixed(decimals);
  4506. };
  4507. Tools.CheckExtends = function (v, min, max) {
  4508. if (v.x < min.x)
  4509. min.x = v.x;
  4510. if (v.y < min.y)
  4511. min.y = v.y;
  4512. if (v.z < min.z)
  4513. min.z = v.z;
  4514. if (v.x > max.x)
  4515. max.x = v.x;
  4516. if (v.y > max.y)
  4517. max.y = v.y;
  4518. if (v.z > max.z)
  4519. max.z = v.z;
  4520. };
  4521. Tools.WithinEpsilon = function (a, b, epsilon) {
  4522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4523. var num = a - b;
  4524. return -epsilon <= num && num <= epsilon;
  4525. };
  4526. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4527. for (var prop in source) {
  4528. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4529. continue;
  4530. }
  4531. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4532. continue;
  4533. }
  4534. var sourceValue = source[prop];
  4535. var typeOfSourceValue = typeof sourceValue;
  4536. if (typeOfSourceValue === "function") {
  4537. continue;
  4538. }
  4539. if (typeOfSourceValue === "object") {
  4540. if (sourceValue instanceof Array) {
  4541. destination[prop] = [];
  4542. if (sourceValue.length > 0) {
  4543. if (typeof sourceValue[0] == "object") {
  4544. for (var index = 0; index < sourceValue.length; index++) {
  4545. var clonedValue = cloneValue(sourceValue[index], destination);
  4546. if (destination[prop].indexOf(clonedValue) === -1) {
  4547. destination[prop].push(clonedValue);
  4548. }
  4549. }
  4550. }
  4551. else {
  4552. destination[prop] = sourceValue.slice(0);
  4553. }
  4554. }
  4555. }
  4556. else {
  4557. destination[prop] = cloneValue(sourceValue, destination);
  4558. }
  4559. }
  4560. else {
  4561. destination[prop] = sourceValue;
  4562. }
  4563. }
  4564. };
  4565. Tools.IsEmpty = function (obj) {
  4566. for (var i in obj) {
  4567. return false;
  4568. }
  4569. return true;
  4570. };
  4571. Tools.RegisterTopRootEvents = function (events) {
  4572. for (var index = 0; index < events.length; index++) {
  4573. var event = events[index];
  4574. window.addEventListener(event.name, event.handler, false);
  4575. try {
  4576. if (window.parent) {
  4577. window.parent.addEventListener(event.name, event.handler, false);
  4578. }
  4579. }
  4580. catch (e) {
  4581. }
  4582. }
  4583. };
  4584. Tools.UnregisterTopRootEvents = function (events) {
  4585. for (var index = 0; index < events.length; index++) {
  4586. var event = events[index];
  4587. window.removeEventListener(event.name, event.handler);
  4588. try {
  4589. if (window.parent) {
  4590. window.parent.removeEventListener(event.name, event.handler);
  4591. }
  4592. }
  4593. catch (e) {
  4594. }
  4595. }
  4596. };
  4597. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4598. // Read the contents of the framebuffer
  4599. var numberOfChannelsByLine = width * 4;
  4600. var halfHeight = height / 2;
  4601. //Reading datas from WebGL
  4602. var data = engine.readPixels(0, 0, width, height);
  4603. //To flip image on Y axis.
  4604. for (var i = 0; i < halfHeight; i++) {
  4605. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4606. var currentCell = j + i * numberOfChannelsByLine;
  4607. var targetLine = height - i - 1;
  4608. var targetCell = j + targetLine * numberOfChannelsByLine;
  4609. var temp = data[currentCell];
  4610. data[currentCell] = data[targetCell];
  4611. data[targetCell] = temp;
  4612. }
  4613. }
  4614. // Create a 2D canvas to store the result
  4615. if (!screenshotCanvas) {
  4616. screenshotCanvas = document.createElement('canvas');
  4617. }
  4618. screenshotCanvas.width = width;
  4619. screenshotCanvas.height = height;
  4620. var context = screenshotCanvas.getContext('2d');
  4621. // Copy the pixels to a 2D canvas
  4622. var imageData = context.createImageData(width, height);
  4623. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4624. var castData = imageData.data;
  4625. castData.set(data);
  4626. context.putImageData(imageData, 0, 0);
  4627. var base64Image = screenshotCanvas.toDataURL();
  4628. if (successCallback) {
  4629. successCallback(base64Image);
  4630. }
  4631. else {
  4632. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4633. if (("download" in document.createElement("a"))) {
  4634. var a = window.document.createElement("a");
  4635. a.href = base64Image;
  4636. var date = new Date();
  4637. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4638. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4639. window.document.body.appendChild(a);
  4640. a.addEventListener("click", function () {
  4641. a.parentElement.removeChild(a);
  4642. });
  4643. a.click();
  4644. }
  4645. else {
  4646. var newWindow = window.open("");
  4647. var img = newWindow.document.createElement("img");
  4648. img.src = base64Image;
  4649. newWindow.document.body.appendChild(img);
  4650. }
  4651. }
  4652. };
  4653. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4654. var width;
  4655. var height;
  4656. //If a precision value is specified
  4657. if (size.precision) {
  4658. width = Math.round(engine.getRenderWidth() * size.precision);
  4659. height = Math.round(width / engine.getAspectRatio(camera));
  4660. size = { width: width, height: height };
  4661. }
  4662. else if (size.width && size.height) {
  4663. width = size.width;
  4664. height = size.height;
  4665. }
  4666. else if (size.width && !size.height) {
  4667. width = size.width;
  4668. height = Math.round(width / engine.getAspectRatio(camera));
  4669. size = { width: width, height: height };
  4670. }
  4671. else if (size.height && !size.width) {
  4672. height = size.height;
  4673. width = Math.round(height * engine.getAspectRatio(camera));
  4674. size = { width: width, height: height };
  4675. }
  4676. else if (!isNaN(size)) {
  4677. height = size;
  4678. width = size;
  4679. }
  4680. else {
  4681. Tools.Error("Invalid 'size' parameter !");
  4682. return;
  4683. }
  4684. var scene = camera.getScene();
  4685. var previousCamera = null;
  4686. if (scene.activeCamera !== camera) {
  4687. previousCamera = scene.activeCamera;
  4688. scene.activeCamera = camera;
  4689. }
  4690. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4691. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4692. texture.renderList = scene.meshes;
  4693. texture.onAfterRender = function () {
  4694. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4695. };
  4696. scene.incrementRenderId();
  4697. texture.render(true);
  4698. texture.dispose();
  4699. if (previousCamera) {
  4700. scene.activeCamera = previousCamera;
  4701. }
  4702. camera.getProjectionMatrix(true); // Force cache refresh;
  4703. };
  4704. // XHR response validator for local file scenario
  4705. Tools.ValidateXHRData = function (xhr, dataType) {
  4706. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4707. if (dataType === void 0) { dataType = 7; }
  4708. try {
  4709. if (dataType & 1) {
  4710. if (xhr.responseText && xhr.responseText.length > 0) {
  4711. return true;
  4712. }
  4713. else if (dataType === 1) {
  4714. return false;
  4715. }
  4716. }
  4717. if (dataType & 2) {
  4718. // Check header width and height since there is no "TGA" magic number
  4719. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4720. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 2) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 4) {
  4728. // Check for the "DDS" magic number
  4729. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4730. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4731. return true;
  4732. }
  4733. else {
  4734. return false;
  4735. }
  4736. }
  4737. }
  4738. catch (e) {
  4739. }
  4740. return false;
  4741. };
  4742. Object.defineProperty(Tools, "NoneLogLevel", {
  4743. get: function () {
  4744. return Tools._NoneLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "MessageLogLevel", {
  4750. get: function () {
  4751. return Tools._MessageLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "WarningLogLevel", {
  4757. get: function () {
  4758. return Tools._WarningLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "ErrorLogLevel", {
  4764. get: function () {
  4765. return Tools._ErrorLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "AllLogLevel", {
  4771. get: function () {
  4772. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Tools._AddLogEntry = function (entry) {
  4778. Tools._LogCache = entry + Tools._LogCache;
  4779. if (Tools.OnNewCacheEntry) {
  4780. Tools.OnNewCacheEntry(entry);
  4781. }
  4782. };
  4783. Tools._FormatMessage = function (message) {
  4784. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4785. var date = new Date();
  4786. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4787. };
  4788. Tools._LogDisabled = function (message) {
  4789. // nothing to do
  4790. };
  4791. Tools._LogEnabled = function (message) {
  4792. var formattedMessage = Tools._FormatMessage(message);
  4793. console.log("BJS - " + formattedMessage);
  4794. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4795. Tools._AddLogEntry(entry);
  4796. };
  4797. Tools._WarnDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._WarnEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.warn("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._ErrorDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._ErrorEnabled = function (message) {
  4810. Tools.errorsCount++;
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.error("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Object.defineProperty(Tools, "LogCache", {
  4817. get: function () {
  4818. return Tools._LogCache;
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Tools.ClearLogCache = function () {
  4824. Tools._LogCache = "";
  4825. Tools.errorsCount = 0;
  4826. };
  4827. Object.defineProperty(Tools, "LogLevels", {
  4828. set: function (level) {
  4829. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4830. Tools.Log = Tools._LogEnabled;
  4831. }
  4832. else {
  4833. Tools.Log = Tools._LogDisabled;
  4834. }
  4835. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4836. Tools.Warn = Tools._WarnEnabled;
  4837. }
  4838. else {
  4839. Tools.Warn = Tools._WarnDisabled;
  4840. }
  4841. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4842. Tools.Error = Tools._ErrorEnabled;
  4843. }
  4844. else {
  4845. Tools.Error = Tools._ErrorDisabled;
  4846. }
  4847. },
  4848. enumerable: true,
  4849. configurable: true
  4850. });
  4851. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4852. get: function () {
  4853. return Tools._PerformanceNoneLogLevel;
  4854. },
  4855. enumerable: true,
  4856. configurable: true
  4857. });
  4858. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4859. get: function () {
  4860. return Tools._PerformanceUserMarkLogLevel;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceConsoleLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4873. set: function (level) {
  4874. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4875. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4876. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4877. return;
  4878. }
  4879. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4880. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4881. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4882. return;
  4883. }
  4884. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4885. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4891. };
  4892. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4893. };
  4894. Tools._StartUserMark = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition || !Tools._performance.mark) {
  4897. return;
  4898. }
  4899. Tools._performance.mark(counterName + "-Begin");
  4900. };
  4901. Tools._EndUserMark = function (counterName, condition) {
  4902. if (condition === void 0) { condition = true; }
  4903. if (!condition || !Tools._performance.mark) {
  4904. return;
  4905. }
  4906. Tools._performance.mark(counterName + "-End");
  4907. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4908. };
  4909. Tools._StartPerformanceConsole = function (counterName, condition) {
  4910. if (condition === void 0) { condition = true; }
  4911. if (!condition) {
  4912. return;
  4913. }
  4914. Tools._StartUserMark(counterName, condition);
  4915. if (console.time) {
  4916. console.time(counterName);
  4917. }
  4918. };
  4919. Tools._EndPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._EndUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.timeEnd(counterName);
  4927. }
  4928. };
  4929. Object.defineProperty(Tools, "Now", {
  4930. get: function () {
  4931. if (window.performance && window.performance.now) {
  4932. return window.performance.now();
  4933. }
  4934. return new Date().getTime();
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools.BaseUrl = "";
  4940. Tools.CorsBehavior = "anonymous";
  4941. Tools.UseFallbackTexture = true;
  4942. // Logs
  4943. Tools._NoneLogLevel = 0;
  4944. Tools._MessageLogLevel = 1;
  4945. Tools._WarningLogLevel = 2;
  4946. Tools._ErrorLogLevel = 4;
  4947. Tools._LogCache = "";
  4948. Tools.errorsCount = 0;
  4949. Tools.Log = Tools._LogEnabled;
  4950. Tools.Warn = Tools._WarnEnabled;
  4951. Tools.Error = Tools._ErrorEnabled;
  4952. // Performances
  4953. Tools._PerformanceNoneLogLevel = 0;
  4954. Tools._PerformanceUserMarkLogLevel = 1;
  4955. Tools._PerformanceConsoleLogLevel = 2;
  4956. Tools._performance = window.performance;
  4957. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4958. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4959. return Tools;
  4960. })();
  4961. BABYLON.Tools = Tools;
  4962. /**
  4963. * An implementation of a loop for asynchronous functions.
  4964. */
  4965. var AsyncLoop = (function () {
  4966. /**
  4967. * Constroctor.
  4968. * @param iterations the number of iterations.
  4969. * @param _fn the function to run each iteration
  4970. * @param _successCallback the callback that will be called upon succesful execution
  4971. * @param offset starting offset.
  4972. */
  4973. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4974. if (offset === void 0) { offset = 0; }
  4975. this.iterations = iterations;
  4976. this._fn = _fn;
  4977. this._successCallback = _successCallback;
  4978. this.index = offset - 1;
  4979. this._done = false;
  4980. }
  4981. /**
  4982. * Execute the next iteration. Must be called after the last iteration was finished.
  4983. */
  4984. AsyncLoop.prototype.executeNext = function () {
  4985. if (!this._done) {
  4986. if (this.index + 1 < this.iterations) {
  4987. ++this.index;
  4988. this._fn(this);
  4989. }
  4990. else {
  4991. this.breakLoop();
  4992. }
  4993. }
  4994. };
  4995. /**
  4996. * Break the loop and run the success callback.
  4997. */
  4998. AsyncLoop.prototype.breakLoop = function () {
  4999. this._done = true;
  5000. this._successCallback();
  5001. };
  5002. /**
  5003. * Helper function
  5004. */
  5005. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5006. if (offset === void 0) { offset = 0; }
  5007. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5008. loop.executeNext();
  5009. return loop;
  5010. };
  5011. /**
  5012. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5013. * @param iterations total number of iterations
  5014. * @param syncedIterations number of synchronous iterations in each async iteration.
  5015. * @param fn the function to call each iteration.
  5016. * @param callback a success call back that will be called when iterating stops.
  5017. * @param breakFunction a break condition (optional)
  5018. * @param timeout timeout settings for the setTimeout function. default - 0.
  5019. * @constructor
  5020. */
  5021. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5022. if (timeout === void 0) { timeout = 0; }
  5023. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5024. if (breakFunction && breakFunction())
  5025. loop.breakLoop();
  5026. else {
  5027. setTimeout(function () {
  5028. for (var i = 0; i < syncedIterations; ++i) {
  5029. var iteration = (loop.index * syncedIterations) + i;
  5030. if (iteration >= iterations)
  5031. break;
  5032. fn(iteration);
  5033. if (breakFunction && breakFunction()) {
  5034. loop.breakLoop();
  5035. break;
  5036. }
  5037. }
  5038. loop.executeNext();
  5039. }, timeout);
  5040. }
  5041. }, callback);
  5042. };
  5043. return AsyncLoop;
  5044. })();
  5045. BABYLON.AsyncLoop = AsyncLoop;
  5046. })(BABYLON || (BABYLON = {}));
  5047. var BABYLON;
  5048. (function (BABYLON) {
  5049. var Internals;
  5050. (function (Internals) {
  5051. var _AlphaState = (function () {
  5052. function _AlphaState() {
  5053. this._isAlphaBlendDirty = false;
  5054. this._isBlendFunctionParametersDirty = false;
  5055. this._alphaBlend = false;
  5056. this._blendFunctionParameters = new Array(4);
  5057. }
  5058. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5059. get: function () {
  5060. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5061. },
  5062. enumerable: true,
  5063. configurable: true
  5064. });
  5065. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5066. get: function () {
  5067. return this._alphaBlend;
  5068. },
  5069. set: function (value) {
  5070. if (this._alphaBlend === value) {
  5071. return;
  5072. }
  5073. this._alphaBlend = value;
  5074. this._isAlphaBlendDirty = true;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5080. if (this._blendFunctionParameters[0] === value0 &&
  5081. this._blendFunctionParameters[1] === value1 &&
  5082. this._blendFunctionParameters[2] === value2 &&
  5083. this._blendFunctionParameters[3] === value3) {
  5084. return;
  5085. }
  5086. this._blendFunctionParameters[0] = value0;
  5087. this._blendFunctionParameters[1] = value1;
  5088. this._blendFunctionParameters[2] = value2;
  5089. this._blendFunctionParameters[3] = value3;
  5090. this._isBlendFunctionParametersDirty = true;
  5091. };
  5092. _AlphaState.prototype.reset = function () {
  5093. this._alphaBlend = false;
  5094. this._blendFunctionParameters[0] = null;
  5095. this._blendFunctionParameters[1] = null;
  5096. this._blendFunctionParameters[2] = null;
  5097. this._blendFunctionParameters[3] = null;
  5098. this._isAlphaBlendDirty = true;
  5099. this._isBlendFunctionParametersDirty = false;
  5100. };
  5101. _AlphaState.prototype.apply = function (gl) {
  5102. if (!this.isDirty) {
  5103. return;
  5104. }
  5105. // Alpha blend
  5106. if (this._isAlphaBlendDirty) {
  5107. if (this._alphaBlend) {
  5108. gl.enable(gl.BLEND);
  5109. }
  5110. else {
  5111. gl.disable(gl.BLEND);
  5112. }
  5113. this._isAlphaBlendDirty = false;
  5114. }
  5115. // Alpha function
  5116. if (this._isBlendFunctionParametersDirty) {
  5117. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5118. this._isBlendFunctionParametersDirty = false;
  5119. }
  5120. };
  5121. return _AlphaState;
  5122. })();
  5123. Internals._AlphaState = _AlphaState;
  5124. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5125. })(BABYLON || (BABYLON = {}));
  5126. var BABYLON;
  5127. (function (BABYLON) {
  5128. var Internals;
  5129. (function (Internals) {
  5130. var _DepthCullingState = (function () {
  5131. function _DepthCullingState() {
  5132. this._isDepthTestDirty = false;
  5133. this._isDepthMaskDirty = false;
  5134. this._isDepthFuncDirty = false;
  5135. this._isCullFaceDirty = false;
  5136. this._isCullDirty = false;
  5137. this._isZOffsetDirty = false;
  5138. }
  5139. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5140. get: function () {
  5141. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5147. get: function () {
  5148. return this._zOffset;
  5149. },
  5150. set: function (value) {
  5151. if (this._zOffset === value) {
  5152. return;
  5153. }
  5154. this._zOffset = value;
  5155. this._isZOffsetDirty = true;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5161. get: function () {
  5162. return this._cullFace;
  5163. },
  5164. set: function (value) {
  5165. if (this._cullFace === value) {
  5166. return;
  5167. }
  5168. this._cullFace = value;
  5169. this._isCullFaceDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5175. get: function () {
  5176. return this._cull;
  5177. },
  5178. set: function (value) {
  5179. if (this._cull === value) {
  5180. return;
  5181. }
  5182. this._cull = value;
  5183. this._isCullDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5189. get: function () {
  5190. return this._depthFunc;
  5191. },
  5192. set: function (value) {
  5193. if (this._depthFunc === value) {
  5194. return;
  5195. }
  5196. this._depthFunc = value;
  5197. this._isDepthFuncDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5203. get: function () {
  5204. return this._depthMask;
  5205. },
  5206. set: function (value) {
  5207. if (this._depthMask === value) {
  5208. return;
  5209. }
  5210. this._depthMask = value;
  5211. this._isDepthMaskDirty = true;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5217. get: function () {
  5218. return this._depthTest;
  5219. },
  5220. set: function (value) {
  5221. if (this._depthTest === value) {
  5222. return;
  5223. }
  5224. this._depthTest = value;
  5225. this._isDepthTestDirty = true;
  5226. },
  5227. enumerable: true,
  5228. configurable: true
  5229. });
  5230. _DepthCullingState.prototype.reset = function () {
  5231. this._depthMask = true;
  5232. this._depthTest = true;
  5233. this._depthFunc = null;
  5234. this._cull = null;
  5235. this._cullFace = null;
  5236. this._zOffset = 0;
  5237. this._isDepthTestDirty = true;
  5238. this._isDepthMaskDirty = true;
  5239. this._isDepthFuncDirty = false;
  5240. this._isCullFaceDirty = false;
  5241. this._isCullDirty = false;
  5242. this._isZOffsetDirty = false;
  5243. };
  5244. _DepthCullingState.prototype.apply = function (gl) {
  5245. if (!this.isDirty) {
  5246. return;
  5247. }
  5248. // Cull
  5249. if (this._isCullDirty) {
  5250. if (this.cull) {
  5251. gl.enable(gl.CULL_FACE);
  5252. }
  5253. else {
  5254. gl.disable(gl.CULL_FACE);
  5255. }
  5256. this._isCullDirty = false;
  5257. }
  5258. // Cull face
  5259. if (this._isCullFaceDirty) {
  5260. gl.cullFace(this.cullFace);
  5261. this._isCullFaceDirty = false;
  5262. }
  5263. // Depth mask
  5264. if (this._isDepthMaskDirty) {
  5265. gl.depthMask(this.depthMask);
  5266. this._isDepthMaskDirty = false;
  5267. }
  5268. // Depth test
  5269. if (this._isDepthTestDirty) {
  5270. if (this.depthTest) {
  5271. gl.enable(gl.DEPTH_TEST);
  5272. }
  5273. else {
  5274. gl.disable(gl.DEPTH_TEST);
  5275. }
  5276. this._isDepthTestDirty = false;
  5277. }
  5278. // Depth func
  5279. if (this._isDepthFuncDirty) {
  5280. gl.depthFunc(this.depthFunc);
  5281. this._isDepthFuncDirty = false;
  5282. }
  5283. // zOffset
  5284. if (this._isZOffsetDirty) {
  5285. if (this.zOffset) {
  5286. gl.enable(gl.POLYGON_OFFSET_FILL);
  5287. gl.polygonOffset(this.zOffset, 0);
  5288. }
  5289. else {
  5290. gl.disable(gl.POLYGON_OFFSET_FILL);
  5291. }
  5292. this._isZOffsetDirty = false;
  5293. }
  5294. };
  5295. return _DepthCullingState;
  5296. })();
  5297. Internals._DepthCullingState = _DepthCullingState;
  5298. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5299. })(BABYLON || (BABYLON = {}));
  5300. var BABYLON;
  5301. (function (BABYLON) {
  5302. var compileShader = function (gl, source, type, defines) {
  5303. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5304. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5305. gl.compileShader(shader);
  5306. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5307. throw new Error(gl.getShaderInfoLog(shader));
  5308. }
  5309. return shader;
  5310. };
  5311. var getWebGLTextureType = function (gl, type) {
  5312. var textureType = gl.UNSIGNED_BYTE;
  5313. if (type === Engine.TEXTURETYPE_FLOAT)
  5314. textureType = gl.FLOAT;
  5315. return textureType;
  5316. };
  5317. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5318. var magFilter = gl.NEAREST;
  5319. var minFilter = gl.NEAREST;
  5320. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5321. magFilter = gl.LINEAR;
  5322. if (generateMipMaps) {
  5323. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5324. }
  5325. else {
  5326. minFilter = gl.LINEAR;
  5327. }
  5328. }
  5329. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5339. magFilter = gl.NEAREST;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.NEAREST;
  5345. }
  5346. }
  5347. return {
  5348. min: minFilter,
  5349. mag: magFilter
  5350. };
  5351. };
  5352. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5354. var engine = scene.getEngine();
  5355. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5356. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5357. gl.bindTexture(gl.TEXTURE_2D, texture);
  5358. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5359. texture._baseWidth = width;
  5360. texture._baseHeight = height;
  5361. texture._width = potWidth;
  5362. texture._height = potHeight;
  5363. texture.isReady = true;
  5364. processFunction(potWidth, potHeight);
  5365. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5368. if (!noMipmap && !isCompressed) {
  5369. gl.generateMipmap(gl.TEXTURE_2D);
  5370. }
  5371. gl.bindTexture(gl.TEXTURE_2D, null);
  5372. engine.resetTextureCache();
  5373. scene._removePendingData(texture);
  5374. if (onLoad) {
  5375. onLoad();
  5376. }
  5377. };
  5378. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5379. var img;
  5380. var onload = function () {
  5381. loadedImages[index] = img;
  5382. loadedImages._internalCount++;
  5383. scene._removePendingData(img);
  5384. if (loadedImages._internalCount === 6) {
  5385. onfinish(loadedImages);
  5386. }
  5387. };
  5388. var onerror = function () {
  5389. scene._removePendingData(img);
  5390. };
  5391. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5392. scene._addPendingData(img);
  5393. };
  5394. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5395. var loadedImages = [];
  5396. loadedImages._internalCount = 0;
  5397. for (var index = 0; index < 6; index++) {
  5398. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5399. }
  5400. };
  5401. var EngineCapabilities = (function () {
  5402. function EngineCapabilities() {
  5403. }
  5404. return EngineCapabilities;
  5405. })();
  5406. BABYLON.EngineCapabilities = EngineCapabilities;
  5407. /**
  5408. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5409. */
  5410. var Engine = (function () {
  5411. /**
  5412. * @constructor
  5413. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5414. * @param {boolean} [antialias] - enable antialias
  5415. * @param options - further options to be sent to the getContext function
  5416. */
  5417. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5418. var _this = this;
  5419. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5420. // Public members
  5421. this.isFullscreen = false;
  5422. this.isPointerLock = false;
  5423. this.cullBackFaces = true;
  5424. this.renderEvenInBackground = true;
  5425. // To enable/disable IDB support and avoid XHR on .manifest
  5426. this.enableOfflineSupport = true;
  5427. this.scenes = new Array();
  5428. this._windowIsBackground = false;
  5429. this._webGLVersion = "1.0";
  5430. this._drawCalls = 0;
  5431. this._renderingQueueLaunched = false;
  5432. this._activeRenderLoops = [];
  5433. // FPS
  5434. this.fpsRange = 60;
  5435. this.previousFramesDuration = [];
  5436. this.fps = 60;
  5437. this.deltaTime = 0;
  5438. // States
  5439. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5440. this._alphaState = new BABYLON.Internals._AlphaState();
  5441. this._alphaMode = Engine.ALPHA_DISABLE;
  5442. // Cache
  5443. this._loadedTexturesCache = new Array();
  5444. this._maxTextureChannels = 16;
  5445. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5446. this._compiledEffects = {};
  5447. this._uintIndicesCurrentlySet = false;
  5448. this._renderingCanvas = canvas;
  5449. options = options || {};
  5450. options.antialias = antialias;
  5451. if (options.preserveDrawingBuffer === undefined) {
  5452. options.preserveDrawingBuffer = false;
  5453. }
  5454. // GL
  5455. //try {
  5456. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5457. // if (this._gl) {
  5458. // this._webGLVersion = "2.0";
  5459. // }
  5460. //} catch (e) {
  5461. // // Do nothing
  5462. //}
  5463. if (!this._gl) {
  5464. try {
  5465. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5466. }
  5467. catch (e) {
  5468. throw new Error("WebGL not supported");
  5469. }
  5470. }
  5471. if (!this._gl) {
  5472. throw new Error("WebGL not supported");
  5473. }
  5474. this._onBlur = function () {
  5475. _this._windowIsBackground = true;
  5476. };
  5477. this._onFocus = function () {
  5478. _this._windowIsBackground = false;
  5479. };
  5480. window.addEventListener("blur", this._onBlur);
  5481. window.addEventListener("focus", this._onFocus);
  5482. // Viewport
  5483. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5484. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5485. this.resize();
  5486. // Caps
  5487. this._caps = new EngineCapabilities();
  5488. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5489. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5490. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5491. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5492. // Infos
  5493. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5494. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5495. if (rendererInfo != null) {
  5496. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5497. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5498. }
  5499. if (!this._glVendor) {
  5500. this._glVendor = "Unknown vendor";
  5501. }
  5502. if (!this._glRenderer) {
  5503. this._glRenderer = "Unknown renderer";
  5504. }
  5505. // Extensions
  5506. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5507. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5508. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5509. 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');
  5510. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5511. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5512. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5513. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5514. this._caps.highPrecisionShaderSupported = true;
  5515. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5516. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5517. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5518. if (this._gl.getShaderPrecisionFormat) {
  5519. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5520. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5521. }
  5522. // Depth buffer
  5523. this.setDepthBuffer(true);
  5524. this.setDepthFunctionToLessOrEqual();
  5525. this.setDepthWrite(true);
  5526. // Fullscreen
  5527. this._onFullscreenChange = function () {
  5528. if (document.fullscreen !== undefined) {
  5529. _this.isFullscreen = document.fullscreen;
  5530. }
  5531. else if (document.mozFullScreen !== undefined) {
  5532. _this.isFullscreen = document.mozFullScreen;
  5533. }
  5534. else if (document.webkitIsFullScreen !== undefined) {
  5535. _this.isFullscreen = document.webkitIsFullScreen;
  5536. }
  5537. else if (document.msIsFullScreen !== undefined) {
  5538. _this.isFullscreen = document.msIsFullScreen;
  5539. }
  5540. // Pointer lock
  5541. if (_this.isFullscreen && _this._pointerLockRequested) {
  5542. canvas.requestPointerLock = canvas.requestPointerLock ||
  5543. canvas.msRequestPointerLock ||
  5544. canvas.mozRequestPointerLock ||
  5545. canvas.webkitRequestPointerLock;
  5546. if (canvas.requestPointerLock) {
  5547. canvas.requestPointerLock();
  5548. }
  5549. }
  5550. };
  5551. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5552. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5553. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5554. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5555. // Pointer lock
  5556. this._onPointerLockChange = function () {
  5557. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5558. document.webkitPointerLockElement === canvas ||
  5559. document.msPointerLockElement === canvas ||
  5560. document.pointerLockElement === canvas);
  5561. };
  5562. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5563. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5564. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5565. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5566. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5567. Engine.audioEngine = new BABYLON.AudioEngine();
  5568. }
  5569. //default loading screen
  5570. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5571. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5572. }
  5573. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5574. get: function () {
  5575. return Engine._ALPHA_DISABLE;
  5576. },
  5577. enumerable: true,
  5578. configurable: true
  5579. });
  5580. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5581. get: function () {
  5582. return Engine._ALPHA_ONEONE;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(Engine, "ALPHA_ADD", {
  5588. get: function () {
  5589. return Engine._ALPHA_ADD;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5595. get: function () {
  5596. return Engine._ALPHA_COMBINE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5602. get: function () {
  5603. return Engine._ALPHA_SUBTRACT;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5609. get: function () {
  5610. return Engine._ALPHA_MULTIPLY;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5616. get: function () {
  5617. return Engine._ALPHA_MAXIMIZED;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5623. get: function () {
  5624. return Engine._DELAYLOADSTATE_NONE;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5630. get: function () {
  5631. return Engine._DELAYLOADSTATE_LOADED;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5637. get: function () {
  5638. return Engine._DELAYLOADSTATE_LOADING;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5644. get: function () {
  5645. return Engine._DELAYLOADSTATE_NOTLOADED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5651. get: function () {
  5652. return Engine._TEXTUREFORMAT_ALPHA;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5658. get: function () {
  5659. return Engine._TEXTUREFORMAT_LUMINANCE;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5665. get: function () {
  5666. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5672. get: function () {
  5673. return Engine._TEXTUREFORMAT_RGB;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_RGBA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5686. get: function () {
  5687. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5693. get: function () {
  5694. return Engine._TEXTURETYPE_FLOAT;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "Version", {
  5700. get: function () {
  5701. return "2.4.0-alpha";
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5707. get: function () {
  5708. return this._webGLVersion;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Engine.prototype._prepareWorkingCanvas = function () {
  5714. if (this._workingCanvas) {
  5715. return;
  5716. }
  5717. this._workingCanvas = document.createElement("canvas");
  5718. this._workingContext = this._workingCanvas.getContext("2d");
  5719. };
  5720. Engine.prototype.resetTextureCache = function () {
  5721. for (var index = 0; index < this._maxTextureChannels; index++) {
  5722. this._activeTexturesCache[index] = null;
  5723. }
  5724. };
  5725. Engine.prototype.getGlInfo = function () {
  5726. return {
  5727. vendor: this._glVendor,
  5728. renderer: this._glRenderer,
  5729. version: this._glVersion
  5730. };
  5731. };
  5732. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5733. if (useScreen === void 0) { useScreen = false; }
  5734. var viewport = camera.viewport;
  5735. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5736. };
  5737. Engine.prototype.getRenderWidth = function (useScreen) {
  5738. if (useScreen === void 0) { useScreen = false; }
  5739. if (!useScreen && this._currentRenderTarget) {
  5740. return this._currentRenderTarget._width;
  5741. }
  5742. return this._renderingCanvas.width;
  5743. };
  5744. Engine.prototype.getRenderHeight = function (useScreen) {
  5745. if (useScreen === void 0) { useScreen = false; }
  5746. if (!useScreen && this._currentRenderTarget) {
  5747. return this._currentRenderTarget._height;
  5748. }
  5749. return this._renderingCanvas.height;
  5750. };
  5751. Engine.prototype.getRenderingCanvas = function () {
  5752. return this._renderingCanvas;
  5753. };
  5754. Engine.prototype.getRenderingCanvasClientRect = function () {
  5755. return this._renderingCanvas.getBoundingClientRect();
  5756. };
  5757. Engine.prototype.setHardwareScalingLevel = function (level) {
  5758. this._hardwareScalingLevel = level;
  5759. this.resize();
  5760. };
  5761. Engine.prototype.getHardwareScalingLevel = function () {
  5762. return this._hardwareScalingLevel;
  5763. };
  5764. Engine.prototype.getLoadedTexturesCache = function () {
  5765. return this._loadedTexturesCache;
  5766. };
  5767. Engine.prototype.getCaps = function () {
  5768. return this._caps;
  5769. };
  5770. Object.defineProperty(Engine.prototype, "drawCalls", {
  5771. get: function () {
  5772. return this._drawCalls;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. // Methods
  5778. Engine.prototype.resetDrawCalls = function () {
  5779. this._drawCalls = 0;
  5780. };
  5781. Engine.prototype.setDepthFunctionToGreater = function () {
  5782. this._depthCullingState.depthFunc = this._gl.GREATER;
  5783. };
  5784. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5785. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5786. };
  5787. Engine.prototype.setDepthFunctionToLess = function () {
  5788. this._depthCullingState.depthFunc = this._gl.LESS;
  5789. };
  5790. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5791. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5792. };
  5793. /**
  5794. * stop executing a render loop function and remove it from the execution array
  5795. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5796. */
  5797. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5798. if (!renderFunction) {
  5799. this._activeRenderLoops = [];
  5800. return;
  5801. }
  5802. var index = this._activeRenderLoops.indexOf(renderFunction);
  5803. if (index >= 0) {
  5804. this._activeRenderLoops.splice(index, 1);
  5805. }
  5806. };
  5807. Engine.prototype._renderLoop = function () {
  5808. var shouldRender = true;
  5809. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5810. shouldRender = false;
  5811. }
  5812. if (shouldRender) {
  5813. // Start new frame
  5814. this.beginFrame();
  5815. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5816. var renderFunction = this._activeRenderLoops[index];
  5817. renderFunction();
  5818. }
  5819. // Present
  5820. this.endFrame();
  5821. }
  5822. if (this._activeRenderLoops.length > 0) {
  5823. // Register new frame
  5824. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5825. }
  5826. else {
  5827. this._renderingQueueLaunched = false;
  5828. }
  5829. };
  5830. /**
  5831. * Register and execute a render loop. The engine can have more than one render function.
  5832. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5833. * @example
  5834. * engine.runRenderLoop(function () {
  5835. * scene.render()
  5836. * })
  5837. */
  5838. Engine.prototype.runRenderLoop = function (renderFunction) {
  5839. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5840. return;
  5841. }
  5842. this._activeRenderLoops.push(renderFunction);
  5843. if (!this._renderingQueueLaunched) {
  5844. this._renderingQueueLaunched = true;
  5845. this._bindedRenderFunction = this._renderLoop.bind(this);
  5846. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5847. }
  5848. };
  5849. /**
  5850. * Toggle full screen mode.
  5851. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5852. */
  5853. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5854. if (this.isFullscreen) {
  5855. BABYLON.Tools.ExitFullscreen();
  5856. }
  5857. else {
  5858. this._pointerLockRequested = requestPointerLock;
  5859. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5860. }
  5861. };
  5862. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5863. this.applyStates();
  5864. if (backBuffer) {
  5865. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5866. }
  5867. if (depthStencil && this._depthCullingState.depthMask) {
  5868. this._gl.clearDepth(1.0);
  5869. }
  5870. var mode = 0;
  5871. if (backBuffer) {
  5872. mode |= this._gl.COLOR_BUFFER_BIT;
  5873. }
  5874. if (depthStencil && this._depthCullingState.depthMask) {
  5875. mode |= this._gl.DEPTH_BUFFER_BIT;
  5876. }
  5877. this._gl.clear(mode);
  5878. };
  5879. /**
  5880. * Set the WebGL's viewport
  5881. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5882. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5883. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5884. */
  5885. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5886. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5887. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5888. var x = viewport.x || 0;
  5889. var y = viewport.y || 0;
  5890. this._cachedViewport = viewport;
  5891. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5892. };
  5893. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5894. this._cachedViewport = null;
  5895. this._gl.viewport(x, y, width, height);
  5896. };
  5897. Engine.prototype.beginFrame = function () {
  5898. this._measureFps();
  5899. };
  5900. Engine.prototype.endFrame = function () {
  5901. //this.flushFramebuffer();
  5902. };
  5903. /**
  5904. * resize the view according to the canvas' size.
  5905. * @example
  5906. * window.addEventListener("resize", function () {
  5907. * engine.resize();
  5908. * });
  5909. */
  5910. Engine.prototype.resize = function () {
  5911. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5912. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5913. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5914. for (var index = 0; index < this.scenes.length; index++) {
  5915. var scene = this.scenes[index];
  5916. if (scene.debugLayer.isVisible()) {
  5917. scene.debugLayer._syncPositions();
  5918. }
  5919. }
  5920. };
  5921. /**
  5922. * force a specific size of the canvas
  5923. * @param {number} width - the new canvas' width
  5924. * @param {number} height - the new canvas' height
  5925. */
  5926. Engine.prototype.setSize = function (width, height) {
  5927. this._renderingCanvas.width = width;
  5928. this._renderingCanvas.height = height;
  5929. for (var index = 0; index < this.scenes.length; index++) {
  5930. var scene = this.scenes[index];
  5931. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5932. var cam = scene.cameras[camIndex];
  5933. cam._currentRenderId = 0;
  5934. }
  5935. }
  5936. };
  5937. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5938. this._currentRenderTarget = texture;
  5939. var gl = this._gl;
  5940. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5941. if (texture.isCube) {
  5942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5943. }
  5944. else {
  5945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5946. }
  5947. this._gl.viewport(0, 0, texture._width, texture._height);
  5948. this.wipeCaches();
  5949. };
  5950. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5951. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5952. this._currentRenderTarget = null;
  5953. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5954. var gl = this._gl;
  5955. gl.bindTexture(gl.TEXTURE_2D, texture);
  5956. gl.generateMipmap(gl.TEXTURE_2D);
  5957. gl.bindTexture(gl.TEXTURE_2D, null);
  5958. }
  5959. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5960. };
  5961. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5962. if (texture.generateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5966. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5967. }
  5968. };
  5969. Engine.prototype.flushFramebuffer = function () {
  5970. this._gl.flush();
  5971. };
  5972. Engine.prototype.restoreDefaultFramebuffer = function () {
  5973. this._currentRenderTarget = null;
  5974. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5975. this.setViewport(this._cachedViewport);
  5976. this.wipeCaches();
  5977. };
  5978. // VBOs
  5979. Engine.prototype._resetVertexBufferBinding = function () {
  5980. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5981. this._cachedVertexBuffers = null;
  5982. };
  5983. Engine.prototype.createVertexBuffer = function (vertices) {
  5984. var vbo = this._gl.createBuffer();
  5985. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5986. if (vertices instanceof Float32Array) {
  5987. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5988. }
  5989. else {
  5990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5991. }
  5992. this._resetVertexBufferBinding();
  5993. vbo.references = 1;
  5994. return vbo;
  5995. };
  5996. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5997. var vbo = this._gl.createBuffer();
  5998. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5999. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6000. this._resetVertexBufferBinding();
  6001. vbo.references = 1;
  6002. return vbo;
  6003. };
  6004. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6005. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6006. if (offset === undefined) {
  6007. offset = 0;
  6008. }
  6009. if (vertices instanceof Float32Array) {
  6010. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6011. }
  6012. else {
  6013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6014. }
  6015. this._resetVertexBufferBinding();
  6016. };
  6017. Engine.prototype._resetIndexBufferBinding = function () {
  6018. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6019. this._cachedIndexBuffer = null;
  6020. };
  6021. Engine.prototype.createIndexBuffer = function (indices) {
  6022. var vbo = this._gl.createBuffer();
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6024. // Check for 32 bits indices
  6025. var arrayBuffer;
  6026. var need32Bits = false;
  6027. if (this._caps.uintIndices) {
  6028. for (var index = 0; index < indices.length; index++) {
  6029. if (indices[index] > 65535) {
  6030. need32Bits = true;
  6031. break;
  6032. }
  6033. }
  6034. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6035. }
  6036. else {
  6037. arrayBuffer = new Uint16Array(indices);
  6038. }
  6039. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6040. this._resetIndexBufferBinding();
  6041. vbo.references = 1;
  6042. vbo.is32Bits = need32Bits;
  6043. return vbo;
  6044. };
  6045. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6046. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6047. this._cachedVertexBuffers = vertexBuffer;
  6048. this._cachedEffectForVertexBuffers = effect;
  6049. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6050. var offset = 0;
  6051. for (var index = 0; index < vertexDeclaration.length; index++) {
  6052. var order = effect.getAttributeLocation(index);
  6053. if (order >= 0) {
  6054. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6055. }
  6056. offset += vertexDeclaration[index] * 4;
  6057. }
  6058. }
  6059. if (this._cachedIndexBuffer !== indexBuffer) {
  6060. this._cachedIndexBuffer = indexBuffer;
  6061. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6062. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6063. }
  6064. };
  6065. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6066. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6067. this._cachedVertexBuffers = vertexBuffers;
  6068. this._cachedEffectForVertexBuffers = effect;
  6069. var attributes = effect.getAttributesNames();
  6070. for (var index = 0; index < attributes.length; index++) {
  6071. var order = effect.getAttributeLocation(index);
  6072. if (order >= 0) {
  6073. var vertexBuffer = vertexBuffers[attributes[index]];
  6074. if (!vertexBuffer) {
  6075. continue;
  6076. }
  6077. var stride = vertexBuffer.getStrideSize();
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6079. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6080. }
  6081. }
  6082. }
  6083. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6084. this._cachedIndexBuffer = indexBuffer;
  6085. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6086. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6087. }
  6088. };
  6089. Engine.prototype._releaseBuffer = function (buffer) {
  6090. buffer.references--;
  6091. if (buffer.references === 0) {
  6092. this._gl.deleteBuffer(buffer);
  6093. return true;
  6094. }
  6095. return false;
  6096. };
  6097. Engine.prototype.createInstancesBuffer = function (capacity) {
  6098. var buffer = this._gl.createBuffer();
  6099. buffer.capacity = capacity;
  6100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6101. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6102. return buffer;
  6103. };
  6104. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6105. this._gl.deleteBuffer(buffer);
  6106. };
  6107. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6108. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6110. for (var index = 0; index < 4; index++) {
  6111. var offsetLocation = offsetLocations[index];
  6112. this._gl.enableVertexAttribArray(offsetLocation);
  6113. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6114. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6115. }
  6116. };
  6117. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6118. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6119. for (var index = 0; index < 4; index++) {
  6120. var offsetLocation = offsetLocations[index];
  6121. this._gl.disableVertexAttribArray(offsetLocation);
  6122. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6123. }
  6124. };
  6125. Engine.prototype.applyStates = function () {
  6126. this._depthCullingState.apply(this._gl);
  6127. this._alphaState.apply(this._gl);
  6128. };
  6129. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6130. // Apply states
  6131. this.applyStates();
  6132. this._drawCalls++;
  6133. // Render
  6134. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6135. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6136. if (instancesCount) {
  6137. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6138. return;
  6139. }
  6140. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6141. };
  6142. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6143. // Apply states
  6144. this.applyStates();
  6145. this._drawCalls++;
  6146. if (instancesCount) {
  6147. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6148. return;
  6149. }
  6150. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6151. };
  6152. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6153. // Apply states
  6154. this.applyStates();
  6155. this._drawCalls++;
  6156. if (instancesCount) {
  6157. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6158. return;
  6159. }
  6160. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6161. };
  6162. // Shaders
  6163. Engine.prototype._releaseEffect = function (effect) {
  6164. if (this._compiledEffects[effect._key]) {
  6165. delete this._compiledEffects[effect._key];
  6166. if (effect.getProgram()) {
  6167. this._gl.deleteProgram(effect.getProgram());
  6168. }
  6169. }
  6170. };
  6171. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6172. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6173. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6174. var name = vertex + "+" + fragment + "@" + defines;
  6175. if (this._compiledEffects[name]) {
  6176. return this._compiledEffects[name];
  6177. }
  6178. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6179. effect._key = name;
  6180. this._compiledEffects[name] = effect;
  6181. return effect;
  6182. };
  6183. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6184. if (uniformsNames === void 0) { uniformsNames = []; }
  6185. if (samplers === void 0) { samplers = []; }
  6186. if (defines === void 0) { defines = ""; }
  6187. return this.createEffect({
  6188. vertex: "particles",
  6189. fragmentElement: fragmentName
  6190. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6191. };
  6192. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6193. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6194. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6195. var shaderProgram = this._gl.createProgram();
  6196. this._gl.attachShader(shaderProgram, vertexShader);
  6197. this._gl.attachShader(shaderProgram, fragmentShader);
  6198. this._gl.linkProgram(shaderProgram);
  6199. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6200. if (!linked) {
  6201. var error = this._gl.getProgramInfoLog(shaderProgram);
  6202. if (error) {
  6203. throw new Error(error);
  6204. }
  6205. }
  6206. this._gl.deleteShader(vertexShader);
  6207. this._gl.deleteShader(fragmentShader);
  6208. return shaderProgram;
  6209. };
  6210. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6211. var results = [];
  6212. for (var index = 0; index < uniformsNames.length; index++) {
  6213. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6214. }
  6215. return results;
  6216. };
  6217. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6218. var results = [];
  6219. for (var index = 0; index < attributesNames.length; index++) {
  6220. try {
  6221. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6222. }
  6223. catch (e) {
  6224. results.push(-1);
  6225. }
  6226. }
  6227. return results;
  6228. };
  6229. Engine.prototype.enableEffect = function (effect) {
  6230. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6231. if (effect && effect.onBind) {
  6232. effect.onBind(effect);
  6233. }
  6234. return;
  6235. }
  6236. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6237. // Use program
  6238. this._gl.useProgram(effect.getProgram());
  6239. for (var i in this._vertexAttribArrays) {
  6240. //make sure this is a number)
  6241. var iAsNumber = +i;
  6242. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6243. continue;
  6244. }
  6245. this._vertexAttribArrays[iAsNumber] = false;
  6246. this._gl.disableVertexAttribArray(iAsNumber);
  6247. }
  6248. var attributesCount = effect.getAttributesCount();
  6249. for (var index = 0; index < attributesCount; index++) {
  6250. // Attributes
  6251. var order = effect.getAttributeLocation(index);
  6252. if (order >= 0) {
  6253. this._vertexAttribArrays[order] = true;
  6254. this._gl.enableVertexAttribArray(order);
  6255. }
  6256. }
  6257. this._currentEffect = effect;
  6258. if (effect.onBind) {
  6259. effect.onBind(effect);
  6260. }
  6261. };
  6262. Engine.prototype.setArray = function (uniform, array) {
  6263. if (!uniform)
  6264. return;
  6265. this._gl.uniform1fv(uniform, array);
  6266. };
  6267. Engine.prototype.setArray2 = function (uniform, array) {
  6268. if (!uniform || array.length % 2 !== 0)
  6269. return;
  6270. this._gl.uniform2fv(uniform, array);
  6271. };
  6272. Engine.prototype.setArray3 = function (uniform, array) {
  6273. if (!uniform || array.length % 3 !== 0)
  6274. return;
  6275. this._gl.uniform3fv(uniform, array);
  6276. };
  6277. Engine.prototype.setArray4 = function (uniform, array) {
  6278. if (!uniform || array.length % 4 !== 0)
  6279. return;
  6280. this._gl.uniform4fv(uniform, array);
  6281. };
  6282. Engine.prototype.setMatrices = function (uniform, matrices) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6286. };
  6287. Engine.prototype.setMatrix = function (uniform, matrix) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6291. };
  6292. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6296. };
  6297. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6301. };
  6302. Engine.prototype.setFloat = function (uniform, value) {
  6303. if (!uniform)
  6304. return;
  6305. this._gl.uniform1f(uniform, value);
  6306. };
  6307. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6308. if (!uniform)
  6309. return;
  6310. this._gl.uniform2f(uniform, x, y);
  6311. };
  6312. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6313. if (!uniform)
  6314. return;
  6315. this._gl.uniform3f(uniform, x, y, z);
  6316. };
  6317. Engine.prototype.setBool = function (uniform, bool) {
  6318. if (!uniform)
  6319. return;
  6320. this._gl.uniform1i(uniform, bool);
  6321. };
  6322. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6323. if (!uniform)
  6324. return;
  6325. this._gl.uniform4f(uniform, x, y, z, w);
  6326. };
  6327. Engine.prototype.setColor3 = function (uniform, color3) {
  6328. if (!uniform)
  6329. return;
  6330. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6331. };
  6332. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6333. if (!uniform)
  6334. return;
  6335. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6336. };
  6337. // States
  6338. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6339. if (zOffset === void 0) { zOffset = 0; }
  6340. if (reverseSide === void 0) { reverseSide = false; }
  6341. // Culling
  6342. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6343. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6344. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6345. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6346. if (culling) {
  6347. this._depthCullingState.cullFace = cullFace;
  6348. this._depthCullingState.cull = true;
  6349. }
  6350. else {
  6351. this._depthCullingState.cull = false;
  6352. }
  6353. }
  6354. // Z offset
  6355. this._depthCullingState.zOffset = zOffset;
  6356. };
  6357. Engine.prototype.setDepthBuffer = function (enable) {
  6358. this._depthCullingState.depthTest = enable;
  6359. };
  6360. Engine.prototype.getDepthWrite = function () {
  6361. return this._depthCullingState.depthMask;
  6362. };
  6363. Engine.prototype.setDepthWrite = function (enable) {
  6364. this._depthCullingState.depthMask = enable;
  6365. };
  6366. Engine.prototype.setColorWrite = function (enable) {
  6367. this._gl.colorMask(enable, enable, enable, enable);
  6368. };
  6369. Engine.prototype.setAlphaMode = function (mode) {
  6370. if (this._alphaMode === mode) {
  6371. return;
  6372. }
  6373. switch (mode) {
  6374. case Engine.ALPHA_DISABLE:
  6375. this.setDepthWrite(true);
  6376. this._alphaState.alphaBlend = false;
  6377. break;
  6378. case Engine.ALPHA_COMBINE:
  6379. this.setDepthWrite(false);
  6380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6381. this._alphaState.alphaBlend = true;
  6382. break;
  6383. case Engine.ALPHA_ONEONE:
  6384. this.setDepthWrite(false);
  6385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6386. this._alphaState.alphaBlend = true;
  6387. break;
  6388. case Engine.ALPHA_ADD:
  6389. this.setDepthWrite(false);
  6390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6391. this._alphaState.alphaBlend = true;
  6392. break;
  6393. case Engine.ALPHA_SUBTRACT:
  6394. this.setDepthWrite(false);
  6395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6396. this._alphaState.alphaBlend = true;
  6397. break;
  6398. case Engine.ALPHA_MULTIPLY:
  6399. this.setDepthWrite(false);
  6400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6401. this._alphaState.alphaBlend = true;
  6402. break;
  6403. case Engine.ALPHA_MAXIMIZED:
  6404. this.setDepthWrite(false);
  6405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6406. this._alphaState.alphaBlend = true;
  6407. break;
  6408. }
  6409. this._alphaMode = mode;
  6410. };
  6411. Engine.prototype.getAlphaMode = function () {
  6412. return this._alphaMode;
  6413. };
  6414. Engine.prototype.setAlphaTesting = function (enable) {
  6415. this._alphaTest = enable;
  6416. };
  6417. Engine.prototype.getAlphaTesting = function () {
  6418. return this._alphaTest;
  6419. };
  6420. // Textures
  6421. Engine.prototype.wipeCaches = function () {
  6422. this.resetTextureCache();
  6423. this._currentEffect = null;
  6424. this._depthCullingState.reset();
  6425. this._alphaState.reset();
  6426. this._cachedVertexBuffers = null;
  6427. this._cachedIndexBuffer = null;
  6428. this._cachedEffectForVertexBuffers = null;
  6429. };
  6430. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6431. var gl = this._gl;
  6432. gl.bindTexture(gl.TEXTURE_2D, texture);
  6433. var magFilter = gl.NEAREST;
  6434. var minFilter = gl.NEAREST;
  6435. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6436. magFilter = gl.LINEAR;
  6437. minFilter = gl.LINEAR;
  6438. }
  6439. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6440. magFilter = gl.LINEAR;
  6441. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6442. }
  6443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6445. gl.bindTexture(gl.TEXTURE_2D, null);
  6446. texture.samplingMode = samplingMode;
  6447. };
  6448. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6449. var _this = this;
  6450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6451. if (onLoad === void 0) { onLoad = null; }
  6452. if (onError === void 0) { onError = null; }
  6453. if (buffer === void 0) { buffer = null; }
  6454. var texture = this._gl.createTexture();
  6455. var extension;
  6456. var fromData = false;
  6457. if (url.substr(0, 5) === "data:") {
  6458. fromData = true;
  6459. }
  6460. if (!fromData)
  6461. extension = url.substr(url.length - 4, 4).toLowerCase();
  6462. else {
  6463. var oldUrl = url;
  6464. fromData = oldUrl.split(':');
  6465. url = oldUrl;
  6466. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6467. }
  6468. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6469. var isTGA = (extension === ".tga");
  6470. scene._addPendingData(texture);
  6471. texture.url = url;
  6472. texture.noMipmap = noMipmap;
  6473. texture.references = 1;
  6474. texture.samplingMode = samplingMode;
  6475. this._loadedTexturesCache.push(texture);
  6476. var onerror = function () {
  6477. scene._removePendingData(texture);
  6478. if (onError) {
  6479. onError();
  6480. }
  6481. };
  6482. var callback;
  6483. if (isTGA) {
  6484. callback = function (arrayBuffer) {
  6485. var data = new Uint8Array(arrayBuffer);
  6486. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6487. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6488. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6489. }, onLoad, samplingMode);
  6490. };
  6491. if (!(fromData instanceof Array))
  6492. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6493. callback(arrayBuffer);
  6494. }, onerror, scene.database, true);
  6495. else
  6496. callback(buffer);
  6497. }
  6498. else if (isDDS) {
  6499. callback = function (data) {
  6500. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6501. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6502. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6503. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6504. }, onLoad, samplingMode);
  6505. };
  6506. if (!(fromData instanceof Array))
  6507. BABYLON.Tools.LoadFile(url, function (data) {
  6508. callback(data);
  6509. }, onerror, scene.database, true);
  6510. else
  6511. callback(buffer);
  6512. }
  6513. else {
  6514. var onload = function (img) {
  6515. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6516. var isPot = (img.width === potWidth && img.height === potHeight);
  6517. if (!isPot) {
  6518. _this._prepareWorkingCanvas();
  6519. _this._workingCanvas.width = potWidth;
  6520. _this._workingCanvas.height = potHeight;
  6521. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6522. _this._workingContext.imageSmoothingEnabled = false;
  6523. _this._workingContext.mozImageSmoothingEnabled = false;
  6524. _this._workingContext.oImageSmoothingEnabled = false;
  6525. _this._workingContext.webkitImageSmoothingEnabled = false;
  6526. _this._workingContext.msImageSmoothingEnabled = false;
  6527. }
  6528. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6529. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6530. _this._workingContext.imageSmoothingEnabled = true;
  6531. _this._workingContext.mozImageSmoothingEnabled = true;
  6532. _this._workingContext.oImageSmoothingEnabled = true;
  6533. _this._workingContext.webkitImageSmoothingEnabled = true;
  6534. _this._workingContext.msImageSmoothingEnabled = true;
  6535. }
  6536. }
  6537. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6538. }, onLoad, samplingMode);
  6539. };
  6540. if (!(fromData instanceof Array))
  6541. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6542. else
  6543. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype._getInternalFormat = function (format) {
  6548. var internalFormat = this._gl.RGBA;
  6549. switch (format) {
  6550. case Engine.TEXTUREFORMAT_ALPHA:
  6551. internalFormat = this._gl.ALPHA;
  6552. break;
  6553. case Engine.TEXTUREFORMAT_LUMINANCE:
  6554. internalFormat = this._gl.LUMINANCE;
  6555. break;
  6556. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6557. internalFormat = this._gl.LUMINANCE_ALPHA;
  6558. break;
  6559. case Engine.TEXTUREFORMAT_RGB:
  6560. internalFormat = this._gl.RGB;
  6561. break;
  6562. case Engine.TEXTUREFORMAT_RGBA:
  6563. internalFormat = this._gl.RGBA;
  6564. break;
  6565. }
  6566. return internalFormat;
  6567. };
  6568. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6569. if (compression === void 0) { compression = null; }
  6570. var internalFormat = this._getInternalFormat(format);
  6571. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6572. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6573. if (compression) {
  6574. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6575. }
  6576. else {
  6577. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6578. }
  6579. if (texture.generateMipMaps) {
  6580. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6581. }
  6582. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6583. this.resetTextureCache();
  6584. texture.isReady = true;
  6585. };
  6586. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6587. if (compression === void 0) { compression = null; }
  6588. var texture = this._gl.createTexture();
  6589. texture._baseWidth = width;
  6590. texture._baseHeight = height;
  6591. texture._width = width;
  6592. texture._height = height;
  6593. texture.references = 1;
  6594. this.updateRawTexture(texture, data, format, invertY, compression);
  6595. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6596. // Filters
  6597. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6601. texture.samplingMode = samplingMode;
  6602. this._loadedTexturesCache.push(texture);
  6603. return texture;
  6604. };
  6605. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6606. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6607. var texture = this._gl.createTexture();
  6608. texture._baseWidth = width;
  6609. texture._baseHeight = height;
  6610. if (forceExponantOfTwo) {
  6611. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6612. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6613. }
  6614. this.resetTextureCache();
  6615. texture._width = width;
  6616. texture._height = height;
  6617. texture.isReady = false;
  6618. texture.generateMipMaps = generateMipMaps;
  6619. texture.references = 1;
  6620. texture.samplingMode = samplingMode;
  6621. this.updateTextureSamplingMode(samplingMode, texture);
  6622. this._loadedTexturesCache.push(texture);
  6623. return texture;
  6624. };
  6625. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6626. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6627. if (texture.isCube) {
  6628. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6629. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6630. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6631. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6632. }
  6633. else {
  6634. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6637. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6638. }
  6639. };
  6640. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6641. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6642. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6643. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6644. if (texture.generateMipMaps) {
  6645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6646. }
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6648. this.resetTextureCache();
  6649. texture.isReady = true;
  6650. };
  6651. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6652. if (texture._isDisabled) {
  6653. return;
  6654. }
  6655. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6656. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6657. try {
  6658. // Testing video texture support
  6659. if (this._videoTextureSupported === undefined) {
  6660. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6661. if (this._gl.getError() !== 0) {
  6662. this._videoTextureSupported = false;
  6663. }
  6664. else {
  6665. this._videoTextureSupported = true;
  6666. }
  6667. }
  6668. // Copy video through the current working canvas if video texture is not supported
  6669. if (!this._videoTextureSupported) {
  6670. if (!texture._workingCanvas) {
  6671. texture._workingCanvas = document.createElement("canvas");
  6672. texture._workingContext = texture._workingCanvas.getContext("2d");
  6673. texture._workingCanvas.width = texture._width;
  6674. texture._workingCanvas.height = texture._height;
  6675. }
  6676. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6677. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6678. }
  6679. else {
  6680. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6681. }
  6682. if (texture.generateMipMaps) {
  6683. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6684. }
  6685. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6686. this.resetTextureCache();
  6687. texture.isReady = true;
  6688. }
  6689. catch (ex) {
  6690. // Something unexpected
  6691. // Let's disable the texture
  6692. texture._isDisabled = true;
  6693. }
  6694. };
  6695. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6696. // old version had a "generateMipMaps" arg instead of options.
  6697. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6698. // in the same way, generateDepthBuffer is defaulted to true
  6699. var generateMipMaps = false;
  6700. var generateDepthBuffer = true;
  6701. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6702. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6703. if (options !== undefined) {
  6704. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6705. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6706. type = options.type === undefined ? type : options.type;
  6707. if (options.samplingMode !== undefined) {
  6708. samplingMode = options.samplingMode;
  6709. }
  6710. if (type === Engine.TEXTURETYPE_FLOAT) {
  6711. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6712. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6713. }
  6714. }
  6715. var gl = this._gl;
  6716. var texture = gl.createTexture();
  6717. gl.bindTexture(gl.TEXTURE_2D, texture);
  6718. var width = size.width || size;
  6719. var height = size.height || size;
  6720. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6721. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6722. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6723. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6724. }
  6725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6728. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6729. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6730. var depthBuffer;
  6731. // Create the depth buffer
  6732. if (generateDepthBuffer) {
  6733. depthBuffer = gl.createRenderbuffer();
  6734. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6735. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6736. }
  6737. // Create the framebuffer
  6738. var framebuffer = gl.createFramebuffer();
  6739. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6740. if (generateDepthBuffer) {
  6741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6742. }
  6743. if (generateMipMaps) {
  6744. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6745. }
  6746. // Unbind
  6747. gl.bindTexture(gl.TEXTURE_2D, null);
  6748. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6749. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6750. texture._framebuffer = framebuffer;
  6751. if (generateDepthBuffer) {
  6752. texture._depthBuffer = depthBuffer;
  6753. }
  6754. texture._width = width;
  6755. texture._height = height;
  6756. texture.isReady = true;
  6757. texture.generateMipMaps = generateMipMaps;
  6758. texture.references = 1;
  6759. texture.samplingMode = samplingMode;
  6760. this.resetTextureCache();
  6761. this._loadedTexturesCache.push(texture);
  6762. return texture;
  6763. };
  6764. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6765. var gl = this._gl;
  6766. var texture = gl.createTexture();
  6767. var generateMipMaps = true;
  6768. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6769. if (options !== undefined) {
  6770. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6771. if (options.samplingMode !== undefined) {
  6772. samplingMode = options.samplingMode;
  6773. }
  6774. }
  6775. texture.isCube = true;
  6776. texture.references = 1;
  6777. texture.generateMipMaps = generateMipMaps;
  6778. texture.references = 1;
  6779. texture.samplingMode = samplingMode;
  6780. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6781. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6782. for (var face = 0; face < 6; face++) {
  6783. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6784. }
  6785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6789. // Create the depth buffer
  6790. var depthBuffer = gl.createRenderbuffer();
  6791. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6792. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6793. // Create the framebuffer
  6794. var framebuffer = gl.createFramebuffer();
  6795. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6796. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6797. // Mipmaps
  6798. if (texture.generateMipMaps) {
  6799. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6800. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6801. }
  6802. // Unbind
  6803. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6804. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6805. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6806. texture._framebuffer = framebuffer;
  6807. texture._depthBuffer = depthBuffer;
  6808. this.resetTextureCache();
  6809. texture._width = size;
  6810. texture._height = size;
  6811. texture.isReady = true;
  6812. return texture;
  6813. };
  6814. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6815. var _this = this;
  6816. var gl = this._gl;
  6817. var texture = gl.createTexture();
  6818. texture.isCube = true;
  6819. texture.url = rootUrl;
  6820. texture.references = 1;
  6821. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6822. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6823. if (isDDS) {
  6824. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6825. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6826. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6827. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6829. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6830. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6831. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6832. }
  6833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6837. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6838. _this.resetTextureCache();
  6839. texture._width = info.width;
  6840. texture._height = info.height;
  6841. texture.isReady = true;
  6842. }, null, null, true);
  6843. }
  6844. else {
  6845. cascadeLoad(rootUrl, scene, function (imgs) {
  6846. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6847. var height = width;
  6848. _this._prepareWorkingCanvas();
  6849. _this._workingCanvas.width = width;
  6850. _this._workingCanvas.height = height;
  6851. var faces = [
  6852. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6853. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6854. ];
  6855. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6856. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6857. for (var index = 0; index < faces.length; index++) {
  6858. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6859. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6860. }
  6861. if (!noMipmap) {
  6862. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6863. }
  6864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6868. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6869. _this.resetTextureCache();
  6870. texture._width = width;
  6871. texture._height = height;
  6872. texture.isReady = true;
  6873. }, files);
  6874. }
  6875. return texture;
  6876. };
  6877. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6878. var _this = this;
  6879. var gl = this._gl;
  6880. var texture = gl.createTexture();
  6881. scene._addPendingData(texture);
  6882. texture.isCube = true;
  6883. texture.references = 1;
  6884. texture.url = url;
  6885. var internalFormat = this._getInternalFormat(format);
  6886. var textureType = gl.UNSIGNED_BYTE;
  6887. if (type === Engine.TEXTURETYPE_FLOAT) {
  6888. textureType = gl.FLOAT;
  6889. }
  6890. var width = size;
  6891. var height = width;
  6892. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6893. texture._width = width;
  6894. texture._height = height;
  6895. var onerror = function () {
  6896. scene._removePendingData(texture);
  6897. };
  6898. var internalCallback = function (data) {
  6899. var rgbeDataArrays = callback(data);
  6900. var facesIndex = [
  6901. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6902. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6903. ];
  6904. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6905. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6906. for (var index = 0; index < facesIndex.length; index++) {
  6907. var faceData = rgbeDataArrays[index];
  6908. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6909. }
  6910. if (!noMipmap && isPot) {
  6911. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6912. }
  6913. else {
  6914. noMipmap = true;
  6915. }
  6916. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6919. }
  6920. else {
  6921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6923. }
  6924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6926. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6927. texture.isReady = true;
  6928. _this.resetTextureCache();
  6929. scene._removePendingData(texture);
  6930. };
  6931. BABYLON.Tools.LoadFile(url, function (data) {
  6932. internalCallback(data);
  6933. }, onerror, scene.database, true);
  6934. return texture;
  6935. };
  6936. ;
  6937. Engine.prototype._releaseTexture = function (texture) {
  6938. var gl = this._gl;
  6939. if (texture._framebuffer) {
  6940. gl.deleteFramebuffer(texture._framebuffer);
  6941. }
  6942. if (texture._depthBuffer) {
  6943. gl.deleteRenderbuffer(texture._depthBuffer);
  6944. }
  6945. gl.deleteTexture(texture);
  6946. // Unbind channels
  6947. this.unbindAllTextures();
  6948. var index = this._loadedTexturesCache.indexOf(texture);
  6949. if (index !== -1) {
  6950. this._loadedTexturesCache.splice(index, 1);
  6951. }
  6952. };
  6953. Engine.prototype.bindSamplers = function (effect) {
  6954. this._gl.useProgram(effect.getProgram());
  6955. var samplers = effect.getSamplers();
  6956. for (var index = 0; index < samplers.length; index++) {
  6957. var uniform = effect.getUniform(samplers[index]);
  6958. this._gl.uniform1i(uniform, index);
  6959. }
  6960. this._currentEffect = null;
  6961. };
  6962. Engine.prototype._bindTexture = function (channel, texture) {
  6963. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6964. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6965. this._activeTexturesCache[channel] = null;
  6966. };
  6967. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6968. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6969. };
  6970. Engine.prototype.unbindAllTextures = function () {
  6971. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6972. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6973. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6974. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6975. this._activeTexturesCache[channel] = null;
  6976. }
  6977. };
  6978. Engine.prototype.setTexture = function (channel, texture) {
  6979. if (channel < 0) {
  6980. return;
  6981. }
  6982. // Not ready?
  6983. if (!texture || !texture.isReady()) {
  6984. if (this._activeTexturesCache[channel] != null) {
  6985. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6986. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6987. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6988. this._activeTexturesCache[channel] = null;
  6989. }
  6990. return;
  6991. }
  6992. // Video
  6993. var alreadyActivated = false;
  6994. if (texture instanceof BABYLON.VideoTexture) {
  6995. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6996. alreadyActivated = true;
  6997. texture.update();
  6998. }
  6999. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7000. texture.delayLoad();
  7001. return;
  7002. }
  7003. if (this._activeTexturesCache[channel] === texture) {
  7004. return;
  7005. }
  7006. this._activeTexturesCache[channel] = texture;
  7007. var internalTexture = texture.getInternalTexture();
  7008. if (!alreadyActivated) {
  7009. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7010. }
  7011. if (internalTexture.isCube) {
  7012. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7013. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7014. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7015. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7016. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7017. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7018. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7019. }
  7020. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7021. }
  7022. else {
  7023. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7024. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7025. internalTexture._cachedWrapU = texture.wrapU;
  7026. switch (texture.wrapU) {
  7027. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7029. break;
  7030. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7032. break;
  7033. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7034. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7035. break;
  7036. }
  7037. }
  7038. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7039. internalTexture._cachedWrapV = texture.wrapV;
  7040. switch (texture.wrapV) {
  7041. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7042. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7043. break;
  7044. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7045. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7046. break;
  7047. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7049. break;
  7050. }
  7051. }
  7052. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7053. }
  7054. };
  7055. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7056. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7057. var value = texture.anisotropicFilteringLevel;
  7058. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7059. value = 1;
  7060. }
  7061. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7062. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7063. texture._cachedAnisotropicFilteringLevel = value;
  7064. }
  7065. };
  7066. Engine.prototype.readPixels = function (x, y, width, height) {
  7067. var data = new Uint8Array(height * width * 4);
  7068. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7069. return data;
  7070. };
  7071. Engine.prototype.releaseInternalTexture = function (texture) {
  7072. if (!texture) {
  7073. return;
  7074. }
  7075. texture.references--;
  7076. // Final reference ?
  7077. if (texture.references === 0) {
  7078. var texturesCache = this.getLoadedTexturesCache();
  7079. var index = texturesCache.indexOf(texture);
  7080. if (index > -1) {
  7081. texturesCache.splice(index, 1);
  7082. }
  7083. this._releaseTexture(texture);
  7084. }
  7085. };
  7086. // Dispose
  7087. Engine.prototype.dispose = function () {
  7088. this.hideLoadingUI();
  7089. this.stopRenderLoop();
  7090. // Release scenes
  7091. while (this.scenes.length) {
  7092. this.scenes[0].dispose();
  7093. }
  7094. // Release audio engine
  7095. Engine.audioEngine.dispose();
  7096. // Release effects
  7097. for (var name in this._compiledEffects) {
  7098. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7099. }
  7100. // Unbind
  7101. for (var i in this._vertexAttribArrays) {
  7102. //making sure this is a string
  7103. var iAsNumber = +i;
  7104. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7105. continue;
  7106. }
  7107. this._gl.disableVertexAttribArray(iAsNumber);
  7108. }
  7109. this._gl = null;
  7110. // Events
  7111. window.removeEventListener("blur", this._onBlur);
  7112. window.removeEventListener("focus", this._onFocus);
  7113. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7114. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7115. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7116. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7117. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7118. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7119. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7120. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7121. };
  7122. // Loading screen
  7123. Engine.prototype.displayLoadingUI = function () {
  7124. this._loadingScreen.displayLoadingUI();
  7125. };
  7126. Engine.prototype.hideLoadingUI = function () {
  7127. this._loadingScreen.hideLoadingUI();
  7128. };
  7129. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7130. get: function () {
  7131. return this._loadingScreen;
  7132. },
  7133. set: function (loadingScreen) {
  7134. this._loadingScreen = loadingScreen;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7140. set: function (text) {
  7141. this._loadingScreen.loadingUIText = text;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7147. set: function (color) {
  7148. this._loadingScreen.loadingUIBackgroundColor = color;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. // FPS
  7154. Engine.prototype.getFps = function () {
  7155. return this.fps;
  7156. };
  7157. Engine.prototype.getDeltaTime = function () {
  7158. return this.deltaTime;
  7159. };
  7160. Engine.prototype._measureFps = function () {
  7161. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7162. var length = this.previousFramesDuration.length;
  7163. if (length >= 2) {
  7164. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7165. }
  7166. if (length >= this.fpsRange) {
  7167. if (length > this.fpsRange) {
  7168. this.previousFramesDuration.splice(0, 1);
  7169. length = this.previousFramesDuration.length;
  7170. }
  7171. var sum = 0;
  7172. for (var id = 0; id < length - 1; id++) {
  7173. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7174. }
  7175. this.fps = 1000.0 / (sum / (length - 1));
  7176. }
  7177. };
  7178. // Statics
  7179. Engine.isSupported = function () {
  7180. try {
  7181. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7182. if (navigator.isCocoonJS) {
  7183. return true;
  7184. }
  7185. var tempcanvas = document.createElement("canvas");
  7186. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7187. return gl != null && !!window.WebGLRenderingContext;
  7188. }
  7189. catch (e) {
  7190. return false;
  7191. }
  7192. };
  7193. // Const statics
  7194. Engine._ALPHA_DISABLE = 0;
  7195. Engine._ALPHA_ADD = 1;
  7196. Engine._ALPHA_COMBINE = 2;
  7197. Engine._ALPHA_SUBTRACT = 3;
  7198. Engine._ALPHA_MULTIPLY = 4;
  7199. Engine._ALPHA_MAXIMIZED = 5;
  7200. Engine._ALPHA_ONEONE = 6;
  7201. Engine._DELAYLOADSTATE_NONE = 0;
  7202. Engine._DELAYLOADSTATE_LOADED = 1;
  7203. Engine._DELAYLOADSTATE_LOADING = 2;
  7204. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7205. Engine._TEXTUREFORMAT_ALPHA = 0;
  7206. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7207. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7208. Engine._TEXTUREFORMAT_RGB = 4;
  7209. Engine._TEXTUREFORMAT_RGBA = 5;
  7210. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7211. Engine._TEXTURETYPE_FLOAT = 1;
  7212. // Updatable statics so stick with vars here
  7213. Engine.Epsilon = 0.001;
  7214. Engine.CollisionsEpsilon = 0.001;
  7215. Engine.CodeRepository = "src/";
  7216. Engine.ShadersRepository = "src/Shaders/";
  7217. return Engine;
  7218. })();
  7219. BABYLON.Engine = Engine;
  7220. })(BABYLON || (BABYLON = {}));
  7221. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7222. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7223. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7224. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7225. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7226. };
  7227. var BABYLON;
  7228. (function (BABYLON) {
  7229. /**
  7230. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7231. */
  7232. var Node = (function () {
  7233. /**
  7234. * @constructor
  7235. * @param {string} name - the name and id to be given to this node
  7236. * @param {BABYLON.Scene} the scene this node will be added to
  7237. */
  7238. function Node(name, scene) {
  7239. this.state = "";
  7240. this.animations = new Array();
  7241. this._ranges = {};
  7242. this._childrenFlag = -1;
  7243. this._isEnabled = true;
  7244. this._isReady = true;
  7245. this._currentRenderId = -1;
  7246. this._parentRenderId = -1;
  7247. this.name = name;
  7248. this.id = name;
  7249. this._scene = scene;
  7250. this._initCache();
  7251. }
  7252. Node.prototype.getScene = function () {
  7253. return this._scene;
  7254. };
  7255. Node.prototype.getEngine = function () {
  7256. return this._scene.getEngine();
  7257. };
  7258. // override it in derived class
  7259. Node.prototype.getWorldMatrix = function () {
  7260. return BABYLON.Matrix.Identity();
  7261. };
  7262. // override it in derived class if you add new variables to the cache
  7263. // and call the parent class method
  7264. Node.prototype._initCache = function () {
  7265. this._cache = {};
  7266. this._cache.parent = undefined;
  7267. };
  7268. Node.prototype.updateCache = function (force) {
  7269. if (!force && this.isSynchronized())
  7270. return;
  7271. this._cache.parent = this.parent;
  7272. this._updateCache();
  7273. };
  7274. // override it in derived class if you add new variables to the cache
  7275. // and call the parent class method if !ignoreParentClass
  7276. Node.prototype._updateCache = function (ignoreParentClass) {
  7277. };
  7278. // override it in derived class if you add new variables to the cache
  7279. Node.prototype._isSynchronized = function () {
  7280. return true;
  7281. };
  7282. Node.prototype._markSyncedWithParent = function () {
  7283. this._parentRenderId = this.parent._currentRenderId;
  7284. };
  7285. Node.prototype.isSynchronizedWithParent = function () {
  7286. if (!this.parent) {
  7287. return true;
  7288. }
  7289. if (this._parentRenderId !== this.parent._currentRenderId) {
  7290. return false;
  7291. }
  7292. return this.parent.isSynchronized();
  7293. };
  7294. Node.prototype.isSynchronized = function (updateCache) {
  7295. var check = this.hasNewParent();
  7296. check = check || !this.isSynchronizedWithParent();
  7297. check = check || !this._isSynchronized();
  7298. if (updateCache)
  7299. this.updateCache(true);
  7300. return !check;
  7301. };
  7302. Node.prototype.hasNewParent = function (update) {
  7303. if (this._cache.parent === this.parent)
  7304. return false;
  7305. if (update)
  7306. this._cache.parent = this.parent;
  7307. return true;
  7308. };
  7309. /**
  7310. * Is this node ready to be used/rendered
  7311. * @return {boolean} is it ready
  7312. */
  7313. Node.prototype.isReady = function () {
  7314. return this._isReady;
  7315. };
  7316. /**
  7317. * Is this node enabled.
  7318. * If the node has a parent and is enabled, the parent will be inspected as well.
  7319. * @return {boolean} whether this node (and its parent) is enabled.
  7320. * @see setEnabled
  7321. */
  7322. Node.prototype.isEnabled = function () {
  7323. if (!this._isEnabled) {
  7324. return false;
  7325. }
  7326. if (this.parent) {
  7327. return this.parent.isEnabled();
  7328. }
  7329. return true;
  7330. };
  7331. /**
  7332. * Set the enabled state of this node.
  7333. * @param {boolean} value - the new enabled state
  7334. * @see isEnabled
  7335. */
  7336. Node.prototype.setEnabled = function (value) {
  7337. this._isEnabled = value;
  7338. };
  7339. /**
  7340. * Is this node a descendant of the given node.
  7341. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7342. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7343. * @see parent
  7344. */
  7345. Node.prototype.isDescendantOf = function (ancestor) {
  7346. if (this.parent) {
  7347. if (this.parent === ancestor) {
  7348. return true;
  7349. }
  7350. return this.parent.isDescendantOf(ancestor);
  7351. }
  7352. return false;
  7353. };
  7354. Node.prototype._getDescendants = function (list, results, directDecendantsOnly) {
  7355. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7356. for (var index = 0; index < list.length; index++) {
  7357. var item = list[index];
  7358. if ((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) {
  7359. results.push(item);
  7360. }
  7361. }
  7362. };
  7363. /**
  7364. * Will return all nodes that have this node as parent.
  7365. * @return {BABYLON.Node[]} all children nodes of all types.
  7366. */
  7367. Node.prototype.getDescendants = function (directDecendantsOnly) {
  7368. var results = [];
  7369. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7370. this._getDescendants(this._scene.lights, results, directDecendantsOnly);
  7371. this._getDescendants(this._scene.cameras, results, directDecendantsOnly);
  7372. return results;
  7373. };
  7374. /**
  7375. * @Deprecated, legacy support.
  7376. * use getDecendants instead.
  7377. */
  7378. Node.prototype.getChildren = function () {
  7379. return this.getDescendants(true);
  7380. };
  7381. /**
  7382. * Get all child-meshes of this node.
  7383. */
  7384. Node.prototype.getChildMeshes = function (directDecendantsOnly) {
  7385. var results = [];
  7386. this._getDescendants(this._scene.meshes, results, false);
  7387. return results;
  7388. };
  7389. Node.prototype._setReady = function (state) {
  7390. if (state === this._isReady) {
  7391. return;
  7392. }
  7393. if (!state) {
  7394. this._isReady = false;
  7395. return;
  7396. }
  7397. this._isReady = true;
  7398. if (this.onReady) {
  7399. this.onReady(this);
  7400. }
  7401. };
  7402. Node.prototype.getAnimationByName = function (name) {
  7403. for (var i = 0; i < this.animations.length; i++) {
  7404. var animation = this.animations[i];
  7405. if (animation.name === name) {
  7406. return animation;
  7407. }
  7408. }
  7409. return null;
  7410. };
  7411. Node.prototype.createAnimationRange = function (name, from, to) {
  7412. // check name not already in use
  7413. if (!this._ranges[name]) {
  7414. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7415. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7416. if (this.animations[i]) {
  7417. this.animations[i].createRange(name, from, to);
  7418. }
  7419. }
  7420. }
  7421. };
  7422. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7423. if (deleteFrames === void 0) { deleteFrames = true; }
  7424. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7425. if (this.animations[i]) {
  7426. this.animations[i].deleteRange(name, deleteFrames);
  7427. }
  7428. }
  7429. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7430. };
  7431. Node.prototype.getAnimationRange = function (name) {
  7432. return this._ranges[name];
  7433. };
  7434. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7435. var range = this.getAnimationRange(name);
  7436. if (!range) {
  7437. return null;
  7438. }
  7439. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7440. };
  7441. Node.prototype.serializeAnimationRanges = function () {
  7442. var serializationRanges = [];
  7443. for (var name in this._ranges) {
  7444. var range = {};
  7445. range.name = name;
  7446. range.from = this._ranges[name].from;
  7447. range.to = this._ranges[name].to;
  7448. serializationRanges.push(range);
  7449. }
  7450. return serializationRanges;
  7451. };
  7452. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7453. if (parsedNode.ranges) {
  7454. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7455. var data = parsedNode.ranges[index];
  7456. node.createAnimationRange(data.name, data.from, data.to);
  7457. }
  7458. }
  7459. };
  7460. __decorate([
  7461. BABYLON.serialize()
  7462. ], Node.prototype, "name", void 0);
  7463. __decorate([
  7464. BABYLON.serialize()
  7465. ], Node.prototype, "id", void 0);
  7466. __decorate([
  7467. BABYLON.serialize()
  7468. ], Node.prototype, "uniqueId", void 0);
  7469. __decorate([
  7470. BABYLON.serialize()
  7471. ], Node.prototype, "state", void 0);
  7472. return Node;
  7473. })();
  7474. BABYLON.Node = Node;
  7475. })(BABYLON || (BABYLON = {}));
  7476. var BABYLON;
  7477. (function (BABYLON) {
  7478. var FilesInput = (function () {
  7479. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7480. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7481. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7482. this._engine = p_engine;
  7483. this._canvas = p_canvas;
  7484. this._currentScene = p_scene;
  7485. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7486. this._progressCallback = p_progressCallback;
  7487. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7488. this._textureLoadingCallback = p_textureLoadingCallback;
  7489. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7490. }
  7491. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7492. var _this = this;
  7493. if (p_elementToMonitor) {
  7494. this._elementToMonitor = p_elementToMonitor;
  7495. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7496. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7497. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7498. }
  7499. };
  7500. FilesInput.prototype.renderFunction = function () {
  7501. if (this._additionnalRenderLoopLogicCallback) {
  7502. this._additionnalRenderLoopLogicCallback();
  7503. }
  7504. if (this._currentScene) {
  7505. if (this._textureLoadingCallback) {
  7506. var remaining = this._currentScene.getWaitingItemsCount();
  7507. if (remaining > 0) {
  7508. this._textureLoadingCallback(remaining);
  7509. }
  7510. }
  7511. this._currentScene.render();
  7512. }
  7513. };
  7514. FilesInput.prototype.drag = function (e) {
  7515. e.stopPropagation();
  7516. e.preventDefault();
  7517. };
  7518. FilesInput.prototype.drop = function (eventDrop) {
  7519. eventDrop.stopPropagation();
  7520. eventDrop.preventDefault();
  7521. this.loadFiles(eventDrop);
  7522. };
  7523. FilesInput.prototype.loadFiles = function (event) {
  7524. if (this._startingProcessingFilesCallback)
  7525. this._startingProcessingFilesCallback();
  7526. // Handling data transfer via drag'n'drop
  7527. if (event && event.dataTransfer && event.dataTransfer.files) {
  7528. this._filesToLoad = event.dataTransfer.files;
  7529. }
  7530. // Handling files from input files
  7531. if (event && event.target && event.target.files) {
  7532. this._filesToLoad = event.target.files;
  7533. }
  7534. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7535. for (var i = 0; i < this._filesToLoad.length; i++) {
  7536. switch (this._filesToLoad[i].type) {
  7537. case "image/jpeg":
  7538. case "image/png":
  7539. case "image/bmp":
  7540. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7541. break;
  7542. case "image/targa":
  7543. case "image/vnd.ms-dds":
  7544. case "audio/wav":
  7545. case "audio/x-wav":
  7546. case "audio/mp3":
  7547. case "audio/mpeg":
  7548. case "audio/mpeg3":
  7549. case "audio/x-mpeg-3":
  7550. case "audio/ogg":
  7551. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7552. break;
  7553. default:
  7554. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7555. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7556. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7557. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7558. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7559. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7560. this._sceneFileToLoad = this._filesToLoad[i];
  7561. }
  7562. break;
  7563. }
  7564. }
  7565. this.reload();
  7566. }
  7567. };
  7568. FilesInput.prototype.reload = function () {
  7569. var _this = this;
  7570. var that = this;
  7571. // If a ".babylon" file has been provided
  7572. if (this._sceneFileToLoad) {
  7573. if (this._currentScene) {
  7574. if (BABYLON.Tools.errorsCount > 0) {
  7575. BABYLON.Tools.ClearLogCache();
  7576. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7577. }
  7578. this._engine.stopRenderLoop();
  7579. this._currentScene.dispose();
  7580. }
  7581. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7582. that._currentScene = newScene;
  7583. // Wait for textures and shaders to be ready
  7584. that._currentScene.executeWhenReady(function () {
  7585. // Attach camera to canvas inputs
  7586. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7587. that._currentScene.createDefaultCameraOrLight();
  7588. }
  7589. that._currentScene.activeCamera.attachControl(that._canvas);
  7590. if (that._sceneLoadedCallback) {
  7591. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7592. }
  7593. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7594. });
  7595. }, function (progress) {
  7596. if (_this._progressCallback) {
  7597. _this._progressCallback(progress);
  7598. }
  7599. });
  7600. }
  7601. else {
  7602. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7603. }
  7604. };
  7605. FilesInput.FilesTextures = new Array();
  7606. FilesInput.FilesToLoad = new Array();
  7607. return FilesInput;
  7608. })();
  7609. BABYLON.FilesInput = FilesInput;
  7610. })(BABYLON || (BABYLON = {}));
  7611. var BABYLON;
  7612. (function (BABYLON) {
  7613. var IntersectionInfo = (function () {
  7614. function IntersectionInfo(bu, bv, distance) {
  7615. this.bu = bu;
  7616. this.bv = bv;
  7617. this.distance = distance;
  7618. this.faceId = 0;
  7619. this.subMeshId = 0;
  7620. }
  7621. return IntersectionInfo;
  7622. })();
  7623. BABYLON.IntersectionInfo = IntersectionInfo;
  7624. var PickingInfo = (function () {
  7625. function PickingInfo() {
  7626. this.hit = false;
  7627. this.distance = 0;
  7628. this.pickedPoint = null;
  7629. this.pickedMesh = null;
  7630. this.bu = 0;
  7631. this.bv = 0;
  7632. this.faceId = -1;
  7633. this.subMeshId = 0;
  7634. this.pickedSprite = null;
  7635. }
  7636. // Methods
  7637. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7638. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7639. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7640. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7641. return null;
  7642. }
  7643. var indices = this.pickedMesh.getIndices();
  7644. var result;
  7645. if (useVerticesNormals) {
  7646. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7647. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7648. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7649. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7650. normal0 = normal0.scale(this.bu);
  7651. normal1 = normal1.scale(this.bv);
  7652. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7653. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7654. }
  7655. else {
  7656. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7657. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7658. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7659. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7660. var p1p2 = vertex1.subtract(vertex2);
  7661. var p3p2 = vertex3.subtract(vertex2);
  7662. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7663. }
  7664. if (useWorldCoordinates) {
  7665. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7666. }
  7667. return BABYLON.Vector3.Normalize(result);
  7668. };
  7669. PickingInfo.prototype.getTextureCoordinates = function () {
  7670. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7671. return null;
  7672. }
  7673. var indices = this.pickedMesh.getIndices();
  7674. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7675. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7676. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7677. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7678. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7679. uv1 = uv1.scale(this.bu);
  7680. uv2 = uv2.scale(this.bv);
  7681. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7682. };
  7683. return PickingInfo;
  7684. })();
  7685. BABYLON.PickingInfo = PickingInfo;
  7686. })(BABYLON || (BABYLON = {}));
  7687. var BABYLON;
  7688. (function (BABYLON) {
  7689. var BoundingSphere = (function () {
  7690. function BoundingSphere(minimum, maximum) {
  7691. this.minimum = minimum;
  7692. this.maximum = maximum;
  7693. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7694. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7695. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7696. this.radius = distance * 0.5;
  7697. this.centerWorld = BABYLON.Vector3.Zero();
  7698. this._update(BABYLON.Matrix.Identity());
  7699. }
  7700. // Methods
  7701. BoundingSphere.prototype._update = function (world) {
  7702. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7703. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7704. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7705. };
  7706. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7707. for (var i = 0; i < 6; i++) {
  7708. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7709. return false;
  7710. }
  7711. return true;
  7712. };
  7713. BoundingSphere.prototype.intersectsPoint = function (point) {
  7714. var x = this.centerWorld.x - point.x;
  7715. var y = this.centerWorld.y - point.y;
  7716. var z = this.centerWorld.z - point.z;
  7717. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7718. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7719. return false;
  7720. return true;
  7721. };
  7722. // Statics
  7723. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7724. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7725. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7726. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7727. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7728. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7729. return false;
  7730. return true;
  7731. };
  7732. return BoundingSphere;
  7733. })();
  7734. BABYLON.BoundingSphere = BoundingSphere;
  7735. })(BABYLON || (BABYLON = {}));
  7736. var BABYLON;
  7737. (function (BABYLON) {
  7738. var BoundingBox = (function () {
  7739. function BoundingBox(minimum, maximum) {
  7740. this.minimum = minimum;
  7741. this.maximum = maximum;
  7742. this.vectors = new Array();
  7743. this.vectorsWorld = new Array();
  7744. // Bounding vectors
  7745. this.vectors.push(this.minimum.clone());
  7746. this.vectors.push(this.maximum.clone());
  7747. this.vectors.push(this.minimum.clone());
  7748. this.vectors[2].x = this.maximum.x;
  7749. this.vectors.push(this.minimum.clone());
  7750. this.vectors[3].y = this.maximum.y;
  7751. this.vectors.push(this.minimum.clone());
  7752. this.vectors[4].z = this.maximum.z;
  7753. this.vectors.push(this.maximum.clone());
  7754. this.vectors[5].z = this.minimum.z;
  7755. this.vectors.push(this.maximum.clone());
  7756. this.vectors[6].x = this.minimum.x;
  7757. this.vectors.push(this.maximum.clone());
  7758. this.vectors[7].y = this.minimum.y;
  7759. // OBB
  7760. this.center = this.maximum.add(this.minimum).scale(0.5);
  7761. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7762. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7763. // World
  7764. for (var index = 0; index < this.vectors.length; index++) {
  7765. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7766. }
  7767. this.minimumWorld = BABYLON.Vector3.Zero();
  7768. this.maximumWorld = BABYLON.Vector3.Zero();
  7769. this._update(BABYLON.Matrix.Identity());
  7770. }
  7771. // Methods
  7772. BoundingBox.prototype.getWorldMatrix = function () {
  7773. return this._worldMatrix;
  7774. };
  7775. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7776. this._worldMatrix.copyFrom(matrix);
  7777. return this;
  7778. };
  7779. BoundingBox.prototype._update = function (world) {
  7780. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7781. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7782. for (var index = 0; index < this.vectors.length; index++) {
  7783. var v = this.vectorsWorld[index];
  7784. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7785. if (v.x < this.minimumWorld.x)
  7786. this.minimumWorld.x = v.x;
  7787. if (v.y < this.minimumWorld.y)
  7788. this.minimumWorld.y = v.y;
  7789. if (v.z < this.minimumWorld.z)
  7790. this.minimumWorld.z = v.z;
  7791. if (v.x > this.maximumWorld.x)
  7792. this.maximumWorld.x = v.x;
  7793. if (v.y > this.maximumWorld.y)
  7794. this.maximumWorld.y = v.y;
  7795. if (v.z > this.maximumWorld.z)
  7796. this.maximumWorld.z = v.z;
  7797. }
  7798. // OBB
  7799. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7800. this.center.scaleInPlace(0.5);
  7801. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7802. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7804. this._worldMatrix = world;
  7805. };
  7806. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7807. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7808. };
  7809. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7810. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7811. };
  7812. BoundingBox.prototype.intersectsPoint = function (point) {
  7813. var delta = -BABYLON.Engine.Epsilon;
  7814. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7815. return false;
  7816. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7817. return false;
  7818. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7819. return false;
  7820. return true;
  7821. };
  7822. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7823. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7824. };
  7825. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7826. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7827. return false;
  7828. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7829. return false;
  7830. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7831. return false;
  7832. return true;
  7833. };
  7834. // Statics
  7835. BoundingBox.Intersects = function (box0, box1) {
  7836. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7837. return false;
  7838. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7839. return false;
  7840. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7841. return false;
  7842. return true;
  7843. };
  7844. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7845. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7846. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7847. return (num <= (sphereRadius * sphereRadius));
  7848. };
  7849. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7850. for (var p = 0; p < 6; p++) {
  7851. for (var i = 0; i < 8; i++) {
  7852. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7853. return false;
  7854. }
  7855. }
  7856. }
  7857. return true;
  7858. };
  7859. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7860. for (var p = 0; p < 6; p++) {
  7861. var inCount = 8;
  7862. for (var i = 0; i < 8; i++) {
  7863. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7864. --inCount;
  7865. }
  7866. else {
  7867. break;
  7868. }
  7869. }
  7870. if (inCount === 0)
  7871. return false;
  7872. }
  7873. return true;
  7874. };
  7875. return BoundingBox;
  7876. })();
  7877. BABYLON.BoundingBox = BoundingBox;
  7878. })(BABYLON || (BABYLON = {}));
  7879. var BABYLON;
  7880. (function (BABYLON) {
  7881. var computeBoxExtents = function (axis, box) {
  7882. var p = BABYLON.Vector3.Dot(box.center, axis);
  7883. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7884. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7885. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7886. var r = r0 + r1 + r2;
  7887. return {
  7888. min: p - r,
  7889. max: p + r
  7890. };
  7891. };
  7892. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7893. var axisOverlap = function (axis, box0, box1) {
  7894. var result0 = computeBoxExtents(axis, box0);
  7895. var result1 = computeBoxExtents(axis, box1);
  7896. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7897. };
  7898. var BoundingInfo = (function () {
  7899. function BoundingInfo(minimum, maximum) {
  7900. this.minimum = minimum;
  7901. this.maximum = maximum;
  7902. this._isLocked = false;
  7903. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7904. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7905. }
  7906. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7907. get: function () {
  7908. return this._isLocked;
  7909. },
  7910. set: function (value) {
  7911. this._isLocked = value;
  7912. },
  7913. enumerable: true,
  7914. configurable: true
  7915. });
  7916. // Methods
  7917. BoundingInfo.prototype.update = function (world) {
  7918. if (this._isLocked) {
  7919. return;
  7920. }
  7921. this.boundingBox._update(world);
  7922. this.boundingSphere._update(world);
  7923. };
  7924. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7925. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7926. return false;
  7927. return this.boundingBox.isInFrustum(frustumPlanes);
  7928. };
  7929. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7930. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7931. };
  7932. BoundingInfo.prototype._checkCollision = function (collider) {
  7933. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7934. };
  7935. BoundingInfo.prototype.intersectsPoint = function (point) {
  7936. if (!this.boundingSphere.centerWorld) {
  7937. return false;
  7938. }
  7939. if (!this.boundingSphere.intersectsPoint(point)) {
  7940. return false;
  7941. }
  7942. if (!this.boundingBox.intersectsPoint(point)) {
  7943. return false;
  7944. }
  7945. return true;
  7946. };
  7947. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7948. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7949. return false;
  7950. }
  7951. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7952. return false;
  7953. }
  7954. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7955. return false;
  7956. }
  7957. if (!precise) {
  7958. return true;
  7959. }
  7960. var box0 = this.boundingBox;
  7961. var box1 = boundingInfo.boundingBox;
  7962. if (!axisOverlap(box0.directions[0], box0, box1))
  7963. return false;
  7964. if (!axisOverlap(box0.directions[1], box0, box1))
  7965. return false;
  7966. if (!axisOverlap(box0.directions[2], box0, box1))
  7967. return false;
  7968. if (!axisOverlap(box1.directions[0], box0, box1))
  7969. return false;
  7970. if (!axisOverlap(box1.directions[1], box0, box1))
  7971. return false;
  7972. if (!axisOverlap(box1.directions[2], box0, box1))
  7973. return false;
  7974. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7975. return false;
  7976. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7977. return false;
  7978. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7979. return false;
  7980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7981. return false;
  7982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7983. return false;
  7984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7985. return false;
  7986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7987. return false;
  7988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7989. return false;
  7990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7991. return false;
  7992. return true;
  7993. };
  7994. return BoundingInfo;
  7995. })();
  7996. BABYLON.BoundingInfo = BoundingInfo;
  7997. })(BABYLON || (BABYLON = {}));
  7998. var BABYLON;
  7999. (function (BABYLON) {
  8000. var AbstractMesh = (function (_super) {
  8001. __extends(AbstractMesh, _super);
  8002. // Constructor
  8003. function AbstractMesh(name, scene) {
  8004. var _this = this;
  8005. _super.call(this, name, scene);
  8006. // Properties
  8007. this.definedFacingForward = true; // orientation for POV movement & rotation
  8008. this.position = new BABYLON.Vector3(0, 0, 0);
  8009. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8010. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8011. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8012. this.visibility = 1.0;
  8013. this.alphaIndex = Number.MAX_VALUE;
  8014. this.infiniteDistance = false;
  8015. this.isVisible = true;
  8016. this.isPickable = true;
  8017. this.showBoundingBox = false;
  8018. this.showSubMeshesBoundingBox = false;
  8019. this.onDispose = null;
  8020. this.isBlocker = false;
  8021. this.renderingGroupId = 0;
  8022. this.receiveShadows = false;
  8023. this.renderOutline = false;
  8024. this.outlineColor = BABYLON.Color3.Red();
  8025. this.outlineWidth = 0.02;
  8026. this.renderOverlay = false;
  8027. this.overlayColor = BABYLON.Color3.Red();
  8028. this.overlayAlpha = 0.5;
  8029. this.hasVertexAlpha = false;
  8030. this.useVertexColors = true;
  8031. this.applyFog = true;
  8032. this.computeBonesUsingShaders = true;
  8033. this.scalingDeterminant = 1;
  8034. this.numBoneInfluencers = 4;
  8035. this.useOctreeForRenderingSelection = true;
  8036. this.useOctreeForPicking = true;
  8037. this.useOctreeForCollisions = true;
  8038. this.layerMask = 0x0FFFFFFF;
  8039. this.alwaysSelectAsActiveMesh = false;
  8040. // Collisions
  8041. this._checkCollisions = false;
  8042. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8043. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8044. this._collider = new BABYLON.Collider();
  8045. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8046. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8047. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8048. // Edges
  8049. this.edgesWidth = 1;
  8050. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8051. // Cache
  8052. this._localWorld = BABYLON.Matrix.Zero();
  8053. this._worldMatrix = BABYLON.Matrix.Zero();
  8054. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8055. this._absolutePosition = BABYLON.Vector3.Zero();
  8056. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8057. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8058. this._isDirty = false;
  8059. this._pivotMatrix = BABYLON.Matrix.Identity();
  8060. this._isDisposed = false;
  8061. this._renderId = 0;
  8062. this._intersectionsInProgress = new Array();
  8063. this._onAfterWorldMatrixUpdate = new Array();
  8064. this._isWorldMatrixFrozen = false;
  8065. this._unIndexed = false;
  8066. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8067. if (collidedMesh === void 0) { collidedMesh = null; }
  8068. //TODO move this to the collision coordinator!
  8069. if (_this.getScene().workerCollisions)
  8070. newPosition.multiplyInPlace(_this._collider.radius);
  8071. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8072. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8073. _this.position.addInPlace(_this._diffPositionForCollisions);
  8074. }
  8075. if (_this.onCollide && collidedMesh) {
  8076. _this.onCollide(collidedMesh);
  8077. }
  8078. if (_this.onCollisionPositionChange) {
  8079. _this.onCollisionPositionChange(_this.position);
  8080. }
  8081. };
  8082. scene.addMesh(this);
  8083. }
  8084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8085. get: function () {
  8086. return AbstractMesh._BILLBOARDMODE_NONE;
  8087. },
  8088. enumerable: true,
  8089. configurable: true
  8090. });
  8091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8092. get: function () {
  8093. return AbstractMesh._BILLBOARDMODE_X;
  8094. },
  8095. enumerable: true,
  8096. configurable: true
  8097. });
  8098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8099. get: function () {
  8100. return AbstractMesh._BILLBOARDMODE_Y;
  8101. },
  8102. enumerable: true,
  8103. configurable: true
  8104. });
  8105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8106. get: function () {
  8107. return AbstractMesh._BILLBOARDMODE_Z;
  8108. },
  8109. enumerable: true,
  8110. configurable: true
  8111. });
  8112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8113. get: function () {
  8114. return AbstractMesh._BILLBOARDMODE_ALL;
  8115. },
  8116. enumerable: true,
  8117. configurable: true
  8118. });
  8119. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8120. get: function () {
  8121. return this._skeleton;
  8122. },
  8123. set: function (value) {
  8124. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8125. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8126. }
  8127. if (value && value.needInitialSkinMatrix) {
  8128. value._registerMeshWithPoseMatrix(this);
  8129. }
  8130. this._skeleton = value;
  8131. if (!this._skeleton) {
  8132. this._bonesTransformMatrices = null;
  8133. }
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8139. /**
  8140. * Getting the rotation object.
  8141. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8142. */
  8143. get: function () {
  8144. return this._rotation;
  8145. },
  8146. set: function (newRotation) {
  8147. this._rotation = newRotation;
  8148. },
  8149. enumerable: true,
  8150. configurable: true
  8151. });
  8152. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8153. get: function () {
  8154. return this._scaling;
  8155. },
  8156. set: function (newScaling) {
  8157. this._scaling = newScaling;
  8158. if (this.physicsImpostor) {
  8159. this.physicsImpostor.forceUpdate();
  8160. }
  8161. },
  8162. enumerable: true,
  8163. configurable: true
  8164. });
  8165. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8166. get: function () {
  8167. return this._rotationQuaternion;
  8168. },
  8169. set: function (quaternion) {
  8170. this._rotationQuaternion = quaternion;
  8171. //reset the rotation vector.
  8172. if (this.rotation.length()) {
  8173. this.rotation.copyFromFloats(0, 0, 0);
  8174. }
  8175. },
  8176. enumerable: true,
  8177. configurable: true
  8178. });
  8179. // Methods
  8180. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8181. this._poseMatrix.copyFrom(matrix);
  8182. };
  8183. AbstractMesh.prototype.getPoseMatrix = function () {
  8184. return this._poseMatrix;
  8185. };
  8186. AbstractMesh.prototype.disableEdgesRendering = function () {
  8187. if (this._edgesRenderer !== undefined) {
  8188. this._edgesRenderer.dispose();
  8189. this._edgesRenderer = undefined;
  8190. }
  8191. };
  8192. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8193. if (epsilon === void 0) { epsilon = 0.95; }
  8194. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8195. this.disableEdgesRendering();
  8196. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8197. };
  8198. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8199. get: function () {
  8200. return false;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. AbstractMesh.prototype.getLOD = function (camera) {
  8206. return this;
  8207. };
  8208. AbstractMesh.prototype.getTotalVertices = function () {
  8209. return 0;
  8210. };
  8211. AbstractMesh.prototype.getIndices = function () {
  8212. return null;
  8213. };
  8214. AbstractMesh.prototype.getVerticesData = function (kind) {
  8215. return null;
  8216. };
  8217. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8218. return false;
  8219. };
  8220. AbstractMesh.prototype.getBoundingInfo = function () {
  8221. if (this._masterMesh) {
  8222. return this._masterMesh.getBoundingInfo();
  8223. }
  8224. if (!this._boundingInfo) {
  8225. this._updateBoundingInfo();
  8226. }
  8227. return this._boundingInfo;
  8228. };
  8229. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8230. get: function () {
  8231. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. AbstractMesh.prototype._preActivate = function () {
  8237. };
  8238. AbstractMesh.prototype._activate = function (renderId) {
  8239. this._renderId = renderId;
  8240. };
  8241. AbstractMesh.prototype.getWorldMatrix = function () {
  8242. if (this._masterMesh) {
  8243. return this._masterMesh.getWorldMatrix();
  8244. }
  8245. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8246. this.computeWorldMatrix();
  8247. }
  8248. return this._worldMatrix;
  8249. };
  8250. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8251. get: function () {
  8252. return this._worldMatrix;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8258. get: function () {
  8259. return this._absolutePosition;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8265. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8266. this.computeWorldMatrix(true);
  8267. this._isWorldMatrixFrozen = true;
  8268. };
  8269. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8270. this._isWorldMatrixFrozen = false;
  8271. this.computeWorldMatrix(true);
  8272. };
  8273. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8274. get: function () {
  8275. return this._isWorldMatrixFrozen;
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8281. axis.normalize();
  8282. if (!this.rotationQuaternion) {
  8283. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8284. this.rotation = BABYLON.Vector3.Zero();
  8285. }
  8286. var rotationQuaternion;
  8287. if (!space || space === BABYLON.Space.LOCAL) {
  8288. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8289. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8290. }
  8291. else {
  8292. if (this.parent) {
  8293. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8294. invertParentWorldMatrix.invert();
  8295. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8296. }
  8297. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8298. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8299. }
  8300. };
  8301. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8302. var displacementVector = axis.scale(distance);
  8303. if (!space || space === BABYLON.Space.LOCAL) {
  8304. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8305. this.setPositionWithLocalVector(tempV3);
  8306. }
  8307. else {
  8308. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8309. }
  8310. };
  8311. AbstractMesh.prototype.getAbsolutePosition = function () {
  8312. this.computeWorldMatrix();
  8313. return this._absolutePosition;
  8314. };
  8315. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8316. if (!absolutePosition) {
  8317. return;
  8318. }
  8319. var absolutePositionX;
  8320. var absolutePositionY;
  8321. var absolutePositionZ;
  8322. if (absolutePosition.x === undefined) {
  8323. if (arguments.length < 3) {
  8324. return;
  8325. }
  8326. absolutePositionX = arguments[0];
  8327. absolutePositionY = arguments[1];
  8328. absolutePositionZ = arguments[2];
  8329. }
  8330. else {
  8331. absolutePositionX = absolutePosition.x;
  8332. absolutePositionY = absolutePosition.y;
  8333. absolutePositionZ = absolutePosition.z;
  8334. }
  8335. if (this.parent) {
  8336. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8337. invertParentWorldMatrix.invert();
  8338. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8339. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8340. }
  8341. else {
  8342. this.position.x = absolutePositionX;
  8343. this.position.y = absolutePositionY;
  8344. this.position.z = absolutePositionZ;
  8345. }
  8346. };
  8347. // ================================== Point of View Movement =================================
  8348. /**
  8349. * Perform relative position change from the point of view of behind the front of the mesh.
  8350. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8351. * Supports definition of mesh facing forward or backward.
  8352. * @param {number} amountRight
  8353. * @param {number} amountUp
  8354. * @param {number} amountForward
  8355. */
  8356. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8357. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8358. };
  8359. /**
  8360. * Calculate relative position change from the point of view of behind the front of the mesh.
  8361. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8362. * Supports definition of mesh facing forward or backward.
  8363. * @param {number} amountRight
  8364. * @param {number} amountUp
  8365. * @param {number} amountForward
  8366. */
  8367. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8368. var rotMatrix = new BABYLON.Matrix();
  8369. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8370. rotQuaternion.toRotationMatrix(rotMatrix);
  8371. var translationDelta = BABYLON.Vector3.Zero();
  8372. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8374. return translationDelta;
  8375. };
  8376. // ================================== Point of View Rotation =================================
  8377. /**
  8378. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8379. * Supports definition of mesh facing forward or backward.
  8380. * @param {number} flipBack
  8381. * @param {number} twirlClockwise
  8382. * @param {number} tiltRight
  8383. */
  8384. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8385. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8386. };
  8387. /**
  8388. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8389. * Supports definition of mesh facing forward or backward.
  8390. * @param {number} flipBack
  8391. * @param {number} twirlClockwise
  8392. * @param {number} tiltRight
  8393. */
  8394. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8395. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8396. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8397. };
  8398. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8399. this._pivotMatrix = matrix;
  8400. this._cache.pivotMatrixUpdated = true;
  8401. };
  8402. AbstractMesh.prototype.getPivotMatrix = function () {
  8403. return this._pivotMatrix;
  8404. };
  8405. AbstractMesh.prototype._isSynchronized = function () {
  8406. if (this._isDirty) {
  8407. return false;
  8408. }
  8409. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8410. return false;
  8411. if (this._cache.pivotMatrixUpdated) {
  8412. return false;
  8413. }
  8414. if (this.infiniteDistance) {
  8415. return false;
  8416. }
  8417. if (!this._cache.position.equals(this.position))
  8418. return false;
  8419. if (this.rotationQuaternion) {
  8420. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8421. return false;
  8422. }
  8423. else {
  8424. if (!this._cache.rotation.equals(this.rotation))
  8425. return false;
  8426. }
  8427. if (!this._cache.scaling.equals(this.scaling))
  8428. return false;
  8429. return true;
  8430. };
  8431. AbstractMesh.prototype._initCache = function () {
  8432. _super.prototype._initCache.call(this);
  8433. this._cache.localMatrixUpdated = false;
  8434. this._cache.position = BABYLON.Vector3.Zero();
  8435. this._cache.scaling = BABYLON.Vector3.Zero();
  8436. this._cache.rotation = BABYLON.Vector3.Zero();
  8437. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8438. this._cache.billboardMode = -1;
  8439. };
  8440. AbstractMesh.prototype.markAsDirty = function (property) {
  8441. if (property === "rotation") {
  8442. this.rotationQuaternion = null;
  8443. }
  8444. this._currentRenderId = Number.MAX_VALUE;
  8445. this._isDirty = true;
  8446. };
  8447. AbstractMesh.prototype._updateBoundingInfo = function () {
  8448. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8449. this._boundingInfo.update(this.worldMatrixFromCache);
  8450. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8451. };
  8452. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8453. if (!this.subMeshes) {
  8454. return;
  8455. }
  8456. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8457. var subMesh = this.subMeshes[subIndex];
  8458. if (!subMesh.IsGlobal) {
  8459. subMesh.updateBoundingInfo(matrix);
  8460. }
  8461. }
  8462. };
  8463. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8464. if (this._isWorldMatrixFrozen) {
  8465. return this._worldMatrix;
  8466. }
  8467. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8468. this._currentRenderId = this.getScene().getRenderId();
  8469. return this._worldMatrix;
  8470. }
  8471. this._cache.position.copyFrom(this.position);
  8472. this._cache.scaling.copyFrom(this.scaling);
  8473. this._cache.pivotMatrixUpdated = false;
  8474. this._cache.billboardMode = this.billboardMode;
  8475. this._currentRenderId = this.getScene().getRenderId();
  8476. this._isDirty = false;
  8477. // Scaling
  8478. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8479. // Rotation
  8480. //rotate, if quaternion is set and rotation was used
  8481. if (this.rotationQuaternion) {
  8482. var len = this.rotation.length();
  8483. if (len) {
  8484. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8485. this.rotation.copyFromFloats(0, 0, 0);
  8486. }
  8487. }
  8488. if (this.rotationQuaternion) {
  8489. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8490. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8491. }
  8492. else {
  8493. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8494. this._cache.rotation.copyFrom(this.rotation);
  8495. }
  8496. // Translation
  8497. if (this.infiniteDistance && !this.parent) {
  8498. var camera = this.getScene().activeCamera;
  8499. if (camera) {
  8500. var cameraWorldMatrix = camera.getWorldMatrix();
  8501. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8502. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8503. }
  8504. }
  8505. else {
  8506. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8507. }
  8508. // Composing transformations
  8509. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8510. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8511. // Billboarding
  8512. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8513. var localPosition = this.position.clone();
  8514. var zero = this.getScene().activeCamera.globalPosition.clone();
  8515. if (this.parent && this.parent.position) {
  8516. localPosition.addInPlace(this.parent.position);
  8517. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8518. }
  8519. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8520. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8521. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8522. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8523. zero.y = localPosition.y + 0.001;
  8524. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8525. zero.z = localPosition.z + 0.001;
  8526. }
  8527. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8528. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8529. BABYLON.Tmp.Matrix[3].invert();
  8530. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8531. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8532. }
  8533. // Local world
  8534. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8535. // Parent
  8536. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8537. this._markSyncedWithParent();
  8538. if (this._meshToBoneReferal) {
  8539. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8540. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8541. }
  8542. else {
  8543. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8544. }
  8545. }
  8546. else {
  8547. this._worldMatrix.copyFrom(this._localWorld);
  8548. }
  8549. // Bounding info
  8550. this._updateBoundingInfo();
  8551. // Absolute position
  8552. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8553. // Callbacks
  8554. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8555. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8556. }
  8557. if (!this._poseMatrix) {
  8558. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8559. }
  8560. return this._worldMatrix;
  8561. };
  8562. /**
  8563. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8564. * @param func: callback function to add
  8565. */
  8566. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8567. this._onAfterWorldMatrixUpdate.push(func);
  8568. };
  8569. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8570. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8571. if (index > -1) {
  8572. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8573. }
  8574. };
  8575. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8576. this.computeWorldMatrix();
  8577. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8578. };
  8579. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8580. this.computeWorldMatrix();
  8581. var invLocalWorldMatrix = this._localWorld.clone();
  8582. invLocalWorldMatrix.invert();
  8583. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8584. };
  8585. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8586. this.computeWorldMatrix(true);
  8587. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8588. };
  8589. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8590. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8591. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8592. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8593. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8594. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8595. /// <returns>Mesh oriented towards targetMesh</returns>
  8596. yawCor = yawCor || 0; // default to zero if undefined
  8597. pitchCor = pitchCor || 0;
  8598. rollCor = rollCor || 0;
  8599. var dv = targetPoint.subtract(this.position);
  8600. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8601. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8602. var pitch = Math.atan2(dv.y, len);
  8603. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8604. };
  8605. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8606. this._meshToBoneReferal = affectedMesh;
  8607. this.parent = bone;
  8608. if (bone.getWorldMatrix().determinant() < 0) {
  8609. this.scalingDeterminant *= -1;
  8610. }
  8611. };
  8612. AbstractMesh.prototype.detachFromBone = function () {
  8613. if (this.parent.getWorldMatrix().determinant() < 0) {
  8614. this.scalingDeterminant *= -1;
  8615. }
  8616. this._meshToBoneReferal = null;
  8617. this.parent = null;
  8618. };
  8619. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8620. return this._boundingInfo.isInFrustum(frustumPlanes);
  8621. };
  8622. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8623. if (!camera) {
  8624. camera = this.getScene().activeCamera;
  8625. }
  8626. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8627. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8628. return false;
  8629. }
  8630. return true;
  8631. };
  8632. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8633. if (!this._boundingInfo || !mesh._boundingInfo) {
  8634. return false;
  8635. }
  8636. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8637. };
  8638. AbstractMesh.prototype.intersectsPoint = function (point) {
  8639. if (!this._boundingInfo) {
  8640. return false;
  8641. }
  8642. return this._boundingInfo.intersectsPoint(point);
  8643. };
  8644. // Physics
  8645. /**
  8646. * @Deprecated. Use new PhysicsImpostor instead.
  8647. * */
  8648. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8649. //legacy support
  8650. if (impostor.impostor) {
  8651. options = impostor;
  8652. impostor = impostor.impostor;
  8653. }
  8654. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8655. return this.physicsImpostor.physicsBody;
  8656. };
  8657. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8658. return this.physicsImpostor;
  8659. };
  8660. /**
  8661. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8662. */
  8663. AbstractMesh.prototype.getPhysicsMass = function () {
  8664. return this.physicsImpostor.getParam("mass");
  8665. };
  8666. /**
  8667. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8668. */
  8669. AbstractMesh.prototype.getPhysicsFriction = function () {
  8670. return this.physicsImpostor.getParam("friction");
  8671. };
  8672. /**
  8673. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8674. */
  8675. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8676. return this.physicsImpostor.getParam("resitution");
  8677. };
  8678. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8679. if (!camera) {
  8680. camera = this.getScene().activeCamera;
  8681. }
  8682. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8683. };
  8684. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8685. if (!camera) {
  8686. camera = this.getScene().activeCamera;
  8687. }
  8688. return this.absolutePosition.subtract(camera.position).length();
  8689. };
  8690. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8691. if (!this.physicsImpostor) {
  8692. return;
  8693. }
  8694. this.physicsImpostor.applyImpulse(force, contactPoint);
  8695. };
  8696. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8697. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8698. return;
  8699. }
  8700. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8701. mainPivot: pivot1,
  8702. connectedPivot: pivot2,
  8703. nativeParams: options
  8704. });
  8705. };
  8706. /**
  8707. * @Deprecated
  8708. */
  8709. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8710. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8711. this.updatePhysicsBody();
  8712. };
  8713. /**
  8714. * @Deprecated
  8715. * Calling this function is not needed anymore.
  8716. * The physics engine takes care of transofmration automatically.
  8717. */
  8718. AbstractMesh.prototype.updatePhysicsBody = function () {
  8719. //Unneeded
  8720. };
  8721. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8722. // Collisions
  8723. get: function () {
  8724. return this._checkCollisions;
  8725. },
  8726. set: function (collisionEnabled) {
  8727. this._checkCollisions = collisionEnabled;
  8728. if (this.getScene().workerCollisions) {
  8729. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8730. }
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8736. var globalPosition = this.getAbsolutePosition();
  8737. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8738. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8739. this._collider.radius = this.ellipsoid;
  8740. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8741. };
  8742. // Submeshes octree
  8743. /**
  8744. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8745. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8746. */
  8747. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8748. if (maxCapacity === void 0) { maxCapacity = 64; }
  8749. if (maxDepth === void 0) { maxDepth = 2; }
  8750. if (!this._submeshesOctree) {
  8751. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8752. }
  8753. this.computeWorldMatrix(true);
  8754. // Update octree
  8755. var bbox = this.getBoundingInfo().boundingBox;
  8756. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8757. return this._submeshesOctree;
  8758. };
  8759. // Collisions
  8760. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8761. this._generatePointsArray();
  8762. // Transformation
  8763. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8764. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8765. subMesh._lastColliderWorldVertices = [];
  8766. subMesh._trianglePlanes = [];
  8767. var start = subMesh.verticesStart;
  8768. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8769. for (var i = start; i < end; i++) {
  8770. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8771. }
  8772. }
  8773. // Collide
  8774. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8775. if (collider.collisionFound) {
  8776. collider.collidedMesh = this;
  8777. }
  8778. };
  8779. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8780. var subMeshes;
  8781. var len;
  8782. // Octrees
  8783. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8784. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8785. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8786. len = intersections.length;
  8787. subMeshes = intersections.data;
  8788. }
  8789. else {
  8790. subMeshes = this.subMeshes;
  8791. len = subMeshes.length;
  8792. }
  8793. for (var index = 0; index < len; index++) {
  8794. var subMesh = subMeshes[index];
  8795. // Bounding test
  8796. if (len > 1 && !subMesh._checkCollision(collider))
  8797. continue;
  8798. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8799. }
  8800. };
  8801. AbstractMesh.prototype._checkCollision = function (collider) {
  8802. // Bounding box test
  8803. if (!this._boundingInfo._checkCollision(collider))
  8804. return;
  8805. // Transformation matrix
  8806. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8807. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8808. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8809. };
  8810. // Picking
  8811. AbstractMesh.prototype._generatePointsArray = function () {
  8812. return false;
  8813. };
  8814. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8815. var pickingInfo = new BABYLON.PickingInfo();
  8816. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8817. return pickingInfo;
  8818. }
  8819. if (!this._generatePointsArray()) {
  8820. return pickingInfo;
  8821. }
  8822. var intersectInfo = null;
  8823. // Octrees
  8824. var subMeshes;
  8825. var len;
  8826. if (this._submeshesOctree && this.useOctreeForPicking) {
  8827. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8828. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8829. len = intersections.length;
  8830. subMeshes = intersections.data;
  8831. }
  8832. else {
  8833. subMeshes = this.subMeshes;
  8834. len = subMeshes.length;
  8835. }
  8836. for (var index = 0; index < len; index++) {
  8837. var subMesh = subMeshes[index];
  8838. // Bounding test
  8839. if (len > 1 && !subMesh.canIntersects(ray))
  8840. continue;
  8841. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8842. if (currentIntersectInfo) {
  8843. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8844. intersectInfo = currentIntersectInfo;
  8845. intersectInfo.subMeshId = index;
  8846. if (fastCheck) {
  8847. break;
  8848. }
  8849. }
  8850. }
  8851. }
  8852. if (intersectInfo) {
  8853. // Get picked point
  8854. var world = this.getWorldMatrix();
  8855. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8856. var direction = ray.direction.clone();
  8857. direction = direction.scale(intersectInfo.distance);
  8858. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8859. var pickedPoint = worldOrigin.add(worldDirection);
  8860. // Return result
  8861. pickingInfo.hit = true;
  8862. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8863. pickingInfo.pickedPoint = pickedPoint;
  8864. pickingInfo.pickedMesh = this;
  8865. pickingInfo.bu = intersectInfo.bu;
  8866. pickingInfo.bv = intersectInfo.bv;
  8867. pickingInfo.faceId = intersectInfo.faceId;
  8868. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8869. return pickingInfo;
  8870. }
  8871. return pickingInfo;
  8872. };
  8873. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8874. return null;
  8875. };
  8876. AbstractMesh.prototype.releaseSubMeshes = function () {
  8877. if (this.subMeshes) {
  8878. while (this.subMeshes.length) {
  8879. this.subMeshes[0].dispose();
  8880. }
  8881. }
  8882. else {
  8883. this.subMeshes = new Array();
  8884. }
  8885. };
  8886. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8887. var index;
  8888. // Action manager
  8889. if (this.actionManager) {
  8890. this.actionManager.dispose();
  8891. this.actionManager = null;
  8892. }
  8893. // Skeleton
  8894. this.skeleton = null;
  8895. // Animations
  8896. this.getScene().stopAnimation(this);
  8897. // Physics
  8898. if (this.physicsImpostor) {
  8899. this.physicsImpostor.dispose(!doNotRecurse);
  8900. }
  8901. // Intersections in progress
  8902. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8903. var other = this._intersectionsInProgress[index];
  8904. var pos = other._intersectionsInProgress.indexOf(this);
  8905. other._intersectionsInProgress.splice(pos, 1);
  8906. }
  8907. this._intersectionsInProgress = [];
  8908. // Edges
  8909. if (this._edgesRenderer) {
  8910. this._edgesRenderer.dispose();
  8911. this._edgesRenderer = null;
  8912. }
  8913. // SubMeshes
  8914. this.releaseSubMeshes();
  8915. // Remove from scene
  8916. this.getScene().removeMesh(this);
  8917. if (!doNotRecurse) {
  8918. // Particles
  8919. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8920. if (this.getScene().particleSystems[index].emitter === this) {
  8921. this.getScene().particleSystems[index].dispose();
  8922. index--;
  8923. }
  8924. }
  8925. // Children
  8926. var objects = this.getScene().meshes.slice(0);
  8927. for (index = 0; index < objects.length; index++) {
  8928. if (objects[index].parent === this) {
  8929. objects[index].dispose();
  8930. }
  8931. }
  8932. }
  8933. else {
  8934. for (index = 0; index < this.getScene().meshes.length; index++) {
  8935. var obj = this.getScene().meshes[index];
  8936. if (obj.parent === this) {
  8937. obj.parent = null;
  8938. obj.computeWorldMatrix(true);
  8939. }
  8940. }
  8941. }
  8942. this._onAfterWorldMatrixUpdate = [];
  8943. this._isDisposed = true;
  8944. // Callback
  8945. if (this.onDispose) {
  8946. this.onDispose();
  8947. }
  8948. };
  8949. // Statics
  8950. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8951. AbstractMesh._BILLBOARDMODE_X = 1;
  8952. AbstractMesh._BILLBOARDMODE_Y = 2;
  8953. AbstractMesh._BILLBOARDMODE_Z = 4;
  8954. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8955. return AbstractMesh;
  8956. })(BABYLON.Node);
  8957. BABYLON.AbstractMesh = AbstractMesh;
  8958. })(BABYLON || (BABYLON = {}));
  8959. var BABYLON;
  8960. (function (BABYLON) {
  8961. var Light = (function (_super) {
  8962. __extends(Light, _super);
  8963. function Light(name, scene) {
  8964. _super.call(this, name, scene);
  8965. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8966. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8967. this.intensity = 1.0;
  8968. this.range = Number.MAX_VALUE;
  8969. this.includeOnlyWithLayerMask = 0;
  8970. this.includedOnlyMeshes = new Array();
  8971. this.excludedMeshes = new Array();
  8972. this.excludeWithLayerMask = 0;
  8973. // PBR Properties.
  8974. this.radius = 0.00001;
  8975. this._excludedMeshesIds = new Array();
  8976. this._includedOnlyMeshesIds = new Array();
  8977. scene.addLight(this);
  8978. }
  8979. Light.prototype.getShadowGenerator = function () {
  8980. return this._shadowGenerator;
  8981. };
  8982. Light.prototype.getAbsolutePosition = function () {
  8983. return BABYLON.Vector3.Zero();
  8984. };
  8985. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8986. };
  8987. Light.prototype._getWorldMatrix = function () {
  8988. return BABYLON.Matrix.Identity();
  8989. };
  8990. Light.prototype.canAffectMesh = function (mesh) {
  8991. if (!mesh) {
  8992. return true;
  8993. }
  8994. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8995. return false;
  8996. }
  8997. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8998. return false;
  8999. }
  9000. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9001. return false;
  9002. }
  9003. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9004. return false;
  9005. }
  9006. return true;
  9007. };
  9008. Light.prototype.getWorldMatrix = function () {
  9009. this._currentRenderId = this.getScene().getRenderId();
  9010. var worldMatrix = this._getWorldMatrix();
  9011. if (this.parent && this.parent.getWorldMatrix) {
  9012. if (!this._parentedWorldMatrix) {
  9013. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9014. }
  9015. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9016. this._markSyncedWithParent();
  9017. return this._parentedWorldMatrix;
  9018. }
  9019. return worldMatrix;
  9020. };
  9021. Light.prototype.dispose = function () {
  9022. if (this._shadowGenerator) {
  9023. this._shadowGenerator.dispose();
  9024. this._shadowGenerator = null;
  9025. }
  9026. // Animations
  9027. this.getScene().stopAnimation(this);
  9028. // Remove from scene
  9029. this.getScene().removeLight(this);
  9030. };
  9031. Light.prototype.getTypeID = function () {
  9032. return 0;
  9033. };
  9034. Light.prototype.clone = function (name) {
  9035. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9036. };
  9037. Light.prototype.serialize = function () {
  9038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9039. // Type
  9040. serializationObject.type = this.getTypeID();
  9041. // Parent
  9042. if (this.parent) {
  9043. serializationObject.parentId = this.parent.id;
  9044. }
  9045. return serializationObject;
  9046. };
  9047. Light.GetConstructorFromName = function (type, name, scene) {
  9048. switch (type) {
  9049. case 0:
  9050. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9051. case 1:
  9052. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9053. case 2:
  9054. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9055. case 3:
  9056. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9057. }
  9058. };
  9059. Light.Parse = function (parsedLight, scene) {
  9060. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9061. // Inclusion / exclusions
  9062. if (parsedLight.excludedMeshesIds) {
  9063. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9064. }
  9065. if (parsedLight.includedOnlyMeshesIds) {
  9066. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9067. }
  9068. // Parent
  9069. if (parsedLight.parentId) {
  9070. light._waitingParentId = parsedLight.parentId;
  9071. }
  9072. // Animations
  9073. if (parsedLight.animations) {
  9074. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9075. var parsedAnimation = parsedLight.animations[animationIndex];
  9076. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9077. }
  9078. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9079. }
  9080. if (parsedLight.autoAnimate) {
  9081. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9082. }
  9083. return light;
  9084. };
  9085. __decorate([
  9086. BABYLON.serializeAsColor3()
  9087. ], Light.prototype, "diffuse", void 0);
  9088. __decorate([
  9089. BABYLON.serializeAsColor3()
  9090. ], Light.prototype, "specular", void 0);
  9091. __decorate([
  9092. BABYLON.serialize()
  9093. ], Light.prototype, "intensity", void 0);
  9094. __decorate([
  9095. BABYLON.serialize()
  9096. ], Light.prototype, "range", void 0);
  9097. __decorate([
  9098. BABYLON.serialize()
  9099. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9100. __decorate([
  9101. BABYLON.serialize()
  9102. ], Light.prototype, "radius", void 0);
  9103. return Light;
  9104. })(BABYLON.Node);
  9105. BABYLON.Light = Light;
  9106. })(BABYLON || (BABYLON = {}));
  9107. var BABYLON;
  9108. (function (BABYLON) {
  9109. var PointLight = (function (_super) {
  9110. __extends(PointLight, _super);
  9111. function PointLight(name, position, scene) {
  9112. _super.call(this, name, scene);
  9113. this.position = position;
  9114. }
  9115. PointLight.prototype.getAbsolutePosition = function () {
  9116. return this.transformedPosition ? this.transformedPosition : this.position;
  9117. };
  9118. PointLight.prototype.computeTransformedPosition = function () {
  9119. if (this.parent && this.parent.getWorldMatrix) {
  9120. if (!this.transformedPosition) {
  9121. this.transformedPosition = BABYLON.Vector3.Zero();
  9122. }
  9123. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9124. return true;
  9125. }
  9126. return false;
  9127. };
  9128. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9129. if (this.parent && this.parent.getWorldMatrix) {
  9130. this.computeTransformedPosition();
  9131. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9132. return;
  9133. }
  9134. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9135. };
  9136. PointLight.prototype.needCube = function () {
  9137. return true;
  9138. };
  9139. PointLight.prototype.supportsVSM = function () {
  9140. return false;
  9141. };
  9142. PointLight.prototype.needRefreshPerFrame = function () {
  9143. return false;
  9144. };
  9145. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9146. switch (faceIndex) {
  9147. case 0:
  9148. return new BABYLON.Vector3(1, 0, 0);
  9149. case 1:
  9150. return new BABYLON.Vector3(-1, 0, 0);
  9151. case 2:
  9152. return new BABYLON.Vector3(0, -1, 0);
  9153. case 3:
  9154. return new BABYLON.Vector3(0, 1, 0);
  9155. case 4:
  9156. return new BABYLON.Vector3(0, 0, 1);
  9157. case 5:
  9158. return new BABYLON.Vector3(0, 0, -1);
  9159. }
  9160. return BABYLON.Vector3.Zero();
  9161. };
  9162. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9163. var activeCamera = this.getScene().activeCamera;
  9164. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9165. };
  9166. PointLight.prototype._getWorldMatrix = function () {
  9167. if (!this._worldMatrix) {
  9168. this._worldMatrix = BABYLON.Matrix.Identity();
  9169. }
  9170. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9171. return this._worldMatrix;
  9172. };
  9173. PointLight.prototype.getTypeID = function () {
  9174. return 0;
  9175. };
  9176. __decorate([
  9177. BABYLON.serializeAsVector3()
  9178. ], PointLight.prototype, "position", void 0);
  9179. return PointLight;
  9180. })(BABYLON.Light);
  9181. BABYLON.PointLight = PointLight;
  9182. })(BABYLON || (BABYLON = {}));
  9183. var BABYLON;
  9184. (function (BABYLON) {
  9185. var SpotLight = (function (_super) {
  9186. __extends(SpotLight, _super);
  9187. function SpotLight(name, position, direction, angle, exponent, scene) {
  9188. _super.call(this, name, scene);
  9189. this.position = position;
  9190. this.direction = direction;
  9191. this.angle = angle;
  9192. this.exponent = exponent;
  9193. }
  9194. SpotLight.prototype.getAbsolutePosition = function () {
  9195. return this.transformedPosition ? this.transformedPosition : this.position;
  9196. };
  9197. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9198. var activeCamera = this.getScene().activeCamera;
  9199. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9200. };
  9201. SpotLight.prototype.needCube = function () {
  9202. return false;
  9203. };
  9204. SpotLight.prototype.supportsVSM = function () {
  9205. return true;
  9206. };
  9207. SpotLight.prototype.needRefreshPerFrame = function () {
  9208. return false;
  9209. };
  9210. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9211. return this.direction;
  9212. };
  9213. SpotLight.prototype.setDirectionToTarget = function (target) {
  9214. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9215. return this.direction;
  9216. };
  9217. SpotLight.prototype.computeTransformedPosition = function () {
  9218. if (this.parent && this.parent.getWorldMatrix) {
  9219. if (!this.transformedPosition) {
  9220. this.transformedPosition = BABYLON.Vector3.Zero();
  9221. }
  9222. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9223. return true;
  9224. }
  9225. return false;
  9226. };
  9227. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9228. var normalizeDirection;
  9229. if (this.parent && this.parent.getWorldMatrix) {
  9230. if (!this._transformedDirection) {
  9231. this._transformedDirection = BABYLON.Vector3.Zero();
  9232. }
  9233. this.computeTransformedPosition();
  9234. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9235. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9236. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9237. }
  9238. else {
  9239. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9240. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9241. }
  9242. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9243. };
  9244. SpotLight.prototype._getWorldMatrix = function () {
  9245. if (!this._worldMatrix) {
  9246. this._worldMatrix = BABYLON.Matrix.Identity();
  9247. }
  9248. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9249. return this._worldMatrix;
  9250. };
  9251. SpotLight.prototype.getTypeID = function () {
  9252. return 2;
  9253. };
  9254. __decorate([
  9255. BABYLON.serializeAsVector3()
  9256. ], SpotLight.prototype, "position", void 0);
  9257. __decorate([
  9258. BABYLON.serializeAsVector3()
  9259. ], SpotLight.prototype, "direction", void 0);
  9260. __decorate([
  9261. BABYLON.serialize()
  9262. ], SpotLight.prototype, "angle", void 0);
  9263. __decorate([
  9264. BABYLON.serialize()
  9265. ], SpotLight.prototype, "exponent", void 0);
  9266. return SpotLight;
  9267. })(BABYLON.Light);
  9268. BABYLON.SpotLight = SpotLight;
  9269. })(BABYLON || (BABYLON = {}));
  9270. var BABYLON;
  9271. (function (BABYLON) {
  9272. var HemisphericLight = (function (_super) {
  9273. __extends(HemisphericLight, _super);
  9274. function HemisphericLight(name, direction, scene) {
  9275. _super.call(this, name, scene);
  9276. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9277. this.direction = direction;
  9278. }
  9279. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9280. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9281. return this.direction;
  9282. };
  9283. HemisphericLight.prototype.getShadowGenerator = function () {
  9284. return null;
  9285. };
  9286. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9287. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9288. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9289. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9290. };
  9291. HemisphericLight.prototype._getWorldMatrix = function () {
  9292. if (!this._worldMatrix) {
  9293. this._worldMatrix = BABYLON.Matrix.Identity();
  9294. }
  9295. return this._worldMatrix;
  9296. };
  9297. HemisphericLight.prototype.getTypeID = function () {
  9298. return 3;
  9299. };
  9300. __decorate([
  9301. BABYLON.serializeAsColor3()
  9302. ], HemisphericLight.prototype, "groundColor", void 0);
  9303. __decorate([
  9304. BABYLON.serializeAsVector3()
  9305. ], HemisphericLight.prototype, "direction", void 0);
  9306. return HemisphericLight;
  9307. })(BABYLON.Light);
  9308. BABYLON.HemisphericLight = HemisphericLight;
  9309. })(BABYLON || (BABYLON = {}));
  9310. var BABYLON;
  9311. (function (BABYLON) {
  9312. var DirectionalLight = (function (_super) {
  9313. __extends(DirectionalLight, _super);
  9314. function DirectionalLight(name, direction, scene) {
  9315. _super.call(this, name, scene);
  9316. this.shadowOrthoScale = 0.5;
  9317. this.autoUpdateExtends = true;
  9318. // Cache
  9319. this._orthoLeft = Number.MAX_VALUE;
  9320. this._orthoRight = Number.MIN_VALUE;
  9321. this._orthoTop = Number.MIN_VALUE;
  9322. this._orthoBottom = Number.MAX_VALUE;
  9323. this.position = direction.scale(-1);
  9324. this.direction = direction;
  9325. }
  9326. DirectionalLight.prototype.getAbsolutePosition = function () {
  9327. return this.transformedPosition ? this.transformedPosition : this.position;
  9328. };
  9329. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9330. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9331. return this.direction;
  9332. };
  9333. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9334. var activeCamera = this.getScene().activeCamera;
  9335. // Check extends
  9336. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9337. var tempVector3 = BABYLON.Vector3.Zero();
  9338. this._orthoLeft = Number.MAX_VALUE;
  9339. this._orthoRight = Number.MIN_VALUE;
  9340. this._orthoTop = Number.MIN_VALUE;
  9341. this._orthoBottom = Number.MAX_VALUE;
  9342. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9343. var mesh = renderList[meshIndex];
  9344. if (!mesh) {
  9345. continue;
  9346. }
  9347. var boundingInfo = mesh.getBoundingInfo();
  9348. if (!boundingInfo) {
  9349. continue;
  9350. }
  9351. var boundingBox = boundingInfo.boundingBox;
  9352. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9353. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9354. if (tempVector3.x < this._orthoLeft)
  9355. this._orthoLeft = tempVector3.x;
  9356. if (tempVector3.y < this._orthoBottom)
  9357. this._orthoBottom = tempVector3.y;
  9358. if (tempVector3.x > this._orthoRight)
  9359. this._orthoRight = tempVector3.x;
  9360. if (tempVector3.y > this._orthoTop)
  9361. this._orthoTop = tempVector3.y;
  9362. }
  9363. }
  9364. }
  9365. var xOffset = this._orthoRight - this._orthoLeft;
  9366. var yOffset = this._orthoTop - this._orthoBottom;
  9367. 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);
  9368. };
  9369. DirectionalLight.prototype.supportsVSM = function () {
  9370. return true;
  9371. };
  9372. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9373. return true;
  9374. };
  9375. DirectionalLight.prototype.needCube = function () {
  9376. return false;
  9377. };
  9378. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9379. return this.direction;
  9380. };
  9381. DirectionalLight.prototype.computeTransformedPosition = function () {
  9382. if (this.parent && this.parent.getWorldMatrix) {
  9383. if (!this.transformedPosition) {
  9384. this.transformedPosition = BABYLON.Vector3.Zero();
  9385. }
  9386. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9387. return true;
  9388. }
  9389. return false;
  9390. };
  9391. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9392. if (this.parent && this.parent.getWorldMatrix) {
  9393. if (!this._transformedDirection) {
  9394. this._transformedDirection = BABYLON.Vector3.Zero();
  9395. }
  9396. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9397. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9398. return;
  9399. }
  9400. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9401. };
  9402. DirectionalLight.prototype._getWorldMatrix = function () {
  9403. if (!this._worldMatrix) {
  9404. this._worldMatrix = BABYLON.Matrix.Identity();
  9405. }
  9406. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9407. return this._worldMatrix;
  9408. };
  9409. DirectionalLight.prototype.getTypeID = function () {
  9410. return 1;
  9411. };
  9412. __decorate([
  9413. BABYLON.serializeAsVector3()
  9414. ], DirectionalLight.prototype, "position", void 0);
  9415. __decorate([
  9416. BABYLON.serializeAsVector3()
  9417. ], DirectionalLight.prototype, "direction", void 0);
  9418. __decorate([
  9419. BABYLON.serialize()
  9420. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9421. __decorate([
  9422. BABYLON.serialize()
  9423. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9424. return DirectionalLight;
  9425. })(BABYLON.Light);
  9426. BABYLON.DirectionalLight = DirectionalLight;
  9427. })(BABYLON || (BABYLON = {}));
  9428. var BABYLON;
  9429. (function (BABYLON) {
  9430. var ShadowGenerator = (function () {
  9431. function ShadowGenerator(mapSize, light) {
  9432. var _this = this;
  9433. // Members
  9434. this._filter = ShadowGenerator.FILTER_NONE;
  9435. this.blurScale = 2;
  9436. this._blurBoxOffset = 0;
  9437. this._bias = 0.00005;
  9438. this._lightDirection = BABYLON.Vector3.Zero();
  9439. this.forceBackFacesOnly = false;
  9440. this._darkness = 0;
  9441. this._transparencyShadow = false;
  9442. this._viewMatrix = BABYLON.Matrix.Zero();
  9443. this._projectionMatrix = BABYLON.Matrix.Zero();
  9444. this._transformMatrix = BABYLON.Matrix.Zero();
  9445. this._worldViewProjection = BABYLON.Matrix.Zero();
  9446. this._currentFaceIndex = 0;
  9447. this._currentFaceIndexCache = 0;
  9448. this._light = light;
  9449. this._scene = light.getScene();
  9450. this._mapSize = mapSize;
  9451. light._shadowGenerator = this;
  9452. // Render target
  9453. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9454. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9455. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9456. this._shadowMap.anisotropicFilteringLevel = 1;
  9457. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9458. this._shadowMap.renderParticles = false;
  9459. this._shadowMap.onBeforeRender = function (faceIndex) {
  9460. _this._currentFaceIndex = faceIndex;
  9461. };
  9462. this._shadowMap.onAfterUnbind = function () {
  9463. if (!_this.useBlurVarianceShadowMap) {
  9464. return;
  9465. }
  9466. if (!_this._shadowMap2) {
  9467. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9468. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9469. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9470. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9471. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9472. _this._downSamplePostprocess.onApply = function (effect) {
  9473. effect.setTexture("textureSampler", _this._shadowMap);
  9474. };
  9475. _this.blurBoxOffset = 1;
  9476. }
  9477. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9478. };
  9479. // Custom render function
  9480. var renderSubMesh = function (subMesh) {
  9481. var mesh = subMesh.getRenderingMesh();
  9482. var scene = _this._scene;
  9483. var engine = scene.getEngine();
  9484. // Culling
  9485. engine.setState(subMesh.getMaterial().backFaceCulling);
  9486. // Managing instances
  9487. var batch = mesh._getInstancesRenderList(subMesh._id);
  9488. if (batch.mustReturn) {
  9489. return;
  9490. }
  9491. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9492. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9493. engine.enableEffect(_this._effect);
  9494. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9495. var material = subMesh.getMaterial();
  9496. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9497. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9498. if (_this.getLight().needCube()) {
  9499. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9500. }
  9501. // Alpha test
  9502. if (material && material.needAlphaTesting()) {
  9503. var alphaTexture = material.getAlphaTestTexture();
  9504. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9505. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9506. }
  9507. // Bones
  9508. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9509. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9510. }
  9511. if (_this.forceBackFacesOnly) {
  9512. engine.setState(true, 0, false, true);
  9513. }
  9514. // Draw
  9515. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9516. if (_this.forceBackFacesOnly) {
  9517. engine.setState(true, 0, false, false);
  9518. }
  9519. }
  9520. else {
  9521. // Need to reset refresh rate of the shadowMap
  9522. _this._shadowMap.resetRefreshCounter();
  9523. }
  9524. };
  9525. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9526. var index;
  9527. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9528. renderSubMesh(opaqueSubMeshes.data[index]);
  9529. }
  9530. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9531. renderSubMesh(alphaTestSubMeshes.data[index]);
  9532. }
  9533. if (_this._transparencyShadow) {
  9534. for (index = 0; index < transparentSubMeshes.length; index++) {
  9535. renderSubMesh(transparentSubMeshes.data[index]);
  9536. }
  9537. }
  9538. };
  9539. this._shadowMap.onClear = function (engine) {
  9540. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9541. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9542. }
  9543. else {
  9544. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9545. }
  9546. };
  9547. }
  9548. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9549. // Static
  9550. get: function () {
  9551. return ShadowGenerator._FILTER_NONE;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9557. get: function () {
  9558. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9564. get: function () {
  9565. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9571. get: function () {
  9572. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9578. get: function () {
  9579. return this._bias;
  9580. },
  9581. set: function (bias) {
  9582. this._bias = bias;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9588. get: function () {
  9589. return this._blurBoxOffset;
  9590. },
  9591. set: function (value) {
  9592. var _this = this;
  9593. if (this._blurBoxOffset === value) {
  9594. return;
  9595. }
  9596. this._blurBoxOffset = value;
  9597. if (this._boxBlurPostprocess) {
  9598. this._boxBlurPostprocess.dispose();
  9599. }
  9600. 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);
  9601. this._boxBlurPostprocess.onApply = function (effect) {
  9602. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9603. };
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9609. get: function () {
  9610. return this._filter;
  9611. },
  9612. set: function (value) {
  9613. if (this._filter === value) {
  9614. return;
  9615. }
  9616. this._filter = value;
  9617. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9618. this._shadowMap.anisotropicFilteringLevel = 16;
  9619. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9620. }
  9621. else {
  9622. this._shadowMap.anisotropicFilteringLevel = 1;
  9623. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9624. }
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9630. get: function () {
  9631. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9632. },
  9633. set: function (value) {
  9634. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9640. get: function () {
  9641. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9642. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9643. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9644. },
  9645. set: function (value) {
  9646. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9652. get: function () {
  9653. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9654. },
  9655. set: function (value) {
  9656. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9662. var defines = [];
  9663. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9664. defines.push("#define VSM");
  9665. }
  9666. if (this.getLight().needCube()) {
  9667. defines.push("#define CUBEMAP");
  9668. }
  9669. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9670. var mesh = subMesh.getMesh();
  9671. var material = subMesh.getMaterial();
  9672. // Alpha test
  9673. if (material && material.needAlphaTesting()) {
  9674. defines.push("#define ALPHATEST");
  9675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9676. attribs.push(BABYLON.VertexBuffer.UVKind);
  9677. defines.push("#define UV1");
  9678. }
  9679. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9681. defines.push("#define UV2");
  9682. }
  9683. }
  9684. // Bones
  9685. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9686. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9687. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9688. if (mesh.numBoneInfluencers > 4) {
  9689. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9690. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9691. }
  9692. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9693. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9694. }
  9695. else {
  9696. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9697. }
  9698. // Instances
  9699. if (useInstances) {
  9700. defines.push("#define INSTANCES");
  9701. attribs.push("world0");
  9702. attribs.push("world1");
  9703. attribs.push("world2");
  9704. attribs.push("world3");
  9705. }
  9706. // Get correct effect
  9707. var join = defines.join("\n");
  9708. if (this._cachedDefines !== join) {
  9709. this._cachedDefines = join;
  9710. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9711. }
  9712. return this._effect.isReady();
  9713. };
  9714. ShadowGenerator.prototype.getShadowMap = function () {
  9715. return this._shadowMap;
  9716. };
  9717. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9718. if (this._shadowMap2) {
  9719. return this._shadowMap2;
  9720. }
  9721. return this._shadowMap;
  9722. };
  9723. ShadowGenerator.prototype.getLight = function () {
  9724. return this._light;
  9725. };
  9726. // Methods
  9727. ShadowGenerator.prototype.getTransformMatrix = function () {
  9728. var scene = this._scene;
  9729. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9730. return this._transformMatrix;
  9731. }
  9732. this._currentRenderID = scene.getRenderId();
  9733. this._currentFaceIndexCache = this._currentFaceIndex;
  9734. var lightPosition = this._light.position;
  9735. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9736. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9737. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9738. }
  9739. if (this._light.computeTransformedPosition()) {
  9740. lightPosition = this._light.transformedPosition;
  9741. }
  9742. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9743. this._cachedPosition = lightPosition.clone();
  9744. this._cachedDirection = this._lightDirection.clone();
  9745. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9746. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9747. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9748. }
  9749. return this._transformMatrix;
  9750. };
  9751. ShadowGenerator.prototype.getDarkness = function () {
  9752. return this._darkness;
  9753. };
  9754. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9755. if (darkness >= 1.0)
  9756. this._darkness = 1.0;
  9757. else if (darkness <= 0.0)
  9758. this._darkness = 0.0;
  9759. else
  9760. this._darkness = darkness;
  9761. };
  9762. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9763. this._transparencyShadow = hasShadow;
  9764. };
  9765. ShadowGenerator.prototype._packHalf = function (depth) {
  9766. var scale = depth * 255.0;
  9767. var fract = scale - Math.floor(scale);
  9768. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9769. };
  9770. ShadowGenerator.prototype.dispose = function () {
  9771. this._shadowMap.dispose();
  9772. if (this._shadowMap2) {
  9773. this._shadowMap2.dispose();
  9774. }
  9775. if (this._downSamplePostprocess) {
  9776. this._downSamplePostprocess.dispose();
  9777. }
  9778. if (this._boxBlurPostprocess) {
  9779. this._boxBlurPostprocess.dispose();
  9780. }
  9781. };
  9782. ShadowGenerator.prototype.serialize = function () {
  9783. var serializationObject = {};
  9784. serializationObject.lightId = this._light.id;
  9785. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9786. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9787. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9788. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9789. serializationObject.renderList = [];
  9790. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9791. var mesh = this.getShadowMap().renderList[meshIndex];
  9792. serializationObject.renderList.push(mesh.id);
  9793. }
  9794. return serializationObject;
  9795. };
  9796. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9797. //casting to point light, as light is missing the position attr and typescript complains.
  9798. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9799. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9800. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9801. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9802. shadowGenerator.getShadowMap().renderList.push(mesh);
  9803. }
  9804. if (parsedShadowGenerator.usePoissonSampling) {
  9805. shadowGenerator.usePoissonSampling = true;
  9806. }
  9807. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9808. shadowGenerator.useVarianceShadowMap = true;
  9809. }
  9810. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9811. shadowGenerator.useBlurVarianceShadowMap = true;
  9812. if (parsedShadowGenerator.blurScale) {
  9813. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9814. }
  9815. if (parsedShadowGenerator.blurBoxOffset) {
  9816. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9817. }
  9818. }
  9819. if (parsedShadowGenerator.bias !== undefined) {
  9820. shadowGenerator.bias = parsedShadowGenerator.bias;
  9821. }
  9822. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9823. return shadowGenerator;
  9824. };
  9825. ShadowGenerator._FILTER_NONE = 0;
  9826. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9827. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9828. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9829. return ShadowGenerator;
  9830. })();
  9831. BABYLON.ShadowGenerator = ShadowGenerator;
  9832. })(BABYLON || (BABYLON = {}));
  9833. var BABYLON;
  9834. (function (BABYLON) {
  9835. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9836. if (boxMin.x > sphereCenter.x + sphereRadius)
  9837. return false;
  9838. if (sphereCenter.x - sphereRadius > boxMax.x)
  9839. return false;
  9840. if (boxMin.y > sphereCenter.y + sphereRadius)
  9841. return false;
  9842. if (sphereCenter.y - sphereRadius > boxMax.y)
  9843. return false;
  9844. if (boxMin.z > sphereCenter.z + sphereRadius)
  9845. return false;
  9846. if (sphereCenter.z - sphereRadius > boxMax.z)
  9847. return false;
  9848. return true;
  9849. };
  9850. var getLowestRoot = function (a, b, c, maxR) {
  9851. var determinant = b * b - 4.0 * a * c;
  9852. var result = { root: 0, found: false };
  9853. if (determinant < 0)
  9854. return result;
  9855. var sqrtD = Math.sqrt(determinant);
  9856. var r1 = (-b - sqrtD) / (2.0 * a);
  9857. var r2 = (-b + sqrtD) / (2.0 * a);
  9858. if (r1 > r2) {
  9859. var temp = r2;
  9860. r2 = r1;
  9861. r1 = temp;
  9862. }
  9863. if (r1 > 0 && r1 < maxR) {
  9864. result.root = r1;
  9865. result.found = true;
  9866. return result;
  9867. }
  9868. if (r2 > 0 && r2 < maxR) {
  9869. result.root = r2;
  9870. result.found = true;
  9871. return result;
  9872. }
  9873. return result;
  9874. };
  9875. var Collider = (function () {
  9876. function Collider() {
  9877. this.radius = new BABYLON.Vector3(1, 1, 1);
  9878. this.retry = 0;
  9879. this.basePointWorld = BABYLON.Vector3.Zero();
  9880. this.velocityWorld = BABYLON.Vector3.Zero();
  9881. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9882. this._collisionPoint = BABYLON.Vector3.Zero();
  9883. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9884. this._tempVector = BABYLON.Vector3.Zero();
  9885. this._tempVector2 = BABYLON.Vector3.Zero();
  9886. this._tempVector3 = BABYLON.Vector3.Zero();
  9887. this._tempVector4 = BABYLON.Vector3.Zero();
  9888. this._edge = BABYLON.Vector3.Zero();
  9889. this._baseToVertex = BABYLON.Vector3.Zero();
  9890. this._destinationPoint = BABYLON.Vector3.Zero();
  9891. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9892. this._displacementVector = BABYLON.Vector3.Zero();
  9893. }
  9894. // Methods
  9895. Collider.prototype._initialize = function (source, dir, e) {
  9896. this.velocity = dir;
  9897. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9898. this.basePoint = source;
  9899. source.multiplyToRef(this.radius, this.basePointWorld);
  9900. dir.multiplyToRef(this.radius, this.velocityWorld);
  9901. this.velocityWorldLength = this.velocityWorld.length();
  9902. this.epsilon = e;
  9903. this.collisionFound = false;
  9904. };
  9905. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9906. pa.subtractToRef(point, this._tempVector);
  9907. pb.subtractToRef(point, this._tempVector2);
  9908. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9909. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9910. if (d < 0)
  9911. return false;
  9912. pc.subtractToRef(point, this._tempVector3);
  9913. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9914. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9915. if (d < 0)
  9916. return false;
  9917. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9918. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9919. return d >= 0;
  9920. };
  9921. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9922. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9923. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9924. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9925. return false;
  9926. }
  9927. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9928. return false;
  9929. return true;
  9930. };
  9931. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9932. var t0;
  9933. var embeddedInPlane = false;
  9934. //defensive programming, actually not needed.
  9935. if (!trianglePlaneArray) {
  9936. trianglePlaneArray = [];
  9937. }
  9938. if (!trianglePlaneArray[faceIndex]) {
  9939. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9940. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9941. }
  9942. var trianglePlane = trianglePlaneArray[faceIndex];
  9943. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9944. return;
  9945. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9946. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9947. if (normalDotVelocity == 0) {
  9948. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9949. return;
  9950. embeddedInPlane = true;
  9951. t0 = 0;
  9952. }
  9953. else {
  9954. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9955. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9956. if (t0 > t1) {
  9957. var temp = t1;
  9958. t1 = t0;
  9959. t0 = temp;
  9960. }
  9961. if (t0 > 1.0 || t1 < 0.0)
  9962. return;
  9963. if (t0 < 0)
  9964. t0 = 0;
  9965. if (t0 > 1.0)
  9966. t0 = 1.0;
  9967. }
  9968. this._collisionPoint.copyFromFloats(0, 0, 0);
  9969. var found = false;
  9970. var t = 1.0;
  9971. if (!embeddedInPlane) {
  9972. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9973. this.velocity.scaleToRef(t0, this._tempVector);
  9974. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9975. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9976. found = true;
  9977. t = t0;
  9978. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9979. }
  9980. }
  9981. if (!found) {
  9982. var velocitySquaredLength = this.velocity.lengthSquared();
  9983. var a = velocitySquaredLength;
  9984. this.basePoint.subtractToRef(p1, this._tempVector);
  9985. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9986. var c = this._tempVector.lengthSquared() - 1.0;
  9987. var lowestRoot = getLowestRoot(a, b, c, t);
  9988. if (lowestRoot.found) {
  9989. t = lowestRoot.root;
  9990. found = true;
  9991. this._collisionPoint.copyFrom(p1);
  9992. }
  9993. this.basePoint.subtractToRef(p2, this._tempVector);
  9994. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9995. c = this._tempVector.lengthSquared() - 1.0;
  9996. lowestRoot = getLowestRoot(a, b, c, t);
  9997. if (lowestRoot.found) {
  9998. t = lowestRoot.root;
  9999. found = true;
  10000. this._collisionPoint.copyFrom(p2);
  10001. }
  10002. this.basePoint.subtractToRef(p3, this._tempVector);
  10003. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10004. c = this._tempVector.lengthSquared() - 1.0;
  10005. lowestRoot = getLowestRoot(a, b, c, t);
  10006. if (lowestRoot.found) {
  10007. t = lowestRoot.root;
  10008. found = true;
  10009. this._collisionPoint.copyFrom(p3);
  10010. }
  10011. p2.subtractToRef(p1, this._edge);
  10012. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10013. var edgeSquaredLength = this._edge.lengthSquared();
  10014. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10015. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10016. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10017. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10018. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10019. lowestRoot = getLowestRoot(a, b, c, t);
  10020. if (lowestRoot.found) {
  10021. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10022. if (f >= 0.0 && f <= 1.0) {
  10023. t = lowestRoot.root;
  10024. found = true;
  10025. this._edge.scaleInPlace(f);
  10026. p1.addToRef(this._edge, this._collisionPoint);
  10027. }
  10028. }
  10029. p3.subtractToRef(p2, this._edge);
  10030. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10031. edgeSquaredLength = this._edge.lengthSquared();
  10032. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10033. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10034. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10035. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10036. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10037. lowestRoot = getLowestRoot(a, b, c, t);
  10038. if (lowestRoot.found) {
  10039. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10040. if (f >= 0.0 && f <= 1.0) {
  10041. t = lowestRoot.root;
  10042. found = true;
  10043. this._edge.scaleInPlace(f);
  10044. p2.addToRef(this._edge, this._collisionPoint);
  10045. }
  10046. }
  10047. p1.subtractToRef(p3, this._edge);
  10048. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10049. edgeSquaredLength = this._edge.lengthSquared();
  10050. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10051. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10052. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10053. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10054. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10055. lowestRoot = getLowestRoot(a, b, c, t);
  10056. if (lowestRoot.found) {
  10057. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10058. if (f >= 0.0 && f <= 1.0) {
  10059. t = lowestRoot.root;
  10060. found = true;
  10061. this._edge.scaleInPlace(f);
  10062. p3.addToRef(this._edge, this._collisionPoint);
  10063. }
  10064. }
  10065. }
  10066. if (found) {
  10067. var distToCollision = t * this.velocity.length();
  10068. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10069. if (!this.intersectionPoint) {
  10070. this.intersectionPoint = this._collisionPoint.clone();
  10071. }
  10072. else {
  10073. this.intersectionPoint.copyFrom(this._collisionPoint);
  10074. }
  10075. this.nearestDistance = distToCollision;
  10076. this.collisionFound = true;
  10077. }
  10078. }
  10079. };
  10080. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10081. for (var i = indexStart; i < indexEnd; i += 3) {
  10082. var p1 = pts[indices[i] - decal];
  10083. var p2 = pts[indices[i + 1] - decal];
  10084. var p3 = pts[indices[i + 2] - decal];
  10085. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10086. }
  10087. };
  10088. Collider.prototype._getResponse = function (pos, vel) {
  10089. pos.addToRef(vel, this._destinationPoint);
  10090. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10091. this.basePoint.addToRef(vel, pos);
  10092. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10093. this._slidePlaneNormal.normalize();
  10094. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10095. pos.addInPlace(this._displacementVector);
  10096. this.intersectionPoint.addInPlace(this._displacementVector);
  10097. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10098. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10099. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10100. };
  10101. return Collider;
  10102. })();
  10103. BABYLON.Collider = Collider;
  10104. })(BABYLON || (BABYLON = {}));
  10105. var BABYLON;
  10106. (function (BABYLON) {
  10107. //WebWorker code will be inserted to this variable.
  10108. BABYLON.CollisionWorker = "";
  10109. (function (WorkerTaskType) {
  10110. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10111. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10112. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10113. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10114. var WorkerTaskType = BABYLON.WorkerTaskType;
  10115. (function (WorkerReplyType) {
  10116. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10117. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10118. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10119. var WorkerReplyType = BABYLON.WorkerReplyType;
  10120. var CollisionCoordinatorWorker = (function () {
  10121. function CollisionCoordinatorWorker() {
  10122. var _this = this;
  10123. this._scaledPosition = BABYLON.Vector3.Zero();
  10124. this._scaledVelocity = BABYLON.Vector3.Zero();
  10125. this.onMeshUpdated = function (mesh) {
  10126. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10127. };
  10128. this.onGeometryUpdated = function (geometry) {
  10129. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10130. };
  10131. this._afterRender = function () {
  10132. if (!_this._init)
  10133. return;
  10134. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10135. return;
  10136. }
  10137. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10138. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10139. if (_this._runningUpdated > 4) {
  10140. return;
  10141. }
  10142. ++_this._runningUpdated;
  10143. var payload = {
  10144. updatedMeshes: _this._addUpdateMeshesList,
  10145. updatedGeometries: _this._addUpdateGeometriesList,
  10146. removedGeometries: _this._toRemoveGeometryArray,
  10147. removedMeshes: _this._toRemoveMeshesArray
  10148. };
  10149. var message = {
  10150. payload: payload,
  10151. taskType: WorkerTaskType.UPDATE
  10152. };
  10153. var serializable = [];
  10154. for (var id in payload.updatedGeometries) {
  10155. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10156. //prepare transferables
  10157. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10158. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10159. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10160. }
  10161. }
  10162. _this._worker.postMessage(message, serializable);
  10163. _this._addUpdateMeshesList = {};
  10164. _this._addUpdateGeometriesList = {};
  10165. _this._toRemoveGeometryArray = [];
  10166. _this._toRemoveMeshesArray = [];
  10167. };
  10168. this._onMessageFromWorker = function (e) {
  10169. var returnData = e.data;
  10170. if (returnData.error != WorkerReplyType.SUCCESS) {
  10171. //TODO what errors can be returned from the worker?
  10172. BABYLON.Tools.Warn("error returned from worker!");
  10173. return;
  10174. }
  10175. switch (returnData.taskType) {
  10176. case WorkerTaskType.INIT:
  10177. _this._init = true;
  10178. //Update the worked with ALL of the scene's current state
  10179. _this._scene.meshes.forEach(function (mesh) {
  10180. _this.onMeshAdded(mesh);
  10181. });
  10182. _this._scene.getGeometries().forEach(function (geometry) {
  10183. _this.onGeometryAdded(geometry);
  10184. });
  10185. break;
  10186. case WorkerTaskType.UPDATE:
  10187. _this._runningUpdated--;
  10188. break;
  10189. case WorkerTaskType.COLLIDE:
  10190. _this._runningCollisionTask = false;
  10191. var returnPayload = returnData.payload;
  10192. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10193. return;
  10194. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10195. //cleanup
  10196. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10197. break;
  10198. }
  10199. };
  10200. this._collisionsCallbackArray = [];
  10201. this._init = false;
  10202. this._runningUpdated = 0;
  10203. this._runningCollisionTask = false;
  10204. this._addUpdateMeshesList = {};
  10205. this._addUpdateGeometriesList = {};
  10206. this._toRemoveGeometryArray = [];
  10207. this._toRemoveMeshesArray = [];
  10208. }
  10209. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10210. if (!this._init)
  10211. return;
  10212. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10213. return;
  10214. position.divideToRef(collider.radius, this._scaledPosition);
  10215. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10216. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10217. var payload = {
  10218. collider: {
  10219. position: this._scaledPosition.asArray(),
  10220. velocity: this._scaledVelocity.asArray(),
  10221. radius: collider.radius.asArray()
  10222. },
  10223. collisionId: collisionIndex,
  10224. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10225. maximumRetry: maximumRetry
  10226. };
  10227. var message = {
  10228. payload: payload,
  10229. taskType: WorkerTaskType.COLLIDE
  10230. };
  10231. this._worker.postMessage(message);
  10232. };
  10233. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10234. this._scene = scene;
  10235. this._scene.registerAfterRender(this._afterRender);
  10236. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10237. this._worker = new Worker(workerUrl);
  10238. this._worker.onmessage = this._onMessageFromWorker;
  10239. var message = {
  10240. payload: {},
  10241. taskType: WorkerTaskType.INIT
  10242. };
  10243. this._worker.postMessage(message);
  10244. };
  10245. CollisionCoordinatorWorker.prototype.destroy = function () {
  10246. this._scene.unregisterAfterRender(this._afterRender);
  10247. this._worker.terminate();
  10248. };
  10249. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10250. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10251. this.onMeshUpdated(mesh);
  10252. };
  10253. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10254. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10255. };
  10256. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10257. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10258. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10259. this.onGeometryUpdated(geometry);
  10260. };
  10261. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10262. this._toRemoveGeometryArray.push(geometry.id);
  10263. };
  10264. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10265. var submeshes = [];
  10266. if (mesh.subMeshes) {
  10267. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10268. return {
  10269. position: idx,
  10270. verticesStart: sm.verticesStart,
  10271. verticesCount: sm.verticesCount,
  10272. indexStart: sm.indexStart,
  10273. indexCount: sm.indexCount,
  10274. hasMaterial: !!sm.getMaterial(),
  10275. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10276. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10277. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10278. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10279. };
  10280. });
  10281. }
  10282. var geometryId = null;
  10283. if (mesh instanceof BABYLON.Mesh) {
  10284. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10285. }
  10286. else if (mesh instanceof BABYLON.InstancedMesh) {
  10287. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10288. }
  10289. return {
  10290. uniqueId: mesh.uniqueId,
  10291. id: mesh.id,
  10292. name: mesh.name,
  10293. geometryId: geometryId,
  10294. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10295. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10296. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10297. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10298. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10299. subMeshes: submeshes,
  10300. checkCollisions: mesh.checkCollisions
  10301. };
  10302. };
  10303. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10304. return {
  10305. id: geometry.id,
  10306. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10307. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10308. indices: new Int32Array(geometry.getIndices() || []),
  10309. };
  10310. };
  10311. return CollisionCoordinatorWorker;
  10312. })();
  10313. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10314. var CollisionCoordinatorLegacy = (function () {
  10315. function CollisionCoordinatorLegacy() {
  10316. this._scaledPosition = BABYLON.Vector3.Zero();
  10317. this._scaledVelocity = BABYLON.Vector3.Zero();
  10318. this._finalPosition = BABYLON.Vector3.Zero();
  10319. }
  10320. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10321. position.divideToRef(collider.radius, this._scaledPosition);
  10322. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10323. collider.collidedMesh = null;
  10324. collider.retry = 0;
  10325. collider.initialVelocity = this._scaledVelocity;
  10326. collider.initialPosition = this._scaledPosition;
  10327. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10328. this._finalPosition.multiplyInPlace(collider.radius);
  10329. //run the callback
  10330. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10331. };
  10332. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10333. this._scene = scene;
  10334. };
  10335. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10336. //Legacy need no destruction method.
  10337. };
  10338. //No update in legacy mode
  10339. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10340. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10341. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10342. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10343. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10344. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10345. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10346. if (excludedMesh === void 0) { excludedMesh = null; }
  10347. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10348. if (collider.retry >= maximumRetry) {
  10349. finalPosition.copyFrom(position);
  10350. return;
  10351. }
  10352. collider._initialize(position, velocity, closeDistance);
  10353. // Check all meshes
  10354. for (var index = 0; index < this._scene.meshes.length; index++) {
  10355. var mesh = this._scene.meshes[index];
  10356. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10357. mesh._checkCollision(collider);
  10358. }
  10359. }
  10360. if (!collider.collisionFound) {
  10361. position.addToRef(velocity, finalPosition);
  10362. return;
  10363. }
  10364. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10365. collider._getResponse(position, velocity);
  10366. }
  10367. if (velocity.length() <= closeDistance) {
  10368. finalPosition.copyFrom(position);
  10369. return;
  10370. }
  10371. collider.retry++;
  10372. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10373. };
  10374. return CollisionCoordinatorLegacy;
  10375. })();
  10376. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10377. })(BABYLON || (BABYLON = {}));
  10378. var BABYLON;
  10379. (function (BABYLON) {
  10380. var Camera = (function (_super) {
  10381. __extends(Camera, _super);
  10382. function Camera(name, position, scene) {
  10383. _super.call(this, name, scene);
  10384. this.upVector = BABYLON.Vector3.Up();
  10385. this.orthoLeft = null;
  10386. this.orthoRight = null;
  10387. this.orthoBottom = null;
  10388. this.orthoTop = null;
  10389. this.fov = 0.8;
  10390. this.minZ = 1.0;
  10391. this.maxZ = 10000.0;
  10392. this.inertia = 0.9;
  10393. this.mode = Camera.PERSPECTIVE_CAMERA;
  10394. this.isIntermediate = false;
  10395. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10396. this.layerMask = 0x0FFFFFFF;
  10397. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10398. // Camera rig members
  10399. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10400. this._rigCameras = new Array();
  10401. // Cache
  10402. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10403. this._projectionMatrix = new BABYLON.Matrix();
  10404. this._postProcesses = new Array();
  10405. this._postProcessesTakenIndices = [];
  10406. this._activeMeshes = new BABYLON.SmartArray(256);
  10407. this._globalPosition = BABYLON.Vector3.Zero();
  10408. scene.addCamera(this);
  10409. if (!scene.activeCamera) {
  10410. scene.activeCamera = this;
  10411. }
  10412. this.position = position;
  10413. }
  10414. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10415. get: function () {
  10416. return Camera._PERSPECTIVE_CAMERA;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10422. get: function () {
  10423. return Camera._ORTHOGRAPHIC_CAMERA;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10429. get: function () {
  10430. return Camera._FOVMODE_VERTICAL_FIXED;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10436. get: function () {
  10437. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10443. get: function () {
  10444. return Camera._RIG_MODE_NONE;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10450. get: function () {
  10451. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10457. get: function () {
  10458. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10459. },
  10460. enumerable: true,
  10461. configurable: true
  10462. });
  10463. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10464. get: function () {
  10465. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10466. },
  10467. enumerable: true,
  10468. configurable: true
  10469. });
  10470. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10471. get: function () {
  10472. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10473. },
  10474. enumerable: true,
  10475. configurable: true
  10476. });
  10477. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10478. get: function () {
  10479. return Camera._RIG_MODE_VR;
  10480. },
  10481. enumerable: true,
  10482. configurable: true
  10483. });
  10484. Object.defineProperty(Camera.prototype, "globalPosition", {
  10485. get: function () {
  10486. return this._globalPosition;
  10487. },
  10488. enumerable: true,
  10489. configurable: true
  10490. });
  10491. Camera.prototype.getActiveMeshes = function () {
  10492. return this._activeMeshes;
  10493. };
  10494. Camera.prototype.isActiveMesh = function (mesh) {
  10495. return (this._activeMeshes.indexOf(mesh) !== -1);
  10496. };
  10497. //Cache
  10498. Camera.prototype._initCache = function () {
  10499. _super.prototype._initCache.call(this);
  10500. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10501. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10502. this._cache.mode = undefined;
  10503. this._cache.minZ = undefined;
  10504. this._cache.maxZ = undefined;
  10505. this._cache.fov = undefined;
  10506. this._cache.aspectRatio = undefined;
  10507. this._cache.orthoLeft = undefined;
  10508. this._cache.orthoRight = undefined;
  10509. this._cache.orthoBottom = undefined;
  10510. this._cache.orthoTop = undefined;
  10511. this._cache.renderWidth = undefined;
  10512. this._cache.renderHeight = undefined;
  10513. };
  10514. Camera.prototype._updateCache = function (ignoreParentClass) {
  10515. if (!ignoreParentClass) {
  10516. _super.prototype._updateCache.call(this);
  10517. }
  10518. var engine = this.getEngine();
  10519. this._cache.position.copyFrom(this.position);
  10520. this._cache.upVector.copyFrom(this.upVector);
  10521. this._cache.mode = this.mode;
  10522. this._cache.minZ = this.minZ;
  10523. this._cache.maxZ = this.maxZ;
  10524. this._cache.fov = this.fov;
  10525. this._cache.aspectRatio = engine.getAspectRatio(this);
  10526. this._cache.orthoLeft = this.orthoLeft;
  10527. this._cache.orthoRight = this.orthoRight;
  10528. this._cache.orthoBottom = this.orthoBottom;
  10529. this._cache.orthoTop = this.orthoTop;
  10530. this._cache.renderWidth = engine.getRenderWidth();
  10531. this._cache.renderHeight = engine.getRenderHeight();
  10532. };
  10533. Camera.prototype._updateFromScene = function () {
  10534. this.updateCache();
  10535. this._update();
  10536. };
  10537. // Synchronized
  10538. Camera.prototype._isSynchronized = function () {
  10539. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10540. };
  10541. Camera.prototype._isSynchronizedViewMatrix = function () {
  10542. if (!_super.prototype._isSynchronized.call(this))
  10543. return false;
  10544. return this._cache.position.equals(this.position)
  10545. && this._cache.upVector.equals(this.upVector)
  10546. && this.isSynchronizedWithParent();
  10547. };
  10548. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10549. var check = this._cache.mode === this.mode
  10550. && this._cache.minZ === this.minZ
  10551. && this._cache.maxZ === this.maxZ;
  10552. if (!check) {
  10553. return false;
  10554. }
  10555. var engine = this.getEngine();
  10556. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10557. check = this._cache.fov === this.fov
  10558. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10559. }
  10560. else {
  10561. check = this._cache.orthoLeft === this.orthoLeft
  10562. && this._cache.orthoRight === this.orthoRight
  10563. && this._cache.orthoBottom === this.orthoBottom
  10564. && this._cache.orthoTop === this.orthoTop
  10565. && this._cache.renderWidth === engine.getRenderWidth()
  10566. && this._cache.renderHeight === engine.getRenderHeight();
  10567. }
  10568. return check;
  10569. };
  10570. // Controls
  10571. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10572. };
  10573. Camera.prototype.detachControl = function (element) {
  10574. };
  10575. Camera.prototype._update = function () {
  10576. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10577. this._updateRigCameras();
  10578. }
  10579. this._checkInputs();
  10580. };
  10581. Camera.prototype._checkInputs = function () {
  10582. };
  10583. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10584. if (insertAt === void 0) { insertAt = null; }
  10585. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10586. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10587. return 0;
  10588. }
  10589. if (insertAt == null || insertAt < 0) {
  10590. this._postProcesses.push(postProcess);
  10591. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10592. return this._postProcesses.length - 1;
  10593. }
  10594. var add = 0;
  10595. var i;
  10596. var start;
  10597. if (this._postProcesses[insertAt]) {
  10598. start = this._postProcesses.length - 1;
  10599. for (i = start; i >= insertAt + 1; --i) {
  10600. this._postProcesses[i + 1] = this._postProcesses[i];
  10601. }
  10602. add = 1;
  10603. }
  10604. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10605. if (this._postProcessesTakenIndices[i] < insertAt) {
  10606. continue;
  10607. }
  10608. start = this._postProcessesTakenIndices.length - 1;
  10609. for (var j = start; j >= i; --j) {
  10610. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10611. }
  10612. this._postProcessesTakenIndices[i] = insertAt;
  10613. break;
  10614. }
  10615. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10616. this._postProcessesTakenIndices.push(insertAt);
  10617. }
  10618. var result = insertAt + add;
  10619. this._postProcesses[result] = postProcess;
  10620. return result;
  10621. };
  10622. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10623. if (atIndices === void 0) { atIndices = null; }
  10624. var result = [];
  10625. var i;
  10626. var index;
  10627. if (!atIndices) {
  10628. var length = this._postProcesses.length;
  10629. for (i = 0; i < length; i++) {
  10630. if (this._postProcesses[i] !== postProcess) {
  10631. continue;
  10632. }
  10633. delete this._postProcesses[i];
  10634. index = this._postProcessesTakenIndices.indexOf(i);
  10635. this._postProcessesTakenIndices.splice(index, 1);
  10636. }
  10637. }
  10638. else {
  10639. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10640. for (i = 0; i < atIndices.length; i++) {
  10641. var foundPostProcess = this._postProcesses[atIndices[i]];
  10642. if (foundPostProcess !== postProcess) {
  10643. result.push(i);
  10644. continue;
  10645. }
  10646. delete this._postProcesses[atIndices[i]];
  10647. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10648. this._postProcessesTakenIndices.splice(index, 1);
  10649. }
  10650. }
  10651. return result;
  10652. };
  10653. Camera.prototype.getWorldMatrix = function () {
  10654. if (!this._worldMatrix) {
  10655. this._worldMatrix = BABYLON.Matrix.Identity();
  10656. }
  10657. var viewMatrix = this.getViewMatrix();
  10658. viewMatrix.invertToRef(this._worldMatrix);
  10659. return this._worldMatrix;
  10660. };
  10661. Camera.prototype._getViewMatrix = function () {
  10662. return BABYLON.Matrix.Identity();
  10663. };
  10664. Camera.prototype.getViewMatrix = function (force) {
  10665. this._computedViewMatrix = this._computeViewMatrix(force);
  10666. if (!force && this._isSynchronizedViewMatrix()) {
  10667. return this._computedViewMatrix;
  10668. }
  10669. if (!this.parent || !this.parent.getWorldMatrix) {
  10670. this._globalPosition.copyFrom(this.position);
  10671. }
  10672. else {
  10673. if (!this._worldMatrix) {
  10674. this._worldMatrix = BABYLON.Matrix.Identity();
  10675. }
  10676. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10677. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10678. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10679. this._computedViewMatrix.invert();
  10680. this._markSyncedWithParent();
  10681. }
  10682. this._currentRenderId = this.getScene().getRenderId();
  10683. return this._computedViewMatrix;
  10684. };
  10685. Camera.prototype._computeViewMatrix = function (force) {
  10686. if (!force && this._isSynchronizedViewMatrix()) {
  10687. return this._computedViewMatrix;
  10688. }
  10689. this._computedViewMatrix = this._getViewMatrix();
  10690. this._currentRenderId = this.getScene().getRenderId();
  10691. return this._computedViewMatrix;
  10692. };
  10693. Camera.prototype.getProjectionMatrix = function (force) {
  10694. if (!force && this._isSynchronizedProjectionMatrix()) {
  10695. return this._projectionMatrix;
  10696. }
  10697. var engine = this.getEngine();
  10698. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10699. if (this.minZ <= 0) {
  10700. this.minZ = 0.1;
  10701. }
  10702. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10703. return this._projectionMatrix;
  10704. }
  10705. var halfWidth = engine.getRenderWidth() / 2.0;
  10706. var halfHeight = engine.getRenderHeight() / 2.0;
  10707. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10708. return this._projectionMatrix;
  10709. };
  10710. Camera.prototype.dispose = function () {
  10711. // Animations
  10712. this.getScene().stopAnimation(this);
  10713. // Remove from scene
  10714. this.getScene().removeCamera(this);
  10715. while (this._rigCameras.length > 0) {
  10716. this._rigCameras.pop().dispose();
  10717. }
  10718. // Postprocesses
  10719. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10720. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10721. }
  10722. };
  10723. // ---- Camera rigs section ----
  10724. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10725. while (this._rigCameras.length > 0) {
  10726. this._rigCameras.pop().dispose();
  10727. }
  10728. this.cameraRigMode = mode;
  10729. this._cameraRigParams = {};
  10730. switch (this.cameraRigMode) {
  10731. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10732. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10733. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10734. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10735. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10736. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10737. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10738. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10739. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10740. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10741. break;
  10742. }
  10743. var postProcesses = new Array();
  10744. switch (this.cameraRigMode) {
  10745. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10746. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10747. this._rigCameras[0].isIntermediate = true;
  10748. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10749. postProcesses[1].onApply = function (effect) {
  10750. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10751. };
  10752. break;
  10753. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10754. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10755. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10756. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10757. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10758. var secondCamIndex = 1 - firstCamIndex;
  10759. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10760. this._rigCameras[firstCamIndex].isIntermediate = true;
  10761. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10762. break;
  10763. case Camera.RIG_MODE_VR:
  10764. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10765. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10766. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10767. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10768. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10769. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10770. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10771. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10772. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10773. if (metrics.compensateDistortion) {
  10774. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10775. }
  10776. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10777. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10778. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10779. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10780. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10781. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10782. if (metrics.compensateDistortion) {
  10783. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10784. }
  10785. break;
  10786. }
  10787. this._update();
  10788. };
  10789. Camera.prototype._getVRProjectionMatrix = function () {
  10790. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10791. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10792. return this._projectionMatrix;
  10793. };
  10794. Camera.prototype.setCameraRigParameter = function (name, value) {
  10795. this._cameraRigParams[name] = value;
  10796. //provisionnally:
  10797. if (name === "interaxialDistance") {
  10798. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10799. }
  10800. };
  10801. /**
  10802. * May needs to be overridden by children so sub has required properties to be copied
  10803. */
  10804. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10805. return null;
  10806. };
  10807. /**
  10808. * May needs to be overridden by children
  10809. */
  10810. Camera.prototype._updateRigCameras = function () {
  10811. for (var i = 0; i < this._rigCameras.length; i++) {
  10812. this._rigCameras[i].minZ = this.minZ;
  10813. this._rigCameras[i].maxZ = this.maxZ;
  10814. this._rigCameras[i].fov = this.fov;
  10815. }
  10816. // only update viewport when ANAGLYPH
  10817. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10818. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10819. }
  10820. };
  10821. Camera.prototype.serialize = function () {
  10822. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10823. // Type
  10824. serializationObject.type = this.getTypeName();
  10825. // Parent
  10826. if (this.parent) {
  10827. serializationObject.parentId = this.parent.id;
  10828. }
  10829. // Animations
  10830. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10831. serializationObject.ranges = this.serializeAnimationRanges();
  10832. return serializationObject;
  10833. };
  10834. Camera.prototype.getTypeName = function () {
  10835. return "Camera";
  10836. };
  10837. Camera.prototype.clone = function (name) {
  10838. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10839. };
  10840. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10841. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10842. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10843. switch (type) {
  10844. case "ArcRotateCamera":
  10845. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10846. case "DeviceOrientationCamera":
  10847. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10848. case "FollowCamera":
  10849. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10850. case "ArcFollowCamera":
  10851. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10852. case "GamepadCamera":
  10853. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10854. case "TouchCamera":
  10855. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10856. case "VirtualJoysticksCamera":
  10857. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10858. case "WebVRFreeCamera":
  10859. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10860. case "VRDeviceOrientationFreeCamera":
  10861. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10862. case "AnaglyphArcRotateCamera":
  10863. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10864. case "AnaglyphFreeCamera":
  10865. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10866. case "AnaglyphGamepadCamera":
  10867. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10868. case "AnaglyphUniversalCamera":
  10869. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10870. case "StereoscopicArcRotateCamera":
  10871. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10872. case "StereoscopicFreeCamera":
  10873. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10874. case "StereoscopicGamepadCamera":
  10875. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10876. case "StereoscopicUniversalCamera":
  10877. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10878. case "FreeCamera":
  10879. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10880. default:
  10881. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10882. }
  10883. };
  10884. Camera.Parse = function (parsedCamera, scene) {
  10885. var type = parsedCamera.type;
  10886. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10887. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10888. // Parent
  10889. if (parsedCamera.parentId) {
  10890. camera._waitingParentId = parsedCamera.parentId;
  10891. }
  10892. // Target
  10893. if (parsedCamera.target) {
  10894. if (camera.setTarget) {
  10895. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10896. }
  10897. }
  10898. // Apply 3d rig, when found
  10899. if (parsedCamera.cameraRigMode) {
  10900. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10901. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10902. }
  10903. // Animations
  10904. if (parsedCamera.animations) {
  10905. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10906. var parsedAnimation = parsedCamera.animations[animationIndex];
  10907. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10908. }
  10909. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10910. }
  10911. if (parsedCamera.autoAnimate) {
  10912. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10913. }
  10914. return camera;
  10915. };
  10916. // Statics
  10917. Camera._PERSPECTIVE_CAMERA = 0;
  10918. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10919. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10920. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10921. Camera._RIG_MODE_NONE = 0;
  10922. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10923. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10924. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10925. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10926. Camera._RIG_MODE_VR = 20;
  10927. __decorate([
  10928. BABYLON.serializeAsVector3()
  10929. ], Camera.prototype, "position", void 0);
  10930. __decorate([
  10931. BABYLON.serialize()
  10932. ], Camera.prototype, "upVector", void 0);
  10933. __decorate([
  10934. BABYLON.serialize()
  10935. ], Camera.prototype, "orthoLeft", void 0);
  10936. __decorate([
  10937. BABYLON.serialize()
  10938. ], Camera.prototype, "orthoRight", void 0);
  10939. __decorate([
  10940. BABYLON.serialize()
  10941. ], Camera.prototype, "orthoBottom", void 0);
  10942. __decorate([
  10943. BABYLON.serialize()
  10944. ], Camera.prototype, "orthoTop", void 0);
  10945. __decorate([
  10946. BABYLON.serialize()
  10947. ], Camera.prototype, "fov", void 0);
  10948. __decorate([
  10949. BABYLON.serialize()
  10950. ], Camera.prototype, "minZ", void 0);
  10951. __decorate([
  10952. BABYLON.serialize()
  10953. ], Camera.prototype, "maxZ", void 0);
  10954. __decorate([
  10955. BABYLON.serialize()
  10956. ], Camera.prototype, "inertia", void 0);
  10957. __decorate([
  10958. BABYLON.serialize()
  10959. ], Camera.prototype, "mode", void 0);
  10960. __decorate([
  10961. BABYLON.serialize()
  10962. ], Camera.prototype, "layerMask", void 0);
  10963. __decorate([
  10964. BABYLON.serialize()
  10965. ], Camera.prototype, "fovMode", void 0);
  10966. __decorate([
  10967. BABYLON.serialize()
  10968. ], Camera.prototype, "cameraRigMode", void 0);
  10969. __decorate([
  10970. BABYLON.serialize()
  10971. ], Camera.prototype, "interaxialDistance", void 0);
  10972. __decorate([
  10973. BABYLON.serialize()
  10974. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10975. return Camera;
  10976. })(BABYLON.Node);
  10977. BABYLON.Camera = Camera;
  10978. })(BABYLON || (BABYLON = {}));
  10979. var BABYLON;
  10980. (function (BABYLON) {
  10981. var TargetCamera = (function (_super) {
  10982. __extends(TargetCamera, _super);
  10983. function TargetCamera(name, position, scene) {
  10984. _super.call(this, name, position, scene);
  10985. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10986. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10987. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10988. this.speed = 2.0;
  10989. this.noRotationConstraint = false;
  10990. this.lockedTarget = null;
  10991. this._currentTarget = BABYLON.Vector3.Zero();
  10992. this._viewMatrix = BABYLON.Matrix.Zero();
  10993. this._camMatrix = BABYLON.Matrix.Zero();
  10994. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10995. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10996. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10997. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10998. this._lookAtTemp = BABYLON.Matrix.Zero();
  10999. this._tempMatrix = BABYLON.Matrix.Zero();
  11000. }
  11001. TargetCamera.prototype.getFrontPosition = function (distance) {
  11002. var direction = this.getTarget().subtract(this.position);
  11003. direction.normalize();
  11004. direction.scaleInPlace(distance);
  11005. return this.globalPosition.add(direction);
  11006. };
  11007. TargetCamera.prototype._getLockedTargetPosition = function () {
  11008. if (!this.lockedTarget) {
  11009. return null;
  11010. }
  11011. return this.lockedTarget.position || this.lockedTarget;
  11012. };
  11013. // Cache
  11014. TargetCamera.prototype._initCache = function () {
  11015. _super.prototype._initCache.call(this);
  11016. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11017. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11018. };
  11019. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11020. if (!ignoreParentClass) {
  11021. _super.prototype._updateCache.call(this);
  11022. }
  11023. var lockedTargetPosition = this._getLockedTargetPosition();
  11024. if (!lockedTargetPosition) {
  11025. this._cache.lockedTarget = null;
  11026. }
  11027. else {
  11028. if (!this._cache.lockedTarget) {
  11029. this._cache.lockedTarget = lockedTargetPosition.clone();
  11030. }
  11031. else {
  11032. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11033. }
  11034. }
  11035. this._cache.rotation.copyFrom(this.rotation);
  11036. };
  11037. // Synchronized
  11038. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11039. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11040. return false;
  11041. }
  11042. var lockedTargetPosition = this._getLockedTargetPosition();
  11043. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11044. && this._cache.rotation.equals(this.rotation);
  11045. };
  11046. // Methods
  11047. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11048. var engine = this.getEngine();
  11049. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11050. };
  11051. // Target
  11052. TargetCamera.prototype.setTarget = function (target) {
  11053. this.upVector.normalize();
  11054. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11055. this._camMatrix.invert();
  11056. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11057. var vDir = target.subtract(this.position);
  11058. if (vDir.x >= 0.0) {
  11059. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11060. }
  11061. else {
  11062. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11063. }
  11064. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11065. if (isNaN(this.rotation.x)) {
  11066. this.rotation.x = 0;
  11067. }
  11068. if (isNaN(this.rotation.y)) {
  11069. this.rotation.y = 0;
  11070. }
  11071. if (isNaN(this.rotation.z)) {
  11072. this.rotation.z = 0;
  11073. }
  11074. };
  11075. TargetCamera.prototype.getTarget = function () {
  11076. return this._currentTarget;
  11077. };
  11078. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11079. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11080. };
  11081. TargetCamera.prototype._updatePosition = function () {
  11082. this.position.addInPlace(this.cameraDirection);
  11083. };
  11084. TargetCamera.prototype._checkInputs = function () {
  11085. var needToMove = this._decideIfNeedsToMove();
  11086. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11087. // Move
  11088. if (needToMove) {
  11089. this._updatePosition();
  11090. }
  11091. // Rotate
  11092. if (needToRotate) {
  11093. this.rotation.x += this.cameraRotation.x;
  11094. this.rotation.y += this.cameraRotation.y;
  11095. if (!this.noRotationConstraint) {
  11096. var limit = (Math.PI / 2) * 0.95;
  11097. if (this.rotation.x > limit)
  11098. this.rotation.x = limit;
  11099. if (this.rotation.x < -limit)
  11100. this.rotation.x = -limit;
  11101. }
  11102. }
  11103. // Inertia
  11104. if (needToMove) {
  11105. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11106. this.cameraDirection.x = 0;
  11107. }
  11108. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11109. this.cameraDirection.y = 0;
  11110. }
  11111. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11112. this.cameraDirection.z = 0;
  11113. }
  11114. this.cameraDirection.scaleInPlace(this.inertia);
  11115. }
  11116. if (needToRotate) {
  11117. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11118. this.cameraRotation.x = 0;
  11119. }
  11120. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11121. this.cameraRotation.y = 0;
  11122. }
  11123. this.cameraRotation.scaleInPlace(this.inertia);
  11124. }
  11125. _super.prototype._checkInputs.call(this);
  11126. };
  11127. TargetCamera.prototype._getViewMatrix = function () {
  11128. if (!this.lockedTarget) {
  11129. // Compute
  11130. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11131. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11132. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11133. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11134. this._lookAtTemp.invert();
  11135. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11136. }
  11137. else {
  11138. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11139. }
  11140. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11141. // Computing target and final matrix
  11142. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11143. }
  11144. else {
  11145. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11146. }
  11147. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11148. return this._viewMatrix;
  11149. };
  11150. TargetCamera.prototype._getVRViewMatrix = function () {
  11151. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11152. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11153. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11154. // Computing target and final matrix
  11155. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11156. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11157. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11158. return this._viewMatrix;
  11159. };
  11160. /**
  11161. * @override
  11162. * Override Camera.createRigCamera
  11163. */
  11164. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11165. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11166. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11167. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11168. rigCamera._cameraRigParams = {};
  11169. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11170. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11171. }
  11172. return rigCamera;
  11173. }
  11174. return null;
  11175. };
  11176. /**
  11177. * @override
  11178. * Override Camera._updateRigCameras
  11179. */
  11180. TargetCamera.prototype._updateRigCameras = function () {
  11181. switch (this.cameraRigMode) {
  11182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11186. case BABYLON.Camera.RIG_MODE_VR:
  11187. var camLeft = this._rigCameras[0];
  11188. var camRight = this._rigCameras[1];
  11189. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11190. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11191. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11192. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11193. camLeft.position.copyFrom(this.position);
  11194. camRight.position.copyFrom(this.position);
  11195. }
  11196. else {
  11197. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11198. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11199. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11200. camLeft.setTarget(this.getTarget());
  11201. camRight.setTarget(this.getTarget());
  11202. }
  11203. break;
  11204. }
  11205. _super.prototype._updateRigCameras.call(this);
  11206. };
  11207. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11208. if (!this._rigCamTransformMatrix) {
  11209. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11210. }
  11211. var target = this.getTarget();
  11212. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11213. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11215. };
  11216. TargetCamera.prototype.getTypeName = function () {
  11217. return "TargetCamera";
  11218. };
  11219. __decorate([
  11220. BABYLON.serializeAsVector3()
  11221. ], TargetCamera.prototype, "rotation", void 0);
  11222. __decorate([
  11223. BABYLON.serialize()
  11224. ], TargetCamera.prototype, "speed", void 0);
  11225. __decorate([
  11226. BABYLON.serializeAsMeshReference("lockedTargetId")
  11227. ], TargetCamera.prototype, "lockedTarget", void 0);
  11228. return TargetCamera;
  11229. })(BABYLON.Camera);
  11230. BABYLON.TargetCamera = TargetCamera;
  11231. })(BABYLON || (BABYLON = {}));
  11232. var BABYLON;
  11233. (function (BABYLON) {
  11234. var FreeCamera = (function (_super) {
  11235. __extends(FreeCamera, _super);
  11236. function FreeCamera(name, position, scene) {
  11237. var _this = this;
  11238. _super.call(this, name, position, scene);
  11239. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11240. this.keysUp = [38];
  11241. this.keysDown = [40];
  11242. this.keysLeft = [37];
  11243. this.keysRight = [39];
  11244. this.checkCollisions = false;
  11245. this.applyGravity = false;
  11246. this.angularSensibility = 2000.0;
  11247. this._keys = [];
  11248. this._collider = new BABYLON.Collider();
  11249. this._needMoveForGravity = false;
  11250. this._oldPosition = BABYLON.Vector3.Zero();
  11251. this._diffPosition = BABYLON.Vector3.Zero();
  11252. this._newPosition = BABYLON.Vector3.Zero();
  11253. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11254. if (collidedMesh === void 0) { collidedMesh = null; }
  11255. //TODO move this to the collision coordinator!
  11256. if (_this.getScene().workerCollisions)
  11257. newPosition.multiplyInPlace(_this._collider.radius);
  11258. var updatePosition = function (newPos) {
  11259. _this._newPosition.copyFrom(newPos);
  11260. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11261. var oldPosition = _this.position.clone();
  11262. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11263. _this.position.addInPlace(_this._diffPosition);
  11264. if (_this.onCollide && collidedMesh) {
  11265. _this.onCollide(collidedMesh);
  11266. }
  11267. }
  11268. };
  11269. updatePosition(newPosition);
  11270. };
  11271. }
  11272. FreeCamera.prototype._onLostFocus = function (e) {
  11273. this._keys = [];
  11274. };
  11275. // Controls
  11276. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11277. var _this = this;
  11278. var previousPosition;
  11279. var engine = this.getEngine();
  11280. if (this._attachedElement) {
  11281. return;
  11282. }
  11283. this._attachedElement = element;
  11284. if (this._onMouseDown === undefined) {
  11285. this._onMouseDown = function (evt) {
  11286. previousPosition = {
  11287. x: evt.clientX,
  11288. y: evt.clientY
  11289. };
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. };
  11294. this._onMouseUp = function (evt) {
  11295. previousPosition = null;
  11296. if (!noPreventDefault) {
  11297. evt.preventDefault();
  11298. }
  11299. };
  11300. this._onMouseOut = function (evt) {
  11301. previousPosition = null;
  11302. _this._keys = [];
  11303. if (!noPreventDefault) {
  11304. evt.preventDefault();
  11305. }
  11306. };
  11307. this._onMouseMove = function (evt) {
  11308. if (!previousPosition && !engine.isPointerLock) {
  11309. return;
  11310. }
  11311. var offsetX;
  11312. var offsetY;
  11313. if (!engine.isPointerLock) {
  11314. offsetX = evt.clientX - previousPosition.x;
  11315. offsetY = evt.clientY - previousPosition.y;
  11316. }
  11317. else {
  11318. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11319. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11320. }
  11321. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11322. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11323. previousPosition = {
  11324. x: evt.clientX,
  11325. y: evt.clientY
  11326. };
  11327. if (!noPreventDefault) {
  11328. evt.preventDefault();
  11329. }
  11330. };
  11331. this._onKeyDown = function (evt) {
  11332. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11333. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11334. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11335. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11336. var index = _this._keys.indexOf(evt.keyCode);
  11337. if (index === -1) {
  11338. _this._keys.push(evt.keyCode);
  11339. }
  11340. if (!noPreventDefault) {
  11341. evt.preventDefault();
  11342. }
  11343. }
  11344. };
  11345. this._onKeyUp = function (evt) {
  11346. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11347. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11348. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11349. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11350. var index = _this._keys.indexOf(evt.keyCode);
  11351. if (index >= 0) {
  11352. _this._keys.splice(index, 1);
  11353. }
  11354. if (!noPreventDefault) {
  11355. evt.preventDefault();
  11356. }
  11357. }
  11358. };
  11359. this._reset = function () {
  11360. _this._keys = [];
  11361. previousPosition = null;
  11362. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11363. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11364. };
  11365. }
  11366. element.addEventListener("mousedown", this._onMouseDown, false);
  11367. element.addEventListener("mouseup", this._onMouseUp, false);
  11368. element.addEventListener("mouseout", this._onMouseOut, false);
  11369. element.addEventListener("mousemove", this._onMouseMove, false);
  11370. BABYLON.Tools.RegisterTopRootEvents([
  11371. { name: "keydown", handler: this._onKeyDown },
  11372. { name: "keyup", handler: this._onKeyUp },
  11373. { name: "blur", handler: this._onLostFocus }
  11374. ]);
  11375. };
  11376. FreeCamera.prototype.detachControl = function (element) {
  11377. if (this._attachedElement !== element) {
  11378. return;
  11379. }
  11380. element.removeEventListener("mousedown", this._onMouseDown);
  11381. element.removeEventListener("mouseup", this._onMouseUp);
  11382. element.removeEventListener("mouseout", this._onMouseOut);
  11383. element.removeEventListener("mousemove", this._onMouseMove);
  11384. BABYLON.Tools.UnregisterTopRootEvents([
  11385. { name: "keydown", handler: this._onKeyDown },
  11386. { name: "keyup", handler: this._onKeyUp },
  11387. { name: "blur", handler: this._onLostFocus }
  11388. ]);
  11389. this._attachedElement = null;
  11390. if (this._reset) {
  11391. this._reset();
  11392. }
  11393. };
  11394. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11395. var globalPosition;
  11396. if (this.parent) {
  11397. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11398. }
  11399. else {
  11400. globalPosition = this.position;
  11401. }
  11402. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11403. this._collider.radius = this.ellipsoid;
  11404. //no need for clone, as long as gravity is not on.
  11405. var actualVelocity = velocity;
  11406. //add gravity to the velocity to prevent the dual-collision checking
  11407. if (this.applyGravity) {
  11408. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11409. actualVelocity = velocity.add(this.getScene().gravity);
  11410. }
  11411. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11412. };
  11413. FreeCamera.prototype._checkInputs = function () {
  11414. if (!this._localDirection) {
  11415. this._localDirection = BABYLON.Vector3.Zero();
  11416. this._transformedDirection = BABYLON.Vector3.Zero();
  11417. }
  11418. // Keyboard
  11419. for (var index = 0; index < this._keys.length; index++) {
  11420. var keyCode = this._keys[index];
  11421. var speed = this._computeLocalCameraSpeed();
  11422. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11423. this._localDirection.copyFromFloats(-speed, 0, 0);
  11424. }
  11425. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11426. this._localDirection.copyFromFloats(0, 0, speed);
  11427. }
  11428. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11429. this._localDirection.copyFromFloats(speed, 0, 0);
  11430. }
  11431. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11432. this._localDirection.copyFromFloats(0, 0, -speed);
  11433. }
  11434. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11435. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11436. this.cameraDirection.addInPlace(this._transformedDirection);
  11437. }
  11438. _super.prototype._checkInputs.call(this);
  11439. };
  11440. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11441. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11442. };
  11443. FreeCamera.prototype._updatePosition = function () {
  11444. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11445. this._collideWithWorld(this.cameraDirection);
  11446. }
  11447. else {
  11448. this.position.addInPlace(this.cameraDirection);
  11449. }
  11450. };
  11451. FreeCamera.prototype.getTypeName = function () {
  11452. return "FreeCamera";
  11453. };
  11454. __decorate([
  11455. BABYLON.serializeAsVector3()
  11456. ], FreeCamera.prototype, "ellipsoid", void 0);
  11457. __decorate([
  11458. BABYLON.serialize()
  11459. ], FreeCamera.prototype, "keysUp", void 0);
  11460. __decorate([
  11461. BABYLON.serialize()
  11462. ], FreeCamera.prototype, "keysDown", void 0);
  11463. __decorate([
  11464. BABYLON.serialize()
  11465. ], FreeCamera.prototype, "keysLeft", void 0);
  11466. __decorate([
  11467. BABYLON.serialize()
  11468. ], FreeCamera.prototype, "keysRight", void 0);
  11469. __decorate([
  11470. BABYLON.serialize()
  11471. ], FreeCamera.prototype, "checkCollisions", void 0);
  11472. __decorate([
  11473. BABYLON.serialize()
  11474. ], FreeCamera.prototype, "applyGravity", void 0);
  11475. __decorate([
  11476. BABYLON.serialize()
  11477. ], FreeCamera.prototype, "angularSensibility", void 0);
  11478. return FreeCamera;
  11479. })(BABYLON.TargetCamera);
  11480. BABYLON.FreeCamera = FreeCamera;
  11481. })(BABYLON || (BABYLON = {}));
  11482. var BABYLON;
  11483. (function (BABYLON) {
  11484. var FollowCamera = (function (_super) {
  11485. __extends(FollowCamera, _super);
  11486. function FollowCamera(name, position, scene, target) {
  11487. _super.call(this, name, position, scene);
  11488. this.radius = 12;
  11489. this.rotationOffset = 0;
  11490. this.heightOffset = 4;
  11491. this.cameraAcceleration = 0.05;
  11492. this.maxCameraSpeed = 20;
  11493. this.target = target;
  11494. }
  11495. FollowCamera.prototype.getRadians = function (degrees) {
  11496. return degrees * Math.PI / 180;
  11497. };
  11498. FollowCamera.prototype.follow = function (cameraTarget) {
  11499. if (!cameraTarget)
  11500. return;
  11501. var yRotation;
  11502. if (cameraTarget.rotationQuaternion) {
  11503. var rotMatrix = new BABYLON.Matrix();
  11504. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11505. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11506. }
  11507. else {
  11508. yRotation = cameraTarget.rotation.y;
  11509. }
  11510. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11511. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11512. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11513. var dx = targetX - this.position.x;
  11514. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11515. var dz = (targetZ) - this.position.z;
  11516. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11517. var vy = dy * this.cameraAcceleration;
  11518. var vz = dz * this.cameraAcceleration * 2;
  11519. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11520. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11521. }
  11522. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11523. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11524. }
  11525. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11526. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11527. }
  11528. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11529. this.setTarget(cameraTarget.position);
  11530. };
  11531. FollowCamera.prototype._checkInputs = function () {
  11532. _super.prototype._checkInputs.call(this);
  11533. this.follow(this.target);
  11534. };
  11535. FollowCamera.prototype.getTypeName = function () {
  11536. return "FollowCamera";
  11537. };
  11538. __decorate([
  11539. BABYLON.serialize()
  11540. ], FollowCamera.prototype, "radius", void 0);
  11541. __decorate([
  11542. BABYLON.serialize()
  11543. ], FollowCamera.prototype, "rotationOffset", void 0);
  11544. __decorate([
  11545. BABYLON.serialize()
  11546. ], FollowCamera.prototype, "heightOffset", void 0);
  11547. __decorate([
  11548. BABYLON.serialize()
  11549. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11550. __decorate([
  11551. BABYLON.serialize()
  11552. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11553. __decorate([
  11554. BABYLON.serializeAsMeshReference("lockedTargetId")
  11555. ], FollowCamera.prototype, "target", void 0);
  11556. return FollowCamera;
  11557. })(BABYLON.TargetCamera);
  11558. BABYLON.FollowCamera = FollowCamera;
  11559. var ArcFollowCamera = (function (_super) {
  11560. __extends(ArcFollowCamera, _super);
  11561. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11562. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11563. this.alpha = alpha;
  11564. this.beta = beta;
  11565. this.radius = radius;
  11566. this.target = target;
  11567. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11568. this.follow();
  11569. }
  11570. ArcFollowCamera.prototype.follow = function () {
  11571. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11572. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11573. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11574. this.position = this.target.position.add(this._cartesianCoordinates);
  11575. this.setTarget(this.target.position);
  11576. };
  11577. ArcFollowCamera.prototype._checkInputs = function () {
  11578. _super.prototype._checkInputs.call(this);
  11579. this.follow();
  11580. };
  11581. ArcFollowCamera.prototype.getTypeName = function () {
  11582. return "ArcFollowCamera";
  11583. };
  11584. return ArcFollowCamera;
  11585. })(BABYLON.TargetCamera);
  11586. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11587. })(BABYLON || (BABYLON = {}));
  11588. var BABYLON;
  11589. (function (BABYLON) {
  11590. // We're mainly based on the logic defined into the FreeCamera code
  11591. var TouchCamera = (function (_super) {
  11592. __extends(TouchCamera, _super);
  11593. function TouchCamera(name, position, scene) {
  11594. _super.call(this, name, position, scene);
  11595. this._offsetX = null;
  11596. this._offsetY = null;
  11597. this._pointerCount = 0;
  11598. this._pointerPressed = [];
  11599. this.touchAngularSensibility = 200000.0;
  11600. this.touchMoveSensibility = 250.0;
  11601. }
  11602. TouchCamera.prototype._onLostFocus = function (e) {
  11603. this._offsetX = null;
  11604. this._offsetY = null;
  11605. _super.prototype._onLostFocus.call(this, e);
  11606. };
  11607. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11608. var _this = this;
  11609. var previousPosition;
  11610. if (this._attachedCanvas) {
  11611. return;
  11612. }
  11613. if (this._onPointerDown === undefined) {
  11614. this._onPointerDown = function (evt) {
  11615. if (evt.pointerType === "mouse") {
  11616. return;
  11617. }
  11618. if (!noPreventDefault) {
  11619. evt.preventDefault();
  11620. }
  11621. _this._pointerPressed.push(evt.pointerId);
  11622. if (_this._pointerPressed.length !== 1) {
  11623. return;
  11624. }
  11625. previousPosition = {
  11626. x: evt.clientX,
  11627. y: evt.clientY
  11628. };
  11629. };
  11630. this._onPointerUp = function (evt) {
  11631. if (evt.pointerType === "mouse") {
  11632. return;
  11633. }
  11634. if (!noPreventDefault) {
  11635. evt.preventDefault();
  11636. }
  11637. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11638. if (index === -1) {
  11639. return;
  11640. }
  11641. _this._pointerPressed.splice(index, 1);
  11642. if (index != 0) {
  11643. return;
  11644. }
  11645. previousPosition = null;
  11646. _this._offsetX = null;
  11647. _this._offsetY = null;
  11648. };
  11649. this._onPointerMove = function (evt) {
  11650. if (evt.pointerType === "mouse") {
  11651. return;
  11652. }
  11653. if (!noPreventDefault) {
  11654. evt.preventDefault();
  11655. }
  11656. if (!previousPosition) {
  11657. return;
  11658. }
  11659. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11660. if (index != 0) {
  11661. return;
  11662. }
  11663. _this._offsetX = evt.clientX - previousPosition.x;
  11664. _this._offsetY = -(evt.clientY - previousPosition.y);
  11665. };
  11666. }
  11667. canvas.addEventListener("pointerdown", this._onPointerDown);
  11668. canvas.addEventListener("pointerup", this._onPointerUp);
  11669. canvas.addEventListener("pointerout", this._onPointerUp);
  11670. canvas.addEventListener("pointermove", this._onPointerMove);
  11671. _super.prototype.attachControl.call(this, canvas);
  11672. };
  11673. TouchCamera.prototype.detachControl = function (canvas) {
  11674. if (this._attachedCanvas !== canvas) {
  11675. return;
  11676. }
  11677. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11678. canvas.removeEventListener("pointerup", this._onPointerUp);
  11679. canvas.removeEventListener("pointerout", this._onPointerUp);
  11680. canvas.removeEventListener("pointermove", this._onPointerMove);
  11681. _super.prototype.detachControl.call(this, canvas);
  11682. };
  11683. TouchCamera.prototype._checkInputs = function () {
  11684. if (this._offsetX) {
  11685. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11686. if (this._pointerPressed.length > 1) {
  11687. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11688. }
  11689. else {
  11690. var speed = this._computeLocalCameraSpeed();
  11691. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11692. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11693. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11694. }
  11695. }
  11696. _super.prototype._checkInputs.call(this);
  11697. };
  11698. TouchCamera.prototype.getTypeName = function () {
  11699. return "TouchCamera";
  11700. };
  11701. __decorate([
  11702. BABYLON.serialize()
  11703. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11704. __decorate([
  11705. BABYLON.serialize()
  11706. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11707. return TouchCamera;
  11708. })(BABYLON.FreeCamera);
  11709. BABYLON.TouchCamera = TouchCamera;
  11710. })(BABYLON || (BABYLON = {}));
  11711. var BABYLON;
  11712. (function (BABYLON) {
  11713. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11714. var ArcRotateCamera = (function (_super) {
  11715. __extends(ArcRotateCamera, _super);
  11716. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11717. var _this = this;
  11718. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11719. this.inertialAlphaOffset = 0;
  11720. this.inertialBetaOffset = 0;
  11721. this.inertialRadiusOffset = 0;
  11722. this.lowerAlphaLimit = null;
  11723. this.upperAlphaLimit = null;
  11724. this.lowerBetaLimit = 0.01;
  11725. this.upperBetaLimit = Math.PI;
  11726. this.lowerRadiusLimit = null;
  11727. this.upperRadiusLimit = null;
  11728. this.angularSensibilityX = 1000.0;
  11729. this.angularSensibilityY = 1000.0;
  11730. this.wheelPrecision = 3.0;
  11731. this.pinchPrecision = 2.0;
  11732. this.panningSensibility = 50.0;
  11733. this.inertialPanningX = 0;
  11734. this.inertialPanningY = 0;
  11735. this.keysUp = [38];
  11736. this.keysDown = [40];
  11737. this.keysLeft = [37];
  11738. this.keysRight = [39];
  11739. this.zoomOnFactor = 1;
  11740. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11741. this.pinchInwards = true;
  11742. this.allowUpsideDown = true;
  11743. this._keys = [];
  11744. this._viewMatrix = new BABYLON.Matrix();
  11745. // Panning
  11746. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11747. this._isRightClick = false;
  11748. this._isCtrlPushed = false;
  11749. this.checkCollisions = false;
  11750. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11751. this._collider = new BABYLON.Collider();
  11752. this._previousPosition = BABYLON.Vector3.Zero();
  11753. this._collisionVelocity = BABYLON.Vector3.Zero();
  11754. this._newPosition = BABYLON.Vector3.Zero();
  11755. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11756. if (collidedMesh === void 0) { collidedMesh = null; }
  11757. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11758. newPosition.multiplyInPlace(_this._collider.radius);
  11759. }
  11760. if (!collidedMesh) {
  11761. _this._previousPosition.copyFrom(_this.position);
  11762. }
  11763. else {
  11764. _this.setPosition(newPosition);
  11765. if (_this.onCollide) {
  11766. _this.onCollide(collidedMesh);
  11767. }
  11768. }
  11769. // Recompute because of constraints
  11770. var cosa = Math.cos(_this.alpha);
  11771. var sina = Math.sin(_this.alpha);
  11772. var cosb = Math.cos(_this.beta);
  11773. var sinb = Math.sin(_this.beta);
  11774. if (sinb === 0) {
  11775. sinb = 0.0001;
  11776. }
  11777. var target = _this._getTargetPosition();
  11778. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11779. _this.position.copyFrom(_this._newPosition);
  11780. var up = _this.upVector;
  11781. if (_this.allowUpsideDown && _this.beta < 0) {
  11782. up = up.clone();
  11783. up = up.negate();
  11784. }
  11785. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11786. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11787. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11788. _this._collisionTriggered = false;
  11789. };
  11790. if (!target) {
  11791. this.target = BABYLON.Vector3.Zero();
  11792. }
  11793. else {
  11794. this.target = target;
  11795. }
  11796. this.alpha = alpha;
  11797. this.beta = beta;
  11798. this.radius = radius;
  11799. this.getViewMatrix();
  11800. }
  11801. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11802. //deprecated angularSensibility support
  11803. get: function () {
  11804. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11805. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11806. },
  11807. //deprecated angularSensibility support
  11808. set: function (value) {
  11809. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11810. this.angularSensibilityX = value;
  11811. this.angularSensibilityY = value;
  11812. },
  11813. enumerable: true,
  11814. configurable: true
  11815. });
  11816. // Cache
  11817. ArcRotateCamera.prototype._initCache = function () {
  11818. _super.prototype._initCache.call(this);
  11819. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11820. this._cache.alpha = undefined;
  11821. this._cache.beta = undefined;
  11822. this._cache.radius = undefined;
  11823. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11824. };
  11825. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11826. if (!ignoreParentClass) {
  11827. _super.prototype._updateCache.call(this);
  11828. }
  11829. this._cache.target.copyFrom(this._getTargetPosition());
  11830. this._cache.alpha = this.alpha;
  11831. this._cache.beta = this.beta;
  11832. this._cache.radius = this.radius;
  11833. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11834. };
  11835. ArcRotateCamera.prototype._getTargetPosition = function () {
  11836. if (this.target.getAbsolutePosition) {
  11837. return this.target.getAbsolutePosition();
  11838. }
  11839. return this.target;
  11840. };
  11841. // Synchronized
  11842. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11843. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11844. return false;
  11845. return this._cache.target.equals(this.target)
  11846. && this._cache.alpha === this.alpha
  11847. && this._cache.beta === this.beta
  11848. && this._cache.radius === this.radius
  11849. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11850. };
  11851. // Methods
  11852. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11853. var _this = this;
  11854. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11855. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11856. var previousPinchDistance = 0;
  11857. var pointers = new BABYLON.SmartCollection();
  11858. if (this._attachedElement) {
  11859. return;
  11860. }
  11861. this._attachedElement = element;
  11862. var engine = this.getEngine();
  11863. if (this._onPointerDown === undefined) {
  11864. this._onPointerDown = function (evt) {
  11865. // Manage panning with right click
  11866. _this._isRightClick = evt.button === 2;
  11867. // manage pointers
  11868. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11869. cacheSoloPointer = pointers.item(evt.pointerId);
  11870. if (!noPreventDefault) {
  11871. evt.preventDefault();
  11872. }
  11873. };
  11874. this._onPointerUp = function (evt) {
  11875. cacheSoloPointer = null;
  11876. previousPinchDistance = 0;
  11877. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11878. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11879. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11880. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11881. pointers.empty();
  11882. if (!noPreventDefault) {
  11883. evt.preventDefault();
  11884. }
  11885. };
  11886. this._onContextMenu = function (evt) {
  11887. evt.preventDefault();
  11888. };
  11889. this._onPointerMove = function (evt) {
  11890. if (!noPreventDefault) {
  11891. evt.preventDefault();
  11892. }
  11893. switch (pointers.count) {
  11894. case 1:
  11895. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11896. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11897. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11898. }
  11899. else {
  11900. var offsetX = evt.clientX - cacheSoloPointer.x;
  11901. var offsetY = evt.clientY - cacheSoloPointer.y;
  11902. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11903. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11904. }
  11905. cacheSoloPointer.x = evt.clientX;
  11906. cacheSoloPointer.y = evt.clientY;
  11907. break;
  11908. case 2:
  11909. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11910. pointers.item(evt.pointerId).x = evt.clientX;
  11911. pointers.item(evt.pointerId).y = evt.clientY;
  11912. var direction = _this.pinchInwards ? 1 : -1;
  11913. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11914. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11915. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11916. if (previousPinchDistance === 0) {
  11917. previousPinchDistance = pinchSquaredDistance;
  11918. return;
  11919. }
  11920. if (pinchSquaredDistance !== previousPinchDistance) {
  11921. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11922. previousPinchDistance = pinchSquaredDistance;
  11923. }
  11924. break;
  11925. default:
  11926. if (pointers.item(evt.pointerId)) {
  11927. pointers.item(evt.pointerId).x = evt.clientX;
  11928. pointers.item(evt.pointerId).y = evt.clientY;
  11929. }
  11930. }
  11931. };
  11932. this._onMouseMove = function (evt) {
  11933. if (!engine.isPointerLock) {
  11934. return;
  11935. }
  11936. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11937. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11938. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11939. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11940. if (!noPreventDefault) {
  11941. evt.preventDefault();
  11942. }
  11943. };
  11944. this._wheel = function (event) {
  11945. var delta = 0;
  11946. if (event.wheelDelta) {
  11947. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11948. }
  11949. else if (event.detail) {
  11950. delta = -event.detail / _this.wheelPrecision;
  11951. }
  11952. if (delta)
  11953. _this.inertialRadiusOffset += delta;
  11954. if (event.preventDefault) {
  11955. if (!noPreventDefault) {
  11956. event.preventDefault();
  11957. }
  11958. }
  11959. };
  11960. this._onKeyDown = function (evt) {
  11961. _this._isCtrlPushed = evt.ctrlKey;
  11962. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11963. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11964. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11965. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11966. var index = _this._keys.indexOf(evt.keyCode);
  11967. if (index === -1) {
  11968. _this._keys.push(evt.keyCode);
  11969. }
  11970. if (evt.preventDefault) {
  11971. if (!noPreventDefault) {
  11972. evt.preventDefault();
  11973. }
  11974. }
  11975. }
  11976. };
  11977. this._onKeyUp = function (evt) {
  11978. _this._isCtrlPushed = evt.ctrlKey;
  11979. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11980. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11981. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11982. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11983. var index = _this._keys.indexOf(evt.keyCode);
  11984. if (index >= 0) {
  11985. _this._keys.splice(index, 1);
  11986. }
  11987. if (evt.preventDefault) {
  11988. if (!noPreventDefault) {
  11989. evt.preventDefault();
  11990. }
  11991. }
  11992. }
  11993. };
  11994. this._onLostFocus = function () {
  11995. _this._keys = [];
  11996. pointers.empty();
  11997. previousPinchDistance = 0;
  11998. cacheSoloPointer = null;
  11999. };
  12000. this._onGestureStart = function (e) {
  12001. if (window.MSGesture === undefined) {
  12002. return;
  12003. }
  12004. if (!_this._MSGestureHandler) {
  12005. _this._MSGestureHandler = new MSGesture();
  12006. _this._MSGestureHandler.target = element;
  12007. }
  12008. _this._MSGestureHandler.addPointer(e.pointerId);
  12009. };
  12010. this._onGesture = function (e) {
  12011. _this.radius *= e.scale;
  12012. if (e.preventDefault) {
  12013. if (!noPreventDefault) {
  12014. e.stopPropagation();
  12015. e.preventDefault();
  12016. }
  12017. }
  12018. };
  12019. this._reset = function () {
  12020. _this._keys = [];
  12021. _this.inertialAlphaOffset = 0;
  12022. _this.inertialBetaOffset = 0;
  12023. _this.inertialRadiusOffset = 0;
  12024. pointers.empty();
  12025. previousPinchDistance = 0;
  12026. cacheSoloPointer = null;
  12027. };
  12028. }
  12029. if (!useCtrlForPanning) {
  12030. element.addEventListener("contextmenu", this._onContextMenu, false);
  12031. }
  12032. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12033. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12034. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12035. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12036. element.addEventListener("mousemove", this._onMouseMove, false);
  12037. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12038. element.addEventListener("MSGestureChange", this._onGesture, false);
  12039. element.addEventListener('mousewheel', this._wheel, false);
  12040. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12041. BABYLON.Tools.RegisterTopRootEvents([
  12042. { name: "keydown", handler: this._onKeyDown },
  12043. { name: "keyup", handler: this._onKeyUp },
  12044. { name: "blur", handler: this._onLostFocus }
  12045. ]);
  12046. };
  12047. ArcRotateCamera.prototype.detachControl = function (element) {
  12048. if (this._attachedElement !== element) {
  12049. return;
  12050. }
  12051. element.removeEventListener("contextmenu", this._onContextMenu);
  12052. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12053. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12054. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12055. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12056. element.removeEventListener("mousemove", this._onMouseMove);
  12057. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12058. element.removeEventListener("MSGestureChange", this._onGesture);
  12059. element.removeEventListener('mousewheel', this._wheel);
  12060. element.removeEventListener('DOMMouseScroll', this._wheel);
  12061. BABYLON.Tools.UnregisterTopRootEvents([
  12062. { name: "keydown", handler: this._onKeyDown },
  12063. { name: "keyup", handler: this._onKeyUp },
  12064. { name: "blur", handler: this._onLostFocus }
  12065. ]);
  12066. this._MSGestureHandler = null;
  12067. this._attachedElement = null;
  12068. if (this._reset) {
  12069. this._reset();
  12070. }
  12071. };
  12072. ArcRotateCamera.prototype._checkInputs = function () {
  12073. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12074. if (this._collisionTriggered) {
  12075. return;
  12076. }
  12077. // Keyboard
  12078. for (var index = 0; index < this._keys.length; index++) {
  12079. var keyCode = this._keys[index];
  12080. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12081. this.inertialAlphaOffset -= 0.01;
  12082. }
  12083. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12084. this.inertialBetaOffset -= 0.01;
  12085. }
  12086. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12087. this.inertialAlphaOffset += 0.01;
  12088. }
  12089. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12090. this.inertialBetaOffset += 0.01;
  12091. }
  12092. }
  12093. // Inertia
  12094. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12095. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12096. this.beta += this.inertialBetaOffset;
  12097. this.radius -= this.inertialRadiusOffset;
  12098. this.inertialAlphaOffset *= this.inertia;
  12099. this.inertialBetaOffset *= this.inertia;
  12100. this.inertialRadiusOffset *= this.inertia;
  12101. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12102. this.inertialAlphaOffset = 0;
  12103. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12104. this.inertialBetaOffset = 0;
  12105. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12106. this.inertialRadiusOffset = 0;
  12107. }
  12108. // Panning inertia
  12109. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12110. if (!this._localDirection) {
  12111. this._localDirection = BABYLON.Vector3.Zero();
  12112. this._transformedDirection = BABYLON.Vector3.Zero();
  12113. }
  12114. this.inertialPanningX *= this.inertia;
  12115. this.inertialPanningY *= this.inertia;
  12116. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12117. this.inertialPanningX = 0;
  12118. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12119. this.inertialPanningY = 0;
  12120. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12121. this._localDirection.multiplyInPlace(this.panningAxis);
  12122. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12123. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12124. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12125. if (!this.panningAxis.y) {
  12126. this._transformedDirection.y = 0;
  12127. }
  12128. this.target.addInPlace(this._transformedDirection);
  12129. }
  12130. // Limits
  12131. this._checkLimits();
  12132. _super.prototype._checkInputs.call(this);
  12133. };
  12134. ArcRotateCamera.prototype._checkLimits = function () {
  12135. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12136. if (this.allowUpsideDown && this.beta > Math.PI) {
  12137. this.beta = this.beta - (2 * Math.PI);
  12138. }
  12139. }
  12140. else {
  12141. if (this.beta < this.lowerBetaLimit) {
  12142. this.beta = this.lowerBetaLimit;
  12143. }
  12144. }
  12145. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12146. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12147. this.beta = this.beta + (2 * Math.PI);
  12148. }
  12149. }
  12150. else {
  12151. if (this.beta > this.upperBetaLimit) {
  12152. this.beta = this.upperBetaLimit;
  12153. }
  12154. }
  12155. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12156. this.alpha = this.lowerAlphaLimit;
  12157. }
  12158. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12159. this.alpha = this.upperAlphaLimit;
  12160. }
  12161. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12162. this.radius = this.lowerRadiusLimit;
  12163. }
  12164. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12165. this.radius = this.upperRadiusLimit;
  12166. }
  12167. };
  12168. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12169. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12170. this.radius = radiusv3.length();
  12171. // Alpha
  12172. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12173. if (radiusv3.z < 0) {
  12174. this.alpha = 2 * Math.PI - this.alpha;
  12175. }
  12176. // Beta
  12177. this.beta = Math.acos(radiusv3.y / this.radius);
  12178. this._checkLimits();
  12179. };
  12180. ArcRotateCamera.prototype.setPosition = function (position) {
  12181. if (this.position.equals(position)) {
  12182. return;
  12183. }
  12184. this.position = position;
  12185. this.rebuildAnglesAndRadius();
  12186. };
  12187. ArcRotateCamera.prototype.setTarget = function (target) {
  12188. if (this._getTargetPosition().equals(target)) {
  12189. return;
  12190. }
  12191. this.target = target;
  12192. this.rebuildAnglesAndRadius();
  12193. };
  12194. ArcRotateCamera.prototype._getViewMatrix = function () {
  12195. // Compute
  12196. var cosa = Math.cos(this.alpha);
  12197. var sina = Math.sin(this.alpha);
  12198. var cosb = Math.cos(this.beta);
  12199. var sinb = Math.sin(this.beta);
  12200. if (sinb === 0) {
  12201. sinb = 0.0001;
  12202. }
  12203. var target = this._getTargetPosition();
  12204. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12205. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12206. this._collider.radius = this.collisionRadius;
  12207. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12208. this._collisionTriggered = true;
  12209. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12210. }
  12211. else {
  12212. this.position.copyFrom(this._newPosition);
  12213. var up = this.upVector;
  12214. if (this.allowUpsideDown && this.beta < 0) {
  12215. up = up.clone();
  12216. up = up.negate();
  12217. }
  12218. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12219. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12220. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12221. }
  12222. return this._viewMatrix;
  12223. };
  12224. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12225. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12226. meshes = meshes || this.getScene().meshes;
  12227. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12228. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12229. this.radius = distance * this.zoomOnFactor;
  12230. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12231. };
  12232. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12233. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12234. var meshesOrMinMaxVector;
  12235. var distance;
  12236. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12237. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12238. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12239. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12240. }
  12241. else {
  12242. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12243. distance = meshesOrMinMaxVectorAndDistance.distance;
  12244. }
  12245. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12246. if (!doNotUpdateMaxZ) {
  12247. this.maxZ = distance * 2;
  12248. }
  12249. };
  12250. /**
  12251. * @override
  12252. * Override Camera.createRigCamera
  12253. */
  12254. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12255. switch (this.cameraRigMode) {
  12256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12260. case BABYLON.Camera.RIG_MODE_VR:
  12261. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12262. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12263. }
  12264. return null;
  12265. };
  12266. /**
  12267. * @override
  12268. * Override Camera._updateRigCameras
  12269. */
  12270. ArcRotateCamera.prototype._updateRigCameras = function () {
  12271. switch (this.cameraRigMode) {
  12272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12276. case BABYLON.Camera.RIG_MODE_VR:
  12277. var camLeft = this._rigCameras[0];
  12278. var camRight = this._rigCameras[1];
  12279. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12280. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12281. camLeft.beta = camRight.beta = this.beta;
  12282. camLeft.radius = camRight.radius = this.radius;
  12283. break;
  12284. }
  12285. _super.prototype._updateRigCameras.call(this);
  12286. };
  12287. ArcRotateCamera.prototype.getTypeName = function () {
  12288. return "ArcRotateCamera";
  12289. };
  12290. __decorate([
  12291. BABYLON.serialize()
  12292. ], ArcRotateCamera.prototype, "alpha", void 0);
  12293. __decorate([
  12294. BABYLON.serialize()
  12295. ], ArcRotateCamera.prototype, "beta", void 0);
  12296. __decorate([
  12297. BABYLON.serialize()
  12298. ], ArcRotateCamera.prototype, "radius", void 0);
  12299. __decorate([
  12300. BABYLON.serializeAsVector3()
  12301. ], ArcRotateCamera.prototype, "target", void 0);
  12302. __decorate([
  12303. BABYLON.serialize()
  12304. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12305. __decorate([
  12306. BABYLON.serialize()
  12307. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12308. __decorate([
  12309. BABYLON.serialize()
  12310. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12311. __decorate([
  12312. BABYLON.serialize()
  12313. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12314. __decorate([
  12315. BABYLON.serialize()
  12316. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12317. __decorate([
  12318. BABYLON.serialize()
  12319. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12320. __decorate([
  12321. BABYLON.serialize()
  12322. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12323. __decorate([
  12324. BABYLON.serialize()
  12325. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12326. __decorate([
  12327. BABYLON.serialize()
  12328. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12329. __decorate([
  12330. BABYLON.serialize()
  12331. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12332. __decorate([
  12333. BABYLON.serialize()
  12334. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12335. __decorate([
  12336. BABYLON.serialize()
  12337. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12338. __decorate([
  12339. BABYLON.serialize()
  12340. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12341. __decorate([
  12342. BABYLON.serialize()
  12343. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12356. __decorate([
  12357. BABYLON.serialize()
  12358. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12359. __decorate([
  12360. BABYLON.serialize()
  12361. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12362. __decorate([
  12363. BABYLON.serialize()
  12364. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12368. return ArcRotateCamera;
  12369. })(BABYLON.TargetCamera);
  12370. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12371. })(BABYLON || (BABYLON = {}));
  12372. var BABYLON;
  12373. (function (BABYLON) {
  12374. var RenderingManager = (function () {
  12375. function RenderingManager(scene) {
  12376. this._renderingGroups = new Array();
  12377. this._scene = scene;
  12378. }
  12379. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12380. if (this._scene._activeParticleSystems.length === 0) {
  12381. return;
  12382. }
  12383. // Particles
  12384. var activeCamera = this._scene.activeCamera;
  12385. var beforeParticlesDate = BABYLON.Tools.Now;
  12386. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12387. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12388. if (particleSystem.renderingGroupId !== index) {
  12389. continue;
  12390. }
  12391. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12392. continue;
  12393. }
  12394. this._clearDepthBuffer();
  12395. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12396. this._scene._activeParticles += particleSystem.render();
  12397. }
  12398. }
  12399. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12400. };
  12401. RenderingManager.prototype._renderSprites = function (index) {
  12402. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12403. return;
  12404. }
  12405. // Sprites
  12406. var activeCamera = this._scene.activeCamera;
  12407. var beforeSpritessDate = BABYLON.Tools.Now;
  12408. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12409. var spriteManager = this._scene.spriteManagers[id];
  12410. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12411. this._clearDepthBuffer();
  12412. spriteManager.render();
  12413. }
  12414. }
  12415. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12416. };
  12417. RenderingManager.prototype._clearDepthBuffer = function () {
  12418. if (this._depthBufferAlreadyCleaned) {
  12419. return;
  12420. }
  12421. this._scene.getEngine().clear(0, false, true);
  12422. this._depthBufferAlreadyCleaned = true;
  12423. };
  12424. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12425. if (this._currentRenderSprites) {
  12426. this._renderSprites(this._currentIndex);
  12427. }
  12428. if (this._currentRenderParticles) {
  12429. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12430. }
  12431. };
  12432. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12433. this._currentActiveMeshes = activeMeshes;
  12434. this._currentRenderParticles = renderParticles;
  12435. this._currentRenderSprites = renderSprites;
  12436. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12437. this._depthBufferAlreadyCleaned = index == 0;
  12438. var renderingGroup = this._renderingGroups[index];
  12439. var needToStepBack = false;
  12440. this._currentIndex = index;
  12441. if (renderingGroup) {
  12442. this._clearDepthBuffer();
  12443. if (!renderingGroup.onBeforeTransparentRendering) {
  12444. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12445. }
  12446. if (!renderingGroup.render(customRenderFunction)) {
  12447. this._renderingGroups.splice(index, 1);
  12448. needToStepBack = true;
  12449. this._renderSpritesAndParticles();
  12450. }
  12451. }
  12452. else {
  12453. this._renderSpritesAndParticles();
  12454. }
  12455. if (needToStepBack) {
  12456. index--;
  12457. }
  12458. }
  12459. };
  12460. RenderingManager.prototype.reset = function () {
  12461. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12462. if (renderingGroup) {
  12463. renderingGroup.prepare();
  12464. }
  12465. });
  12466. };
  12467. RenderingManager.prototype.dispatch = function (subMesh) {
  12468. var mesh = subMesh.getMesh();
  12469. var renderingGroupId = mesh.renderingGroupId || 0;
  12470. if (!this._renderingGroups[renderingGroupId]) {
  12471. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12472. }
  12473. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12474. };
  12475. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12476. return RenderingManager;
  12477. })();
  12478. BABYLON.RenderingManager = RenderingManager;
  12479. })(BABYLON || (BABYLON = {}));
  12480. var BABYLON;
  12481. (function (BABYLON) {
  12482. var RenderingGroup = (function () {
  12483. function RenderingGroup(index, scene) {
  12484. this.index = index;
  12485. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12486. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12487. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12488. this._scene = scene;
  12489. }
  12490. RenderingGroup.prototype.render = function (customRenderFunction) {
  12491. if (customRenderFunction) {
  12492. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12493. return true;
  12494. }
  12495. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12496. if (this.onBeforeTransparentRendering) {
  12497. this.onBeforeTransparentRendering();
  12498. }
  12499. return false;
  12500. }
  12501. var engine = this._scene.getEngine();
  12502. // Opaque
  12503. var subIndex;
  12504. var submesh;
  12505. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12506. submesh = this._opaqueSubMeshes.data[subIndex];
  12507. submesh.render(false);
  12508. }
  12509. // Alpha test
  12510. engine.setAlphaTesting(true);
  12511. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12512. submesh = this._alphaTestSubMeshes.data[subIndex];
  12513. submesh.render(false);
  12514. }
  12515. engine.setAlphaTesting(false);
  12516. if (this.onBeforeTransparentRendering) {
  12517. this.onBeforeTransparentRendering();
  12518. }
  12519. // Transparent
  12520. if (this._transparentSubMeshes.length) {
  12521. // Sorting
  12522. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12523. submesh = this._transparentSubMeshes.data[subIndex];
  12524. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12525. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12526. }
  12527. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12528. sortedArray.sort(function (a, b) {
  12529. // Alpha index first
  12530. if (a._alphaIndex > b._alphaIndex) {
  12531. return 1;
  12532. }
  12533. if (a._alphaIndex < b._alphaIndex) {
  12534. return -1;
  12535. }
  12536. // Then distance to camera
  12537. if (a._distanceToCamera < b._distanceToCamera) {
  12538. return 1;
  12539. }
  12540. if (a._distanceToCamera > b._distanceToCamera) {
  12541. return -1;
  12542. }
  12543. return 0;
  12544. });
  12545. // Rendering
  12546. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12547. submesh = sortedArray[subIndex];
  12548. submesh.render(true);
  12549. }
  12550. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12551. }
  12552. return true;
  12553. };
  12554. RenderingGroup.prototype.prepare = function () {
  12555. this._opaqueSubMeshes.reset();
  12556. this._transparentSubMeshes.reset();
  12557. this._alphaTestSubMeshes.reset();
  12558. };
  12559. RenderingGroup.prototype.dispatch = function (subMesh) {
  12560. var material = subMesh.getMaterial();
  12561. var mesh = subMesh.getMesh();
  12562. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12563. this._transparentSubMeshes.push(subMesh);
  12564. }
  12565. else if (material.needAlphaTesting()) {
  12566. this._alphaTestSubMeshes.push(subMesh);
  12567. }
  12568. else {
  12569. this._opaqueSubMeshes.push(subMesh); // Opaque
  12570. }
  12571. };
  12572. return RenderingGroup;
  12573. })();
  12574. BABYLON.RenderingGroup = RenderingGroup;
  12575. })(BABYLON || (BABYLON = {}));
  12576. var BABYLON;
  12577. (function (BABYLON) {
  12578. /**
  12579. * Represents a scene to be rendered by the engine.
  12580. * @see http://doc.babylonjs.com/page.php?p=21911
  12581. */
  12582. var Scene = (function () {
  12583. /**
  12584. * @constructor
  12585. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12586. */
  12587. function Scene(engine) {
  12588. // Members
  12589. this.autoClear = true;
  12590. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12591. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12592. this.forceWireframe = false;
  12593. this.forcePointsCloud = false;
  12594. this.forceShowBoundingBoxes = false;
  12595. this.animationsEnabled = true;
  12596. this.constantlyUpdateMeshUnderPointer = false;
  12597. // Animations
  12598. this.animations = [];
  12599. 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
  12600. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12601. this._startingPointerTime = 0;
  12602. // Fog
  12603. /**
  12604. * is fog enabled on this scene.
  12605. * @type {boolean}
  12606. */
  12607. this.fogEnabled = true;
  12608. this.fogMode = Scene.FOGMODE_NONE;
  12609. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12610. this.fogDensity = 0.1;
  12611. this.fogStart = 0;
  12612. this.fogEnd = 1000.0;
  12613. // Lights
  12614. /**
  12615. * is shadow enabled on this scene.
  12616. * @type {boolean}
  12617. */
  12618. this.shadowsEnabled = true;
  12619. /**
  12620. * is light enabled on this scene.
  12621. * @type {boolean}
  12622. */
  12623. this.lightsEnabled = true;
  12624. /**
  12625. * All of the lights added to this scene.
  12626. * @see BABYLON.Light
  12627. * @type {BABYLON.Light[]}
  12628. */
  12629. this.lights = new Array();
  12630. // Cameras
  12631. /**
  12632. * All of the cameras added to this scene.
  12633. * @see BABYLON.Camera
  12634. * @type {BABYLON.Camera[]}
  12635. */
  12636. this.cameras = new Array();
  12637. this.activeCameras = new Array();
  12638. // Meshes
  12639. /**
  12640. * All of the (abstract) meshes added to this scene.
  12641. * @see BABYLON.AbstractMesh
  12642. * @type {BABYLON.AbstractMesh[]}
  12643. */
  12644. this.meshes = new Array();
  12645. // Geometries
  12646. this._geometries = new Array();
  12647. this.materials = new Array();
  12648. this.multiMaterials = new Array();
  12649. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12650. // Textures
  12651. this.texturesEnabled = true;
  12652. this.textures = new Array();
  12653. // Particles
  12654. this.particlesEnabled = true;
  12655. this.particleSystems = new Array();
  12656. // Sprites
  12657. this.spritesEnabled = true;
  12658. this.spriteManagers = new Array();
  12659. // Layers
  12660. this.layers = new Array();
  12661. // Skeletons
  12662. this.skeletonsEnabled = true;
  12663. this.skeletons = new Array();
  12664. // Lens flares
  12665. this.lensFlaresEnabled = true;
  12666. this.lensFlareSystems = new Array();
  12667. // Collisions
  12668. this.collisionsEnabled = true;
  12669. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12670. // Postprocesses
  12671. this.postProcessesEnabled = true;
  12672. // Customs render targets
  12673. this.renderTargetsEnabled = true;
  12674. this.dumpNextRenderTargets = false;
  12675. this.customRenderTargets = new Array();
  12676. // Imported meshes
  12677. this.importedMeshesFiles = new Array();
  12678. // Probes
  12679. this.probesEnabled = true;
  12680. this.reflectionProbes = new Array();
  12681. this._actionManagers = new Array();
  12682. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12683. // Procedural textures
  12684. this.proceduralTexturesEnabled = true;
  12685. this._proceduralTextures = new Array();
  12686. this.soundTracks = new Array();
  12687. this._audioEnabled = true;
  12688. this._headphone = false;
  12689. this._totalVertices = 0;
  12690. this._activeIndices = 0;
  12691. this._activeParticles = 0;
  12692. this._lastFrameDuration = 0;
  12693. this._evaluateActiveMeshesDuration = 0;
  12694. this._renderTargetsDuration = 0;
  12695. this._particlesDuration = 0;
  12696. this._renderDuration = 0;
  12697. this._spritesDuration = 0;
  12698. this._animationRatio = 0;
  12699. this._renderId = 0;
  12700. this._executeWhenReadyTimeoutId = -1;
  12701. this._toBeDisposed = new BABYLON.SmartArray(256);
  12702. this._onReadyCallbacks = new Array();
  12703. this._pendingData = []; //ANY
  12704. this._onBeforeRenderCallbacks = new Array();
  12705. this._onAfterRenderCallbacks = new Array();
  12706. this._activeMeshes = new BABYLON.SmartArray(256);
  12707. this._processedMaterials = new BABYLON.SmartArray(256);
  12708. this._renderTargets = new BABYLON.SmartArray(256);
  12709. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12710. this._activeSkeletons = new BABYLON.SmartArray(32);
  12711. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12712. this._activeBones = 0;
  12713. this._activeAnimatables = new Array();
  12714. this._transformMatrix = BABYLON.Matrix.Zero();
  12715. this._edgesRenderers = new BABYLON.SmartArray(16);
  12716. this._uniqueIdCounter = 0;
  12717. this._engine = engine;
  12718. engine.scenes.push(this);
  12719. this._renderingManager = new BABYLON.RenderingManager(this);
  12720. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12721. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12722. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12723. if (BABYLON.OutlineRenderer) {
  12724. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12725. }
  12726. this.attachControl();
  12727. this._debugLayer = new BABYLON.DebugLayer(this);
  12728. if (BABYLON.SoundTrack) {
  12729. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12730. }
  12731. //simplification queue
  12732. if (BABYLON.SimplificationQueue) {
  12733. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12734. }
  12735. //collision coordinator initialization. For now legacy per default.
  12736. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12737. }
  12738. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12739. get: function () {
  12740. return Scene._FOGMODE_NONE;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12746. get: function () {
  12747. return Scene._FOGMODE_EXP;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12753. get: function () {
  12754. return Scene._FOGMODE_EXP2;
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12760. get: function () {
  12761. return Scene._FOGMODE_LINEAR;
  12762. },
  12763. enumerable: true,
  12764. configurable: true
  12765. });
  12766. Object.defineProperty(Scene.prototype, "debugLayer", {
  12767. // Properties
  12768. get: function () {
  12769. return this._debugLayer;
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12775. get: function () {
  12776. return this._workerCollisions;
  12777. },
  12778. set: function (enabled) {
  12779. enabled = (enabled && !!Worker);
  12780. this._workerCollisions = enabled;
  12781. if (this.collisionCoordinator) {
  12782. this.collisionCoordinator.destroy();
  12783. }
  12784. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12785. this.collisionCoordinator.init(this);
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12791. get: function () {
  12792. return this._selectionOctree;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12798. /**
  12799. * The mesh that is currently under the pointer.
  12800. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12801. */
  12802. get: function () {
  12803. return this._pointerOverMesh;
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Object.defineProperty(Scene.prototype, "pointerX", {
  12809. /**
  12810. * Current on-screen X position of the pointer
  12811. * @return {number} X position of the pointer
  12812. */
  12813. get: function () {
  12814. return this._pointerX;
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(Scene.prototype, "pointerY", {
  12820. /**
  12821. * Current on-screen Y position of the pointer
  12822. * @return {number} Y position of the pointer
  12823. */
  12824. get: function () {
  12825. return this._pointerY;
  12826. },
  12827. enumerable: true,
  12828. configurable: true
  12829. });
  12830. Scene.prototype.getCachedMaterial = function () {
  12831. return this._cachedMaterial;
  12832. };
  12833. Scene.prototype.getBoundingBoxRenderer = function () {
  12834. return this._boundingBoxRenderer;
  12835. };
  12836. Scene.prototype.getOutlineRenderer = function () {
  12837. return this._outlineRenderer;
  12838. };
  12839. Scene.prototype.getEngine = function () {
  12840. return this._engine;
  12841. };
  12842. Scene.prototype.getTotalVertices = function () {
  12843. return this._totalVertices;
  12844. };
  12845. Scene.prototype.getActiveIndices = function () {
  12846. return this._activeIndices;
  12847. };
  12848. Scene.prototype.getActiveParticles = function () {
  12849. return this._activeParticles;
  12850. };
  12851. Scene.prototype.getActiveBones = function () {
  12852. return this._activeBones;
  12853. };
  12854. // Stats
  12855. Scene.prototype.getLastFrameDuration = function () {
  12856. return this._lastFrameDuration;
  12857. };
  12858. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12859. return this._evaluateActiveMeshesDuration;
  12860. };
  12861. Scene.prototype.getActiveMeshes = function () {
  12862. return this._activeMeshes;
  12863. };
  12864. Scene.prototype.getRenderTargetsDuration = function () {
  12865. return this._renderTargetsDuration;
  12866. };
  12867. Scene.prototype.getRenderDuration = function () {
  12868. return this._renderDuration;
  12869. };
  12870. Scene.prototype.getParticlesDuration = function () {
  12871. return this._particlesDuration;
  12872. };
  12873. Scene.prototype.getSpritesDuration = function () {
  12874. return this._spritesDuration;
  12875. };
  12876. Scene.prototype.getAnimationRatio = function () {
  12877. return this._animationRatio;
  12878. };
  12879. Scene.prototype.getRenderId = function () {
  12880. return this._renderId;
  12881. };
  12882. Scene.prototype.incrementRenderId = function () {
  12883. this._renderId++;
  12884. };
  12885. Scene.prototype._updatePointerPosition = function (evt) {
  12886. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12887. this._pointerX = evt.clientX - canvasRect.left;
  12888. this._pointerY = evt.clientY - canvasRect.top;
  12889. this._unTranslatedPointerX = this._pointerX;
  12890. this._unTranslatedPointerY = this._pointerY;
  12891. if (this.cameraToUseForPointers) {
  12892. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12893. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12894. }
  12895. };
  12896. // Pointers handling
  12897. Scene.prototype.attachControl = function () {
  12898. var _this = this;
  12899. var spritePredicate = function (sprite) {
  12900. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12901. };
  12902. this._onPointerMove = function (evt) {
  12903. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12904. return;
  12905. }
  12906. var canvas = _this._engine.getRenderingCanvas();
  12907. _this._updatePointerPosition(evt);
  12908. // Meshes
  12909. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  12910. if (pickResult.hit && pickResult.pickedMesh) {
  12911. _this.setPointerOverSprite(null);
  12912. _this.setPointerOverMesh(pickResult.pickedMesh);
  12913. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12914. canvas.style.cursor = "pointer";
  12915. }
  12916. else {
  12917. canvas.style.cursor = "";
  12918. }
  12919. }
  12920. else {
  12921. _this.setPointerOverMesh(null);
  12922. // Sprites
  12923. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12924. if (pickResult.hit && pickResult.pickedSprite) {
  12925. canvas.style.cursor = "pointer";
  12926. _this.setPointerOverSprite(pickResult.pickedSprite);
  12927. }
  12928. else {
  12929. _this.setPointerOverSprite(null);
  12930. // Restore pointer
  12931. canvas.style.cursor = "";
  12932. }
  12933. }
  12934. if (_this.onPointerMove) {
  12935. _this.onPointerMove(evt, pickResult);
  12936. }
  12937. };
  12938. this._onPointerDown = function (evt) {
  12939. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12940. return;
  12941. }
  12942. _this._updatePointerPosition(evt);
  12943. _this._startingPointerPosition.x = _this._pointerX;
  12944. _this._startingPointerPosition.y = _this._pointerY;
  12945. _this._startingPointerTime = new Date().getTime();
  12946. var predicate = null;
  12947. // Meshes
  12948. _this._pickedDownMesh = null;
  12949. if (!_this.onPointerDown && !_this.onPointerPick) {
  12950. predicate = function (mesh) {
  12951. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12952. };
  12953. }
  12954. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12955. if (pickResult.hit && pickResult.pickedMesh) {
  12956. if (pickResult.pickedMesh.actionManager) {
  12957. _this._pickedDownMesh = pickResult.pickedMesh;
  12958. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12959. switch (evt.button) {
  12960. case 0:
  12961. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12962. break;
  12963. case 1:
  12964. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12965. break;
  12966. case 2:
  12967. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12968. break;
  12969. }
  12970. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12971. }
  12972. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12973. var that = _this;
  12974. window.setTimeout(function () {
  12975. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12976. if (pickResult.hit && pickResult.pickedMesh) {
  12977. if (pickResult.pickedMesh.actionManager) {
  12978. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12979. that._startingPointerTime = 0;
  12980. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12981. }
  12982. }
  12983. }
  12984. }, BABYLON.ActionManager.LongPressDelay);
  12985. }
  12986. }
  12987. }
  12988. if (_this.onPointerDown) {
  12989. _this.onPointerDown(evt, pickResult);
  12990. }
  12991. // Sprites
  12992. _this._pickedDownSprite = null;
  12993. if (_this.spriteManagers.length > 0) {
  12994. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12995. if (pickResult.hit && pickResult.pickedSprite) {
  12996. if (pickResult.pickedSprite.actionManager) {
  12997. _this._pickedDownSprite = pickResult.pickedSprite;
  12998. switch (evt.button) {
  12999. case 0:
  13000. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13001. break;
  13002. case 1:
  13003. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13004. break;
  13005. case 2:
  13006. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13007. break;
  13008. }
  13009. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13010. }
  13011. }
  13012. }
  13013. };
  13014. this._onPointerUp = function (evt) {
  13015. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13016. return;
  13017. }
  13018. var predicate = null;
  13019. _this._updatePointerPosition(evt);
  13020. if (!_this.onPointerUp && !_this.onPointerPick) {
  13021. predicate = function (mesh) {
  13022. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  13023. };
  13024. }
  13025. // Meshes
  13026. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  13027. if (pickResult.hit && pickResult.pickedMesh) {
  13028. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13029. _this.onPointerPick(evt, pickResult);
  13030. }
  13031. if (pickResult.pickedMesh.actionManager) {
  13032. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13033. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13034. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13035. }
  13036. }
  13037. }
  13038. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13039. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13040. }
  13041. if (_this.onPointerUp) {
  13042. _this.onPointerUp(evt, pickResult);
  13043. }
  13044. _this._startingPointerTime = 0;
  13045. // Sprites
  13046. if (_this.spriteManagers.length > 0) {
  13047. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13048. if (pickResult.hit && pickResult.pickedSprite) {
  13049. if (pickResult.pickedSprite.actionManager) {
  13050. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13051. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13052. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13053. }
  13054. }
  13055. }
  13056. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13057. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13058. }
  13059. }
  13060. };
  13061. this._onKeyDown = function (evt) {
  13062. if (_this.actionManager) {
  13063. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13064. }
  13065. };
  13066. this._onKeyUp = function (evt) {
  13067. if (_this.actionManager) {
  13068. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13069. }
  13070. };
  13071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13072. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13073. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13074. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13075. // Wheel
  13076. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13077. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13078. BABYLON.Tools.RegisterTopRootEvents([
  13079. { name: "keydown", handler: this._onKeyDown },
  13080. { name: "keyup", handler: this._onKeyUp }
  13081. ]);
  13082. };
  13083. Scene.prototype.detachControl = function () {
  13084. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13085. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13086. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13087. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13088. // Wheel
  13089. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13090. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13091. BABYLON.Tools.UnregisterTopRootEvents([
  13092. { name: "keydown", handler: this._onKeyDown },
  13093. { name: "keyup", handler: this._onKeyUp }
  13094. ]);
  13095. };
  13096. // Ready
  13097. Scene.prototype.isReady = function () {
  13098. if (this._pendingData.length > 0) {
  13099. return false;
  13100. }
  13101. var index;
  13102. for (index = 0; index < this._geometries.length; index++) {
  13103. var geometry = this._geometries[index];
  13104. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13105. return false;
  13106. }
  13107. }
  13108. for (index = 0; index < this.meshes.length; index++) {
  13109. var mesh = this.meshes[index];
  13110. if (!mesh.isReady()) {
  13111. return false;
  13112. }
  13113. var mat = mesh.material;
  13114. if (mat) {
  13115. if (!mat.isReady(mesh)) {
  13116. return false;
  13117. }
  13118. }
  13119. }
  13120. return true;
  13121. };
  13122. Scene.prototype.resetCachedMaterial = function () {
  13123. this._cachedMaterial = null;
  13124. };
  13125. Scene.prototype.registerBeforeRender = function (func) {
  13126. this._onBeforeRenderCallbacks.push(func);
  13127. };
  13128. Scene.prototype.unregisterBeforeRender = function (func) {
  13129. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13130. if (index > -1) {
  13131. this._onBeforeRenderCallbacks.splice(index, 1);
  13132. }
  13133. };
  13134. Scene.prototype.registerAfterRender = function (func) {
  13135. this._onAfterRenderCallbacks.push(func);
  13136. };
  13137. Scene.prototype.unregisterAfterRender = function (func) {
  13138. var index = this._onAfterRenderCallbacks.indexOf(func);
  13139. if (index > -1) {
  13140. this._onAfterRenderCallbacks.splice(index, 1);
  13141. }
  13142. };
  13143. Scene.prototype._addPendingData = function (data) {
  13144. this._pendingData.push(data);
  13145. };
  13146. Scene.prototype._removePendingData = function (data) {
  13147. var index = this._pendingData.indexOf(data);
  13148. if (index !== -1) {
  13149. this._pendingData.splice(index, 1);
  13150. }
  13151. };
  13152. Scene.prototype.getWaitingItemsCount = function () {
  13153. return this._pendingData.length;
  13154. };
  13155. /**
  13156. * Registers a function to be executed when the scene is ready.
  13157. * @param {Function} func - the function to be executed.
  13158. */
  13159. Scene.prototype.executeWhenReady = function (func) {
  13160. var _this = this;
  13161. this._onReadyCallbacks.push(func);
  13162. if (this._executeWhenReadyTimeoutId !== -1) {
  13163. return;
  13164. }
  13165. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13166. _this._checkIsReady();
  13167. }, 150);
  13168. };
  13169. Scene.prototype._checkIsReady = function () {
  13170. var _this = this;
  13171. if (this.isReady()) {
  13172. this._onReadyCallbacks.forEach(function (func) {
  13173. func();
  13174. });
  13175. this._onReadyCallbacks = [];
  13176. this._executeWhenReadyTimeoutId = -1;
  13177. return;
  13178. }
  13179. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13180. _this._checkIsReady();
  13181. }, 150);
  13182. };
  13183. // Animations
  13184. /**
  13185. * Will start the animation sequence of a given target
  13186. * @param target - the target
  13187. * @param {number} from - from which frame should animation start
  13188. * @param {number} to - till which frame should animation run.
  13189. * @param {boolean} [loop] - should the animation loop
  13190. * @param {number} [speedRatio] - the speed in which to run the animation
  13191. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13192. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13193. * @return {BABYLON.Animatable} the animatable object created for this animation
  13194. * @see BABYLON.Animatable
  13195. * @see http://doc.babylonjs.com/page.php?p=22081
  13196. */
  13197. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13198. if (speedRatio === void 0) { speedRatio = 1.0; }
  13199. this.stopAnimation(target);
  13200. if (!animatable) {
  13201. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13202. }
  13203. // Local animations
  13204. if (target.animations) {
  13205. animatable.appendAnimations(target, target.animations);
  13206. }
  13207. // Children animations
  13208. if (target.getAnimatables) {
  13209. var animatables = target.getAnimatables();
  13210. for (var index = 0; index < animatables.length; index++) {
  13211. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13212. }
  13213. }
  13214. return animatable;
  13215. };
  13216. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13217. if (speedRatio === undefined) {
  13218. speedRatio = 1.0;
  13219. }
  13220. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13221. return animatable;
  13222. };
  13223. Scene.prototype.getAnimatableByTarget = function (target) {
  13224. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13225. if (this._activeAnimatables[index].target === target) {
  13226. return this._activeAnimatables[index];
  13227. }
  13228. }
  13229. return null;
  13230. };
  13231. Object.defineProperty(Scene.prototype, "Animatables", {
  13232. get: function () {
  13233. return this._activeAnimatables;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. /**
  13239. * Will stop the animation of the given target
  13240. * @param target - the target
  13241. * @see beginAnimation
  13242. */
  13243. Scene.prototype.stopAnimation = function (target) {
  13244. var animatable = this.getAnimatableByTarget(target);
  13245. if (animatable) {
  13246. animatable.stop();
  13247. }
  13248. };
  13249. Scene.prototype._animate = function () {
  13250. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13251. return;
  13252. }
  13253. if (!this._animationStartDate) {
  13254. if (this._pendingData.length > 0) {
  13255. return;
  13256. }
  13257. this._animationStartDate = BABYLON.Tools.Now;
  13258. }
  13259. // Getting time
  13260. var now = BABYLON.Tools.Now;
  13261. var delay = now - this._animationStartDate;
  13262. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13263. this._activeAnimatables[index]._animate(delay);
  13264. }
  13265. };
  13266. // Matrix
  13267. Scene.prototype.getViewMatrix = function () {
  13268. return this._viewMatrix;
  13269. };
  13270. Scene.prototype.getProjectionMatrix = function () {
  13271. return this._projectionMatrix;
  13272. };
  13273. Scene.prototype.getTransformMatrix = function () {
  13274. return this._transformMatrix;
  13275. };
  13276. Scene.prototype.setTransformMatrix = function (view, projection) {
  13277. this._viewMatrix = view;
  13278. this._projectionMatrix = projection;
  13279. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13280. };
  13281. // Methods
  13282. Scene.prototype.addMesh = function (newMesh) {
  13283. newMesh.uniqueId = this._uniqueIdCounter++;
  13284. var position = this.meshes.push(newMesh);
  13285. //notify the collision coordinator
  13286. this.collisionCoordinator.onMeshAdded(newMesh);
  13287. if (this.onNewMeshAdded) {
  13288. this.onNewMeshAdded(newMesh, position, this);
  13289. }
  13290. };
  13291. Scene.prototype.removeMesh = function (toRemove) {
  13292. var index = this.meshes.indexOf(toRemove);
  13293. if (index !== -1) {
  13294. // Remove from the scene if mesh found
  13295. this.meshes.splice(index, 1);
  13296. }
  13297. //notify the collision coordinator
  13298. this.collisionCoordinator.onMeshRemoved(toRemove);
  13299. if (this.onMeshRemoved) {
  13300. this.onMeshRemoved(toRemove);
  13301. }
  13302. return index;
  13303. };
  13304. Scene.prototype.removeSkeleton = function (toRemove) {
  13305. var index = this.skeletons.indexOf(toRemove);
  13306. if (index !== -1) {
  13307. // Remove from the scene if mesh found
  13308. this.skeletons.splice(index, 1);
  13309. }
  13310. return index;
  13311. };
  13312. Scene.prototype.removeLight = function (toRemove) {
  13313. var index = this.lights.indexOf(toRemove);
  13314. if (index !== -1) {
  13315. // Remove from the scene if mesh found
  13316. this.lights.splice(index, 1);
  13317. }
  13318. if (this.onLightRemoved) {
  13319. this.onLightRemoved(toRemove);
  13320. }
  13321. return index;
  13322. };
  13323. Scene.prototype.removeCamera = function (toRemove) {
  13324. var index = this.cameras.indexOf(toRemove);
  13325. if (index !== -1) {
  13326. // Remove from the scene if mesh found
  13327. this.cameras.splice(index, 1);
  13328. }
  13329. // Remove from activeCameras
  13330. var index2 = this.activeCameras.indexOf(toRemove);
  13331. if (index2 !== -1) {
  13332. // Remove from the scene if mesh found
  13333. this.activeCameras.splice(index2, 1);
  13334. }
  13335. // Reset the activeCamera
  13336. if (this.activeCamera === toRemove) {
  13337. if (this.cameras.length > 0) {
  13338. this.activeCamera = this.cameras[0];
  13339. }
  13340. else {
  13341. this.activeCamera = null;
  13342. }
  13343. }
  13344. if (this.onCameraRemoved) {
  13345. this.onCameraRemoved(toRemove);
  13346. }
  13347. return index;
  13348. };
  13349. Scene.prototype.addLight = function (newLight) {
  13350. newLight.uniqueId = this._uniqueIdCounter++;
  13351. var position = this.lights.push(newLight);
  13352. if (this.onNewLightAdded) {
  13353. this.onNewLightAdded(newLight, position, this);
  13354. }
  13355. };
  13356. Scene.prototype.addCamera = function (newCamera) {
  13357. newCamera.uniqueId = this._uniqueIdCounter++;
  13358. var position = this.cameras.push(newCamera);
  13359. if (this.onNewCameraAdded) {
  13360. this.onNewCameraAdded(newCamera, position, this);
  13361. }
  13362. };
  13363. /**
  13364. * Switch active camera
  13365. * @param {Camera} newCamera - new active camera
  13366. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13367. */
  13368. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13369. if (attachControl === void 0) { attachControl = true; }
  13370. var canvas = this._engine.getRenderingCanvas();
  13371. this.activeCamera.detachControl(canvas);
  13372. this.activeCamera = newCamera;
  13373. if (attachControl) {
  13374. newCamera.attachControl(canvas);
  13375. }
  13376. };
  13377. /**
  13378. * sets the active camera of the scene using its ID
  13379. * @param {string} id - the camera's ID
  13380. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13381. * @see activeCamera
  13382. */
  13383. Scene.prototype.setActiveCameraByID = function (id) {
  13384. var camera = this.getCameraByID(id);
  13385. if (camera) {
  13386. this.activeCamera = camera;
  13387. return camera;
  13388. }
  13389. return null;
  13390. };
  13391. /**
  13392. * sets the active camera of the scene using its name
  13393. * @param {string} name - the camera's name
  13394. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13395. * @see activeCamera
  13396. */
  13397. Scene.prototype.setActiveCameraByName = function (name) {
  13398. var camera = this.getCameraByName(name);
  13399. if (camera) {
  13400. this.activeCamera = camera;
  13401. return camera;
  13402. }
  13403. return null;
  13404. };
  13405. /**
  13406. * get a material using its id
  13407. * @param {string} the material's ID
  13408. * @return {BABYLON.Material|null} the material or null if none found.
  13409. */
  13410. Scene.prototype.getMaterialByID = function (id) {
  13411. for (var index = 0; index < this.materials.length; index++) {
  13412. if (this.materials[index].id === id) {
  13413. return this.materials[index];
  13414. }
  13415. }
  13416. return null;
  13417. };
  13418. /**
  13419. * get a material using its name
  13420. * @param {string} the material's name
  13421. * @return {BABYLON.Material|null} the material or null if none found.
  13422. */
  13423. Scene.prototype.getMaterialByName = function (name) {
  13424. for (var index = 0; index < this.materials.length; index++) {
  13425. if (this.materials[index].name === name) {
  13426. return this.materials[index];
  13427. }
  13428. }
  13429. return null;
  13430. };
  13431. Scene.prototype.getLensFlareSystemByName = function (name) {
  13432. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13433. if (this.lensFlareSystems[index].name === name) {
  13434. return this.lensFlareSystems[index];
  13435. }
  13436. }
  13437. return null;
  13438. };
  13439. Scene.prototype.getCameraByID = function (id) {
  13440. for (var index = 0; index < this.cameras.length; index++) {
  13441. if (this.cameras[index].id === id) {
  13442. return this.cameras[index];
  13443. }
  13444. }
  13445. return null;
  13446. };
  13447. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13448. for (var index = 0; index < this.cameras.length; index++) {
  13449. if (this.cameras[index].uniqueId === uniqueId) {
  13450. return this.cameras[index];
  13451. }
  13452. }
  13453. return null;
  13454. };
  13455. /**
  13456. * get a camera using its name
  13457. * @param {string} the camera's name
  13458. * @return {BABYLON.Camera|null} the camera or null if none found.
  13459. */
  13460. Scene.prototype.getCameraByName = function (name) {
  13461. for (var index = 0; index < this.cameras.length; index++) {
  13462. if (this.cameras[index].name === name) {
  13463. return this.cameras[index];
  13464. }
  13465. }
  13466. return null;
  13467. };
  13468. /**
  13469. * get a bone using its id
  13470. * @param {string} the bone's id
  13471. * @return {BABYLON.Bone|null} the bone or null if not found
  13472. */
  13473. Scene.prototype.getBoneByID = function (id) {
  13474. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13475. var skeleton = this.skeletons[skeletonIndex];
  13476. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13477. if (skeleton.bones[boneIndex].id === id) {
  13478. return skeleton.bones[boneIndex];
  13479. }
  13480. }
  13481. }
  13482. return null;
  13483. };
  13484. /**
  13485. * get a bone using its id
  13486. * @param {string} the bone's name
  13487. * @return {BABYLON.Bone|null} the bone or null if not found
  13488. */
  13489. Scene.prototype.getBoneByName = function (name) {
  13490. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13491. var skeleton = this.skeletons[skeletonIndex];
  13492. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13493. if (skeleton.bones[boneIndex].name === name) {
  13494. return skeleton.bones[boneIndex];
  13495. }
  13496. }
  13497. }
  13498. return null;
  13499. };
  13500. /**
  13501. * get a light node using its name
  13502. * @param {string} the light's name
  13503. * @return {BABYLON.Light|null} the light or null if none found.
  13504. */
  13505. Scene.prototype.getLightByName = function (name) {
  13506. for (var index = 0; index < this.lights.length; index++) {
  13507. if (this.lights[index].name === name) {
  13508. return this.lights[index];
  13509. }
  13510. }
  13511. return null;
  13512. };
  13513. /**
  13514. * get a light node using its ID
  13515. * @param {string} the light's id
  13516. * @return {BABYLON.Light|null} the light or null if none found.
  13517. */
  13518. Scene.prototype.getLightByID = function (id) {
  13519. for (var index = 0; index < this.lights.length; index++) {
  13520. if (this.lights[index].id === id) {
  13521. return this.lights[index];
  13522. }
  13523. }
  13524. return null;
  13525. };
  13526. /**
  13527. * get a light node using its scene-generated unique ID
  13528. * @param {number} the light's unique id
  13529. * @return {BABYLON.Light|null} the light or null if none found.
  13530. */
  13531. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13532. for (var index = 0; index < this.lights.length; index++) {
  13533. if (this.lights[index].uniqueId === uniqueId) {
  13534. return this.lights[index];
  13535. }
  13536. }
  13537. return null;
  13538. };
  13539. /**
  13540. * get a particle system by id
  13541. * @param id {number} the particle system id
  13542. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13543. */
  13544. Scene.prototype.getParticleSystemByID = function (id) {
  13545. for (var index = 0; index < this.particleSystems.length; index++) {
  13546. if (this.particleSystems[index].id === id) {
  13547. return this.particleSystems[index];
  13548. }
  13549. }
  13550. return null;
  13551. };
  13552. /**
  13553. * get a geometry using its ID
  13554. * @param {string} the geometry's id
  13555. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13556. */
  13557. Scene.prototype.getGeometryByID = function (id) {
  13558. for (var index = 0; index < this._geometries.length; index++) {
  13559. if (this._geometries[index].id === id) {
  13560. return this._geometries[index];
  13561. }
  13562. }
  13563. return null;
  13564. };
  13565. /**
  13566. * add a new geometry to this scene.
  13567. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13568. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13569. * @return {boolean} was the geometry added or not
  13570. */
  13571. Scene.prototype.pushGeometry = function (geometry, force) {
  13572. if (!force && this.getGeometryByID(geometry.id)) {
  13573. return false;
  13574. }
  13575. this._geometries.push(geometry);
  13576. //notify the collision coordinator
  13577. this.collisionCoordinator.onGeometryAdded(geometry);
  13578. if (this.onGeometryAdded) {
  13579. this.onGeometryAdded(geometry);
  13580. }
  13581. return true;
  13582. };
  13583. /**
  13584. * Removes an existing geometry
  13585. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13586. * @return {boolean} was the geometry removed or not
  13587. */
  13588. Scene.prototype.removeGeometry = function (geometry) {
  13589. var index = this._geometries.indexOf(geometry);
  13590. if (index > -1) {
  13591. this._geometries.splice(index, 1);
  13592. //notify the collision coordinator
  13593. this.collisionCoordinator.onGeometryDeleted(geometry);
  13594. if (this.onGeometryRemoved) {
  13595. this.onGeometryRemoved(geometry);
  13596. }
  13597. return true;
  13598. }
  13599. return false;
  13600. };
  13601. Scene.prototype.getGeometries = function () {
  13602. return this._geometries;
  13603. };
  13604. /**
  13605. * Get the first added mesh found of a given ID
  13606. * @param {string} id - the id to search for
  13607. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13608. */
  13609. Scene.prototype.getMeshByID = function (id) {
  13610. for (var index = 0; index < this.meshes.length; index++) {
  13611. if (this.meshes[index].id === id) {
  13612. return this.meshes[index];
  13613. }
  13614. }
  13615. return null;
  13616. };
  13617. /**
  13618. * Get a mesh with its auto-generated unique id
  13619. * @param {number} uniqueId - the unique id to search for
  13620. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13621. */
  13622. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13623. for (var index = 0; index < this.meshes.length; index++) {
  13624. if (this.meshes[index].uniqueId === uniqueId) {
  13625. return this.meshes[index];
  13626. }
  13627. }
  13628. return null;
  13629. };
  13630. /**
  13631. * Get a the last added mesh found of a given ID
  13632. * @param {string} id - the id to search for
  13633. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13634. */
  13635. Scene.prototype.getLastMeshByID = function (id) {
  13636. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13637. if (this.meshes[index].id === id) {
  13638. return this.meshes[index];
  13639. }
  13640. }
  13641. return null;
  13642. };
  13643. /**
  13644. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13645. * @param {string} id - the id to search for
  13646. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13647. */
  13648. Scene.prototype.getLastEntryByID = function (id) {
  13649. var index;
  13650. for (index = this.meshes.length - 1; index >= 0; index--) {
  13651. if (this.meshes[index].id === id) {
  13652. return this.meshes[index];
  13653. }
  13654. }
  13655. for (index = this.cameras.length - 1; index >= 0; index--) {
  13656. if (this.cameras[index].id === id) {
  13657. return this.cameras[index];
  13658. }
  13659. }
  13660. for (index = this.lights.length - 1; index >= 0; index--) {
  13661. if (this.lights[index].id === id) {
  13662. return this.lights[index];
  13663. }
  13664. }
  13665. return null;
  13666. };
  13667. Scene.prototype.getNodeByID = function (id) {
  13668. var mesh = this.getMeshByID(id);
  13669. if (mesh) {
  13670. return mesh;
  13671. }
  13672. var light = this.getLightByID(id);
  13673. if (light) {
  13674. return light;
  13675. }
  13676. var camera = this.getCameraByID(id);
  13677. if (camera) {
  13678. return camera;
  13679. }
  13680. var bone = this.getBoneByID(id);
  13681. return bone;
  13682. };
  13683. Scene.prototype.getNodeByName = function (name) {
  13684. var mesh = this.getMeshByName(name);
  13685. if (mesh) {
  13686. return mesh;
  13687. }
  13688. var light = this.getLightByName(name);
  13689. if (light) {
  13690. return light;
  13691. }
  13692. var camera = this.getCameraByName(name);
  13693. if (camera) {
  13694. return camera;
  13695. }
  13696. var bone = this.getBoneByName(name);
  13697. return bone;
  13698. };
  13699. Scene.prototype.getMeshByName = function (name) {
  13700. for (var index = 0; index < this.meshes.length; index++) {
  13701. if (this.meshes[index].name === name) {
  13702. return this.meshes[index];
  13703. }
  13704. }
  13705. return null;
  13706. };
  13707. Scene.prototype.getSoundByName = function (name) {
  13708. var index;
  13709. if (BABYLON.AudioEngine) {
  13710. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13711. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13712. return this.mainSoundTrack.soundCollection[index];
  13713. }
  13714. }
  13715. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13716. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13717. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13718. return this.soundTracks[sdIndex].soundCollection[index];
  13719. }
  13720. }
  13721. }
  13722. }
  13723. return null;
  13724. };
  13725. Scene.prototype.getLastSkeletonByID = function (id) {
  13726. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13727. if (this.skeletons[index].id === id) {
  13728. return this.skeletons[index];
  13729. }
  13730. }
  13731. return null;
  13732. };
  13733. Scene.prototype.getSkeletonById = function (id) {
  13734. for (var index = 0; index < this.skeletons.length; index++) {
  13735. if (this.skeletons[index].id === id) {
  13736. return this.skeletons[index];
  13737. }
  13738. }
  13739. return null;
  13740. };
  13741. Scene.prototype.getSkeletonByName = function (name) {
  13742. for (var index = 0; index < this.skeletons.length; index++) {
  13743. if (this.skeletons[index].name === name) {
  13744. return this.skeletons[index];
  13745. }
  13746. }
  13747. return null;
  13748. };
  13749. Scene.prototype.isActiveMesh = function (mesh) {
  13750. return (this._activeMeshes.indexOf(mesh) !== -1);
  13751. };
  13752. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13753. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13754. var material = subMesh.getMaterial();
  13755. if (mesh.showSubMeshesBoundingBox) {
  13756. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13757. }
  13758. if (material) {
  13759. // Render targets
  13760. if (material.getRenderTargetTextures) {
  13761. if (this._processedMaterials.indexOf(material) === -1) {
  13762. this._processedMaterials.push(material);
  13763. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13764. }
  13765. }
  13766. // Dispatch
  13767. this._activeIndices += subMesh.indexCount;
  13768. this._renderingManager.dispatch(subMesh);
  13769. }
  13770. }
  13771. };
  13772. Scene.prototype._evaluateActiveMeshes = function () {
  13773. this.activeCamera._activeMeshes.reset();
  13774. this._activeMeshes.reset();
  13775. this._renderingManager.reset();
  13776. this._processedMaterials.reset();
  13777. this._activeParticleSystems.reset();
  13778. this._activeSkeletons.reset();
  13779. this._softwareSkinnedMeshes.reset();
  13780. this._boundingBoxRenderer.reset();
  13781. this._edgesRenderers.reset();
  13782. if (!this._frustumPlanes) {
  13783. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13784. }
  13785. else {
  13786. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13787. }
  13788. // Meshes
  13789. var meshes;
  13790. var len;
  13791. if (this._selectionOctree) {
  13792. var selection = this._selectionOctree.select(this._frustumPlanes);
  13793. meshes = selection.data;
  13794. len = selection.length;
  13795. }
  13796. else {
  13797. len = this.meshes.length;
  13798. meshes = this.meshes;
  13799. }
  13800. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13801. var mesh = meshes[meshIndex];
  13802. if (mesh.isBlocked) {
  13803. continue;
  13804. }
  13805. this._totalVertices += mesh.getTotalVertices();
  13806. if (!mesh.isReady() || !mesh.isEnabled()) {
  13807. continue;
  13808. }
  13809. mesh.computeWorldMatrix();
  13810. // Intersections
  13811. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13812. this._meshesForIntersections.pushNoDuplicate(mesh);
  13813. }
  13814. // Switch to current LOD
  13815. var meshLOD = mesh.getLOD(this.activeCamera);
  13816. if (!meshLOD) {
  13817. continue;
  13818. }
  13819. mesh._preActivate();
  13820. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13821. this._activeMeshes.push(mesh);
  13822. this.activeCamera._activeMeshes.push(mesh);
  13823. mesh._activate(this._renderId);
  13824. this._activeMesh(meshLOD);
  13825. }
  13826. }
  13827. // Particle systems
  13828. var beforeParticlesDate = BABYLON.Tools.Now;
  13829. if (this.particlesEnabled) {
  13830. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13831. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13832. var particleSystem = this.particleSystems[particleIndex];
  13833. if (!particleSystem.isStarted()) {
  13834. continue;
  13835. }
  13836. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13837. this._activeParticleSystems.push(particleSystem);
  13838. particleSystem.animate();
  13839. }
  13840. }
  13841. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13842. }
  13843. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13844. };
  13845. Scene.prototype._activeMesh = function (mesh) {
  13846. if (mesh.skeleton && this.skeletonsEnabled) {
  13847. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13848. if (!mesh.computeBonesUsingShaders) {
  13849. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13850. }
  13851. }
  13852. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13853. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13854. }
  13855. if (mesh._edgesRenderer) {
  13856. this._edgesRenderers.push(mesh._edgesRenderer);
  13857. }
  13858. if (mesh && mesh.subMeshes) {
  13859. // Submeshes Octrees
  13860. var len;
  13861. var subMeshes;
  13862. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13863. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13864. len = intersections.length;
  13865. subMeshes = intersections.data;
  13866. }
  13867. else {
  13868. subMeshes = mesh.subMeshes;
  13869. len = subMeshes.length;
  13870. }
  13871. for (var subIndex = 0; subIndex < len; subIndex++) {
  13872. var subMesh = subMeshes[subIndex];
  13873. this._evaluateSubMesh(subMesh, mesh);
  13874. }
  13875. }
  13876. };
  13877. Scene.prototype.updateTransformMatrix = function (force) {
  13878. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13879. };
  13880. Scene.prototype._renderForCamera = function (camera) {
  13881. var engine = this._engine;
  13882. this.activeCamera = camera;
  13883. if (!this.activeCamera)
  13884. throw new Error("Active camera not set");
  13885. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13886. // Viewport
  13887. engine.setViewport(this.activeCamera.viewport);
  13888. // Camera
  13889. this.resetCachedMaterial();
  13890. this._renderId++;
  13891. this.updateTransformMatrix();
  13892. if (this.beforeCameraRender) {
  13893. this.beforeCameraRender(this.activeCamera);
  13894. }
  13895. // Meshes
  13896. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13897. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13898. this._evaluateActiveMeshes();
  13899. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13900. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13901. // Skeletons
  13902. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13903. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13904. skeleton.prepare();
  13905. }
  13906. // Software skinning
  13907. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13908. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13909. mesh.applySkeleton(mesh.skeleton);
  13910. }
  13911. // Render targets
  13912. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13913. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13914. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13915. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13916. var renderTarget = this._renderTargets.data[renderIndex];
  13917. if (renderTarget._shouldRender()) {
  13918. this._renderId++;
  13919. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13920. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13921. }
  13922. }
  13923. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13924. this._renderId++;
  13925. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13926. }
  13927. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13928. // Prepare Frame
  13929. this.postProcessManager._prepareFrame();
  13930. var beforeRenderDate = BABYLON.Tools.Now;
  13931. // Backgrounds
  13932. var layerIndex;
  13933. var layer;
  13934. if (this.layers.length) {
  13935. engine.setDepthBuffer(false);
  13936. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13937. layer = this.layers[layerIndex];
  13938. if (layer.isBackground) {
  13939. layer.render();
  13940. }
  13941. }
  13942. engine.setDepthBuffer(true);
  13943. }
  13944. // Render
  13945. BABYLON.Tools.StartPerformanceCounter("Main render");
  13946. this._renderingManager.render(null, null, true, true);
  13947. BABYLON.Tools.EndPerformanceCounter("Main render");
  13948. // Bounding boxes
  13949. this._boundingBoxRenderer.render();
  13950. // Edges
  13951. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13952. this._edgesRenderers.data[edgesRendererIndex].render();
  13953. }
  13954. // Lens flares
  13955. if (this.lensFlaresEnabled) {
  13956. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13957. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13958. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13959. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13960. lensFlareSystem.render();
  13961. }
  13962. }
  13963. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13964. }
  13965. // Foregrounds
  13966. if (this.layers.length) {
  13967. engine.setDepthBuffer(false);
  13968. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13969. layer = this.layers[layerIndex];
  13970. if (!layer.isBackground) {
  13971. layer.render();
  13972. }
  13973. }
  13974. engine.setDepthBuffer(true);
  13975. }
  13976. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13977. // Finalize frame
  13978. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13979. // Update camera
  13980. this.activeCamera._updateFromScene();
  13981. // Reset some special arrays
  13982. this._renderTargets.reset();
  13983. if (this.afterCameraRender) {
  13984. this.afterCameraRender(this.activeCamera);
  13985. }
  13986. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13987. };
  13988. Scene.prototype._processSubCameras = function (camera) {
  13989. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13990. this._renderForCamera(camera);
  13991. return;
  13992. }
  13993. // rig cameras
  13994. for (var index = 0; index < camera._rigCameras.length; index++) {
  13995. this._renderForCamera(camera._rigCameras[index]);
  13996. }
  13997. this.activeCamera = camera;
  13998. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13999. // Update camera
  14000. this.activeCamera._updateFromScene();
  14001. };
  14002. Scene.prototype._checkIntersections = function () {
  14003. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14004. var sourceMesh = this._meshesForIntersections.data[index];
  14005. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14006. var action = sourceMesh.actionManager.actions[actionIndex];
  14007. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14008. var parameters = action.getTriggerParameter();
  14009. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14010. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14011. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14012. if (areIntersecting && currentIntersectionInProgress === -1) {
  14013. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14014. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14015. sourceMesh._intersectionsInProgress.push(otherMesh);
  14016. }
  14017. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14018. sourceMesh._intersectionsInProgress.push(otherMesh);
  14019. }
  14020. }
  14021. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14022. //They intersected, and now they don't.
  14023. //is this trigger an exit trigger? execute an event.
  14024. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14025. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14026. }
  14027. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14028. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14029. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14030. }
  14031. }
  14032. }
  14033. }
  14034. }
  14035. };
  14036. Scene.prototype.render = function () {
  14037. var startDate = BABYLON.Tools.Now;
  14038. this._particlesDuration = 0;
  14039. this._spritesDuration = 0;
  14040. this._activeParticles = 0;
  14041. this._renderDuration = 0;
  14042. this._renderTargetsDuration = 0;
  14043. this._evaluateActiveMeshesDuration = 0;
  14044. this._totalVertices = 0;
  14045. this._activeIndices = 0;
  14046. this._activeBones = 0;
  14047. this.getEngine().resetDrawCalls();
  14048. this._meshesForIntersections.reset();
  14049. this.resetCachedMaterial();
  14050. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14051. // Actions
  14052. if (this.actionManager) {
  14053. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14054. }
  14055. //Simplification Queue
  14056. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14057. this.simplificationQueue.executeNext();
  14058. }
  14059. // Animations
  14060. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14061. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14062. this._animate();
  14063. // Physics
  14064. if (this._physicsEngine) {
  14065. BABYLON.Tools.StartPerformanceCounter("Physics");
  14066. this._physicsEngine._step(deltaTime / 1000.0);
  14067. BABYLON.Tools.EndPerformanceCounter("Physics");
  14068. }
  14069. // Before render
  14070. if (this.beforeRender) {
  14071. this.beforeRender();
  14072. }
  14073. var callbackIndex;
  14074. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14075. this._onBeforeRenderCallbacks[callbackIndex]();
  14076. }
  14077. // Customs render targets
  14078. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14079. var engine = this.getEngine();
  14080. var currentActiveCamera = this.activeCamera;
  14081. if (this.renderTargetsEnabled) {
  14082. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14083. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14084. var renderTarget = this.customRenderTargets[customIndex];
  14085. if (renderTarget._shouldRender()) {
  14086. this._renderId++;
  14087. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14088. if (!this.activeCamera)
  14089. throw new Error("Active camera not set");
  14090. // Viewport
  14091. engine.setViewport(this.activeCamera.viewport);
  14092. // Camera
  14093. this.updateTransformMatrix();
  14094. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14095. }
  14096. }
  14097. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14098. this._renderId++;
  14099. }
  14100. if (this.customRenderTargets.length > 0) {
  14101. engine.restoreDefaultFramebuffer();
  14102. }
  14103. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14104. this.activeCamera = currentActiveCamera;
  14105. // Procedural textures
  14106. if (this.proceduralTexturesEnabled) {
  14107. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14108. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14109. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14110. if (proceduralTexture._shouldRender()) {
  14111. proceduralTexture.render();
  14112. }
  14113. }
  14114. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14115. }
  14116. // Clear
  14117. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14118. // Shadows
  14119. if (this.shadowsEnabled) {
  14120. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14121. var light = this.lights[lightIndex];
  14122. var shadowGenerator = light.getShadowGenerator();
  14123. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14124. this._renderTargets.push(shadowGenerator.getShadowMap());
  14125. }
  14126. }
  14127. }
  14128. // Depth renderer
  14129. if (this._depthRenderer) {
  14130. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14131. }
  14132. // RenderPipeline
  14133. this.postProcessRenderPipelineManager.update();
  14134. // Multi-cameras?
  14135. if (this.activeCameras.length > 0) {
  14136. var currentRenderId = this._renderId;
  14137. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14138. this._renderId = currentRenderId;
  14139. if (cameraIndex > 0) {
  14140. this._engine.clear(0, false, true);
  14141. }
  14142. this._processSubCameras(this.activeCameras[cameraIndex]);
  14143. }
  14144. }
  14145. else {
  14146. if (!this.activeCamera) {
  14147. throw new Error("No camera defined");
  14148. }
  14149. this._processSubCameras(this.activeCamera);
  14150. }
  14151. // Intersection checks
  14152. this._checkIntersections();
  14153. // Update the audio listener attached to the camera
  14154. if (BABYLON.AudioEngine) {
  14155. this._updateAudioParameters();
  14156. }
  14157. // After render
  14158. if (this.afterRender) {
  14159. this.afterRender();
  14160. }
  14161. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14162. this._onAfterRenderCallbacks[callbackIndex]();
  14163. }
  14164. // Cleaning
  14165. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14166. this._toBeDisposed.data[index].dispose();
  14167. this._toBeDisposed[index] = null;
  14168. }
  14169. this._toBeDisposed.reset();
  14170. if (this.dumpNextRenderTargets) {
  14171. this.dumpNextRenderTargets = false;
  14172. }
  14173. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14174. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14175. };
  14176. Scene.prototype._updateAudioParameters = function () {
  14177. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14178. return;
  14179. }
  14180. var listeningCamera;
  14181. var audioEngine = BABYLON.Engine.audioEngine;
  14182. if (this.activeCameras.length > 0) {
  14183. listeningCamera = this.activeCameras[0];
  14184. }
  14185. else {
  14186. listeningCamera = this.activeCamera;
  14187. }
  14188. if (listeningCamera && audioEngine.canUseWebAudio) {
  14189. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14190. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14191. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14192. cameraDirection.normalize();
  14193. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14194. var i;
  14195. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14196. var sound = this.mainSoundTrack.soundCollection[i];
  14197. if (sound.useCustomAttenuation) {
  14198. sound.updateDistanceFromListener();
  14199. }
  14200. }
  14201. for (i = 0; i < this.soundTracks.length; i++) {
  14202. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14203. sound = this.soundTracks[i].soundCollection[j];
  14204. if (sound.useCustomAttenuation) {
  14205. sound.updateDistanceFromListener();
  14206. }
  14207. }
  14208. }
  14209. }
  14210. };
  14211. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14212. // Audio
  14213. get: function () {
  14214. return this._audioEnabled;
  14215. },
  14216. set: function (value) {
  14217. this._audioEnabled = value;
  14218. if (BABYLON.AudioEngine) {
  14219. if (this._audioEnabled) {
  14220. this._enableAudio();
  14221. }
  14222. else {
  14223. this._disableAudio();
  14224. }
  14225. }
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. Scene.prototype._disableAudio = function () {
  14231. var i;
  14232. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14233. this.mainSoundTrack.soundCollection[i].pause();
  14234. }
  14235. for (i = 0; i < this.soundTracks.length; i++) {
  14236. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14237. this.soundTracks[i].soundCollection[j].pause();
  14238. }
  14239. }
  14240. };
  14241. Scene.prototype._enableAudio = function () {
  14242. var i;
  14243. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14244. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14245. this.mainSoundTrack.soundCollection[i].play();
  14246. }
  14247. }
  14248. for (i = 0; i < this.soundTracks.length; i++) {
  14249. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14250. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14251. this.soundTracks[i].soundCollection[j].play();
  14252. }
  14253. }
  14254. }
  14255. };
  14256. Object.defineProperty(Scene.prototype, "headphone", {
  14257. get: function () {
  14258. return this._headphone;
  14259. },
  14260. set: function (value) {
  14261. this._headphone = value;
  14262. if (BABYLON.AudioEngine) {
  14263. if (this._headphone) {
  14264. this._switchAudioModeForHeadphones();
  14265. }
  14266. else {
  14267. this._switchAudioModeForNormalSpeakers();
  14268. }
  14269. }
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Scene.prototype._switchAudioModeForHeadphones = function () {
  14275. this.mainSoundTrack.switchPanningModelToHRTF();
  14276. for (var i = 0; i < this.soundTracks.length; i++) {
  14277. this.soundTracks[i].switchPanningModelToHRTF();
  14278. }
  14279. };
  14280. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14281. this.mainSoundTrack.switchPanningModelToEqualPower();
  14282. for (var i = 0; i < this.soundTracks.length; i++) {
  14283. this.soundTracks[i].switchPanningModelToEqualPower();
  14284. }
  14285. };
  14286. Scene.prototype.enableDepthRenderer = function () {
  14287. if (this._depthRenderer) {
  14288. return this._depthRenderer;
  14289. }
  14290. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14291. return this._depthRenderer;
  14292. };
  14293. Scene.prototype.disableDepthRenderer = function () {
  14294. if (!this._depthRenderer) {
  14295. return;
  14296. }
  14297. this._depthRenderer.dispose();
  14298. this._depthRenderer = null;
  14299. };
  14300. Scene.prototype.freezeMaterials = function () {
  14301. for (var i = 0; i < this.materials.length; i++) {
  14302. this.materials[i].freeze();
  14303. }
  14304. };
  14305. Scene.prototype.unfreezeMaterials = function () {
  14306. for (var i = 0; i < this.materials.length; i++) {
  14307. this.materials[i].unfreeze();
  14308. }
  14309. };
  14310. Scene.prototype.dispose = function () {
  14311. this.beforeRender = null;
  14312. this.afterRender = null;
  14313. this.skeletons = [];
  14314. this._boundingBoxRenderer.dispose();
  14315. if (this._depthRenderer) {
  14316. this._depthRenderer.dispose();
  14317. }
  14318. // Debug layer
  14319. this.debugLayer.hide();
  14320. // Events
  14321. if (this.onDispose) {
  14322. this.onDispose();
  14323. }
  14324. this._onBeforeRenderCallbacks = [];
  14325. this._onAfterRenderCallbacks = [];
  14326. this.detachControl();
  14327. // Release sounds & sounds tracks
  14328. if (BABYLON.AudioEngine) {
  14329. this.disposeSounds();
  14330. }
  14331. // Detach cameras
  14332. var canvas = this._engine.getRenderingCanvas();
  14333. var index;
  14334. for (index = 0; index < this.cameras.length; index++) {
  14335. this.cameras[index].detachControl(canvas);
  14336. }
  14337. // Release lights
  14338. while (this.lights.length) {
  14339. this.lights[0].dispose();
  14340. }
  14341. // Release meshes
  14342. while (this.meshes.length) {
  14343. this.meshes[0].dispose(true);
  14344. }
  14345. // Release cameras
  14346. while (this.cameras.length) {
  14347. this.cameras[0].dispose();
  14348. }
  14349. // Release materials
  14350. while (this.materials.length) {
  14351. this.materials[0].dispose();
  14352. }
  14353. // Release particles
  14354. while (this.particleSystems.length) {
  14355. this.particleSystems[0].dispose();
  14356. }
  14357. // Release sprites
  14358. while (this.spriteManagers.length) {
  14359. this.spriteManagers[0].dispose();
  14360. }
  14361. // Release layers
  14362. while (this.layers.length) {
  14363. this.layers[0].dispose();
  14364. }
  14365. // Release textures
  14366. while (this.textures.length) {
  14367. this.textures[0].dispose();
  14368. }
  14369. // Post-processes
  14370. this.postProcessManager.dispose();
  14371. // Physics
  14372. if (this._physicsEngine) {
  14373. this.disablePhysicsEngine();
  14374. }
  14375. // Remove from engine
  14376. index = this._engine.scenes.indexOf(this);
  14377. if (index > -1) {
  14378. this._engine.scenes.splice(index, 1);
  14379. }
  14380. this._engine.wipeCaches();
  14381. };
  14382. // Release sounds & sounds tracks
  14383. Scene.prototype.disposeSounds = function () {
  14384. this.mainSoundTrack.dispose();
  14385. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14386. this.soundTracks[scIndex].dispose();
  14387. }
  14388. };
  14389. // Octrees
  14390. Scene.prototype.getWorldExtends = function () {
  14391. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14392. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14393. for (var index = 0; index < this.meshes.length; index++) {
  14394. var mesh = this.meshes[index];
  14395. mesh.computeWorldMatrix(true);
  14396. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14397. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14398. BABYLON.Tools.CheckExtends(minBox, min, max);
  14399. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14400. }
  14401. return {
  14402. min: min,
  14403. max: max
  14404. };
  14405. };
  14406. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14407. if (maxCapacity === void 0) { maxCapacity = 64; }
  14408. if (maxDepth === void 0) { maxDepth = 2; }
  14409. if (!this._selectionOctree) {
  14410. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14411. }
  14412. var worldExtends = this.getWorldExtends();
  14413. // Update octree
  14414. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14415. return this._selectionOctree;
  14416. };
  14417. // Picking
  14418. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14419. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14420. var engine = this._engine;
  14421. if (!camera) {
  14422. if (!this.activeCamera)
  14423. throw new Error("Active camera not set");
  14424. camera = this.activeCamera;
  14425. }
  14426. var cameraViewport = camera.viewport;
  14427. var viewport = cameraViewport.toGlobal(engine);
  14428. // Moving coordinates to local viewport world
  14429. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14430. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14431. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14432. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14433. };
  14434. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14435. var engine = this._engine;
  14436. if (!camera) {
  14437. if (!this.activeCamera)
  14438. throw new Error("Active camera not set");
  14439. camera = this.activeCamera;
  14440. }
  14441. var cameraViewport = camera.viewport;
  14442. var viewport = cameraViewport.toGlobal(engine);
  14443. var identity = BABYLON.Matrix.Identity();
  14444. // Moving coordinates to local viewport world
  14445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14447. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14448. };
  14449. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14450. var pickingInfo = null;
  14451. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14452. var mesh = this.meshes[meshIndex];
  14453. if (predicate) {
  14454. if (!predicate(mesh)) {
  14455. continue;
  14456. }
  14457. }
  14458. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14459. continue;
  14460. }
  14461. var world = mesh.getWorldMatrix();
  14462. var ray = rayFunction(world);
  14463. var result = mesh.intersects(ray, fastCheck);
  14464. if (!result || !result.hit)
  14465. continue;
  14466. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14467. continue;
  14468. pickingInfo = result;
  14469. if (fastCheck) {
  14470. break;
  14471. }
  14472. }
  14473. return pickingInfo || new BABYLON.PickingInfo();
  14474. };
  14475. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14476. var pickingInfo = null;
  14477. camera = camera || this.activeCamera;
  14478. if (this.spriteManagers.length > 0) {
  14479. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14480. var spriteManager = this.spriteManagers[spriteIndex];
  14481. if (!spriteManager.isPickable) {
  14482. continue;
  14483. }
  14484. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14485. if (!result || !result.hit)
  14486. continue;
  14487. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14488. continue;
  14489. pickingInfo = result;
  14490. if (fastCheck) {
  14491. break;
  14492. }
  14493. }
  14494. }
  14495. return pickingInfo || new BABYLON.PickingInfo();
  14496. };
  14497. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14498. var _this = this;
  14499. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14500. /// <param name="x">X position on screen</param>
  14501. /// <param name="y">Y position on screen</param>
  14502. /// <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>
  14503. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14504. /// <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>
  14505. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14506. };
  14507. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14508. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14509. /// <param name="x">X position on screen</param>
  14510. /// <param name="y">Y position on screen</param>
  14511. /// <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>
  14512. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14513. /// <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>
  14514. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14515. };
  14516. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14517. var _this = this;
  14518. return this._internalPick(function (world) {
  14519. if (!_this._pickWithRayInverseMatrix) {
  14520. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14521. }
  14522. world.invertToRef(_this._pickWithRayInverseMatrix);
  14523. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14524. }, predicate, fastCheck);
  14525. };
  14526. Scene.prototype.setPointerOverMesh = function (mesh) {
  14527. if (this._pointerOverMesh === mesh) {
  14528. return;
  14529. }
  14530. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14531. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14532. }
  14533. this._pointerOverMesh = mesh;
  14534. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14535. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14536. }
  14537. };
  14538. Scene.prototype.getPointerOverMesh = function () {
  14539. return this._pointerOverMesh;
  14540. };
  14541. Scene.prototype.setPointerOverSprite = function (sprite) {
  14542. if (this._pointerOverSprite === sprite) {
  14543. return;
  14544. }
  14545. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14546. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14547. }
  14548. this._pointerOverSprite = sprite;
  14549. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14550. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14551. }
  14552. };
  14553. Scene.prototype.getPointerOverSprite = function () {
  14554. return this._pointerOverSprite;
  14555. };
  14556. // Physics
  14557. Scene.prototype.getPhysicsEngine = function () {
  14558. return this._physicsEngine;
  14559. };
  14560. /**
  14561. * Enables physics to the current scene
  14562. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14563. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14564. * @return {boolean} was the physics engine initialized
  14565. */
  14566. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14567. if (this._physicsEngine) {
  14568. return true;
  14569. }
  14570. try {
  14571. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14572. return true;
  14573. }
  14574. catch (e) {
  14575. BABYLON.Tools.Error(e.message);
  14576. return false;
  14577. }
  14578. };
  14579. Scene.prototype.disablePhysicsEngine = function () {
  14580. if (!this._physicsEngine) {
  14581. return;
  14582. }
  14583. this._physicsEngine.dispose();
  14584. this._physicsEngine = undefined;
  14585. };
  14586. Scene.prototype.isPhysicsEnabled = function () {
  14587. return this._physicsEngine !== undefined;
  14588. };
  14589. /**
  14590. *
  14591. * Sets the gravity of the physics engine (and NOT of the scene)
  14592. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14593. */
  14594. Scene.prototype.setGravity = function (gravity) {
  14595. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14596. if (!this._physicsEngine) {
  14597. return;
  14598. }
  14599. this._physicsEngine.setGravity(gravity);
  14600. };
  14601. /**
  14602. * Legacy support, using the new API
  14603. * @Deprecated
  14604. */
  14605. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14606. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14607. if (parts.parts) {
  14608. options = parts;
  14609. parts = parts.parts;
  14610. }
  14611. var mainMesh = parts[0].mesh;
  14612. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14613. for (var index = 1; index < parts.length; index++) {
  14614. var mesh = parts[index].mesh;
  14615. if (mesh.parent !== mainMesh) {
  14616. mesh.position = mesh.position.subtract(mainMesh.position);
  14617. mesh.parent = mainMesh;
  14618. }
  14619. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14620. }
  14621. mainMesh.physicsImpostor.forceUpdate();
  14622. };
  14623. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14624. var mesh = compound.parts[0].mesh;
  14625. mesh.physicsImpostor.dispose(true);
  14626. mesh.physicsImpostor = null;
  14627. };
  14628. // Misc.
  14629. Scene.prototype.createDefaultCameraOrLight = function () {
  14630. // Light
  14631. if (this.lights.length === 0) {
  14632. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14633. }
  14634. // Camera
  14635. if (!this.activeCamera) {
  14636. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14637. // Compute position
  14638. var worldExtends = this.getWorldExtends();
  14639. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14640. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14641. camera.setTarget(worldCenter);
  14642. this.activeCamera = camera;
  14643. }
  14644. };
  14645. // Tags
  14646. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14647. if (tagsQuery === undefined) {
  14648. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14649. return list;
  14650. }
  14651. var listByTags = [];
  14652. forEach = forEach || (function (item) { return; });
  14653. for (var i in list) {
  14654. var item = list[i];
  14655. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14656. listByTags.push(item);
  14657. forEach(item);
  14658. }
  14659. }
  14660. return listByTags;
  14661. };
  14662. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14663. return this._getByTags(this.meshes, tagsQuery, forEach);
  14664. };
  14665. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14666. return this._getByTags(this.cameras, tagsQuery, forEach);
  14667. };
  14668. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14669. return this._getByTags(this.lights, tagsQuery, forEach);
  14670. };
  14671. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14672. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14673. };
  14674. // Statics
  14675. Scene._FOGMODE_NONE = 0;
  14676. Scene._FOGMODE_EXP = 1;
  14677. Scene._FOGMODE_EXP2 = 2;
  14678. Scene._FOGMODE_LINEAR = 3;
  14679. Scene.MinDeltaTime = 1.0;
  14680. Scene.MaxDeltaTime = 1000.0;
  14681. return Scene;
  14682. })();
  14683. BABYLON.Scene = Scene;
  14684. })(BABYLON || (BABYLON = {}));
  14685. var BABYLON;
  14686. (function (BABYLON) {
  14687. var VertexBuffer = (function () {
  14688. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14689. if (engine instanceof BABYLON.Mesh) {
  14690. this._engine = engine.getScene().getEngine();
  14691. }
  14692. else {
  14693. this._engine = engine;
  14694. }
  14695. this._updatable = updatable;
  14696. this._data = data;
  14697. if (!postponeInternalCreation) {
  14698. this.create();
  14699. }
  14700. this._kind = kind;
  14701. if (stride) {
  14702. this._strideSize = stride;
  14703. return;
  14704. }
  14705. // Deduce stride from kind
  14706. switch (kind) {
  14707. case VertexBuffer.PositionKind:
  14708. this._strideSize = 3;
  14709. break;
  14710. case VertexBuffer.NormalKind:
  14711. this._strideSize = 3;
  14712. break;
  14713. case VertexBuffer.UVKind:
  14714. case VertexBuffer.UV2Kind:
  14715. case VertexBuffer.UV3Kind:
  14716. case VertexBuffer.UV4Kind:
  14717. case VertexBuffer.UV5Kind:
  14718. case VertexBuffer.UV6Kind:
  14719. this._strideSize = 2;
  14720. break;
  14721. case VertexBuffer.ColorKind:
  14722. this._strideSize = 4;
  14723. break;
  14724. case VertexBuffer.MatricesIndicesKind:
  14725. case VertexBuffer.MatricesIndicesExtraKind:
  14726. this._strideSize = 4;
  14727. break;
  14728. case VertexBuffer.MatricesWeightsKind:
  14729. case VertexBuffer.MatricesWeightsExtraKind:
  14730. this._strideSize = 4;
  14731. break;
  14732. }
  14733. }
  14734. // Properties
  14735. VertexBuffer.prototype.isUpdatable = function () {
  14736. return this._updatable;
  14737. };
  14738. VertexBuffer.prototype.getData = function () {
  14739. return this._data;
  14740. };
  14741. VertexBuffer.prototype.getBuffer = function () {
  14742. return this._buffer;
  14743. };
  14744. VertexBuffer.prototype.getStrideSize = function () {
  14745. return this._strideSize;
  14746. };
  14747. // Methods
  14748. VertexBuffer.prototype.create = function (data) {
  14749. if (!data && this._buffer) {
  14750. return; // nothing to do
  14751. }
  14752. data = data || this._data;
  14753. if (!this._buffer) {
  14754. if (this._updatable) {
  14755. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14756. }
  14757. else {
  14758. this._buffer = this._engine.createVertexBuffer(data);
  14759. }
  14760. }
  14761. if (this._updatable) {
  14762. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14763. this._data = data;
  14764. }
  14765. };
  14766. VertexBuffer.prototype.update = function (data) {
  14767. this.create(data);
  14768. };
  14769. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14770. if (!this._buffer) {
  14771. return;
  14772. }
  14773. if (this._updatable) {
  14774. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14775. this._data = null;
  14776. }
  14777. };
  14778. VertexBuffer.prototype.dispose = function () {
  14779. if (!this._buffer) {
  14780. return;
  14781. }
  14782. if (this._engine._releaseBuffer(this._buffer)) {
  14783. this._buffer = null;
  14784. }
  14785. };
  14786. Object.defineProperty(VertexBuffer, "PositionKind", {
  14787. get: function () {
  14788. return VertexBuffer._PositionKind;
  14789. },
  14790. enumerable: true,
  14791. configurable: true
  14792. });
  14793. Object.defineProperty(VertexBuffer, "NormalKind", {
  14794. get: function () {
  14795. return VertexBuffer._NormalKind;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. Object.defineProperty(VertexBuffer, "UVKind", {
  14801. get: function () {
  14802. return VertexBuffer._UVKind;
  14803. },
  14804. enumerable: true,
  14805. configurable: true
  14806. });
  14807. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14808. get: function () {
  14809. return VertexBuffer._UV2Kind;
  14810. },
  14811. enumerable: true,
  14812. configurable: true
  14813. });
  14814. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14815. get: function () {
  14816. return VertexBuffer._UV3Kind;
  14817. },
  14818. enumerable: true,
  14819. configurable: true
  14820. });
  14821. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14822. get: function () {
  14823. return VertexBuffer._UV4Kind;
  14824. },
  14825. enumerable: true,
  14826. configurable: true
  14827. });
  14828. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14829. get: function () {
  14830. return VertexBuffer._UV5Kind;
  14831. },
  14832. enumerable: true,
  14833. configurable: true
  14834. });
  14835. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14836. get: function () {
  14837. return VertexBuffer._UV6Kind;
  14838. },
  14839. enumerable: true,
  14840. configurable: true
  14841. });
  14842. Object.defineProperty(VertexBuffer, "ColorKind", {
  14843. get: function () {
  14844. return VertexBuffer._ColorKind;
  14845. },
  14846. enumerable: true,
  14847. configurable: true
  14848. });
  14849. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14850. get: function () {
  14851. return VertexBuffer._MatricesIndicesKind;
  14852. },
  14853. enumerable: true,
  14854. configurable: true
  14855. });
  14856. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14857. get: function () {
  14858. return VertexBuffer._MatricesWeightsKind;
  14859. },
  14860. enumerable: true,
  14861. configurable: true
  14862. });
  14863. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14864. get: function () {
  14865. return VertexBuffer._MatricesIndicesExtraKind;
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14871. get: function () {
  14872. return VertexBuffer._MatricesWeightsExtraKind;
  14873. },
  14874. enumerable: true,
  14875. configurable: true
  14876. });
  14877. // Enums
  14878. VertexBuffer._PositionKind = "position";
  14879. VertexBuffer._NormalKind = "normal";
  14880. VertexBuffer._UVKind = "uv";
  14881. VertexBuffer._UV2Kind = "uv2";
  14882. VertexBuffer._UV3Kind = "uv3";
  14883. VertexBuffer._UV4Kind = "uv4";
  14884. VertexBuffer._UV5Kind = "uv5";
  14885. VertexBuffer._UV6Kind = "uv6";
  14886. VertexBuffer._ColorKind = "color";
  14887. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14888. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14889. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14890. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14891. return VertexBuffer;
  14892. })();
  14893. BABYLON.VertexBuffer = VertexBuffer;
  14894. })(BABYLON || (BABYLON = {}));
  14895. var BABYLON;
  14896. (function (BABYLON) {
  14897. /**
  14898. * Creates an instance based on a source mesh.
  14899. */
  14900. var InstancedMesh = (function (_super) {
  14901. __extends(InstancedMesh, _super);
  14902. function InstancedMesh(name, source) {
  14903. _super.call(this, name, source.getScene());
  14904. source.instances.push(this);
  14905. this._sourceMesh = source;
  14906. this.position.copyFrom(source.position);
  14907. this.rotation.copyFrom(source.rotation);
  14908. this.scaling.copyFrom(source.scaling);
  14909. if (source.rotationQuaternion) {
  14910. this.rotationQuaternion = source.rotationQuaternion.clone();
  14911. }
  14912. this.infiniteDistance = source.infiniteDistance;
  14913. this.setPivotMatrix(source.getPivotMatrix());
  14914. this.refreshBoundingInfo();
  14915. this._syncSubMeshes();
  14916. }
  14917. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14918. // Methods
  14919. get: function () {
  14920. return this._sourceMesh.receiveShadows;
  14921. },
  14922. enumerable: true,
  14923. configurable: true
  14924. });
  14925. Object.defineProperty(InstancedMesh.prototype, "material", {
  14926. get: function () {
  14927. return this._sourceMesh.material;
  14928. },
  14929. enumerable: true,
  14930. configurable: true
  14931. });
  14932. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14933. get: function () {
  14934. return this._sourceMesh.visibility;
  14935. },
  14936. enumerable: true,
  14937. configurable: true
  14938. });
  14939. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14940. get: function () {
  14941. return this._sourceMesh.skeleton;
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14947. get: function () {
  14948. return this._sourceMesh.renderingGroupId;
  14949. },
  14950. enumerable: true,
  14951. configurable: true
  14952. });
  14953. InstancedMesh.prototype.getTotalVertices = function () {
  14954. return this._sourceMesh.getTotalVertices();
  14955. };
  14956. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14957. get: function () {
  14958. return this._sourceMesh;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14964. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14965. };
  14966. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14967. return this._sourceMesh.isVerticesDataPresent(kind);
  14968. };
  14969. InstancedMesh.prototype.getIndices = function () {
  14970. return this._sourceMesh.getIndices();
  14971. };
  14972. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14973. get: function () {
  14974. return this._sourceMesh._positions;
  14975. },
  14976. enumerable: true,
  14977. configurable: true
  14978. });
  14979. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14980. var meshBB = this._sourceMesh.getBoundingInfo();
  14981. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14982. this._updateBoundingInfo();
  14983. };
  14984. InstancedMesh.prototype._preActivate = function () {
  14985. if (this._currentLOD) {
  14986. this._currentLOD._preActivate();
  14987. }
  14988. };
  14989. InstancedMesh.prototype._activate = function (renderId) {
  14990. if (this._currentLOD) {
  14991. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14992. }
  14993. };
  14994. InstancedMesh.prototype.getLOD = function (camera) {
  14995. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14996. if (this._currentLOD === this.sourceMesh) {
  14997. return this;
  14998. }
  14999. return this._currentLOD;
  15000. };
  15001. InstancedMesh.prototype._syncSubMeshes = function () {
  15002. this.releaseSubMeshes();
  15003. if (this._sourceMesh.subMeshes) {
  15004. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15005. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15006. }
  15007. }
  15008. };
  15009. InstancedMesh.prototype._generatePointsArray = function () {
  15010. return this._sourceMesh._generatePointsArray();
  15011. };
  15012. // Clone
  15013. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15014. var result = this._sourceMesh.createInstance(name);
  15015. // Deep copy
  15016. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15017. // Bounding info
  15018. this.refreshBoundingInfo();
  15019. // Parent
  15020. if (newParent) {
  15021. result.parent = newParent;
  15022. }
  15023. if (!doNotCloneChildren) {
  15024. // Children
  15025. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15026. var mesh = this.getScene().meshes[index];
  15027. if (mesh.parent === this) {
  15028. mesh.clone(mesh.name, result);
  15029. }
  15030. }
  15031. }
  15032. result.computeWorldMatrix(true);
  15033. return result;
  15034. };
  15035. // Dispoe
  15036. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15037. // Remove from mesh
  15038. var index = this._sourceMesh.instances.indexOf(this);
  15039. this._sourceMesh.instances.splice(index, 1);
  15040. _super.prototype.dispose.call(this, doNotRecurse);
  15041. };
  15042. return InstancedMesh;
  15043. })(BABYLON.AbstractMesh);
  15044. BABYLON.InstancedMesh = InstancedMesh;
  15045. })(BABYLON || (BABYLON = {}));
  15046. var BABYLON;
  15047. (function (BABYLON) {
  15048. var _InstancesBatch = (function () {
  15049. function _InstancesBatch() {
  15050. this.mustReturn = false;
  15051. this.visibleInstances = new Array();
  15052. this.renderSelf = new Array();
  15053. }
  15054. return _InstancesBatch;
  15055. })();
  15056. BABYLON._InstancesBatch = _InstancesBatch;
  15057. var Mesh = (function (_super) {
  15058. __extends(Mesh, _super);
  15059. /**
  15060. * @constructor
  15061. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15062. * @param {Scene} scene - The scene to add this mesh to.
  15063. * @param {Node} parent - The parent of this mesh, if it has one
  15064. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15065. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15066. * When false, achieved by calling a clone(), also passing False.
  15067. * This will make creation of children, recursive.
  15068. */
  15069. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15070. if (parent === void 0) { parent = null; }
  15071. _super.call(this, name, scene);
  15072. // Members
  15073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15074. this.instances = new Array();
  15075. this._LODLevels = new Array();
  15076. this._onBeforeRenderCallbacks = new Array();
  15077. this._onAfterRenderCallbacks = new Array();
  15078. this._visibleInstances = {};
  15079. this._renderIdForInstances = new Array();
  15080. this._batchCache = new _InstancesBatch();
  15081. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15082. this._sideOrientation = Mesh._DEFAULTSIDE;
  15083. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15084. if (source) {
  15085. // Geometry
  15086. if (source._geometry) {
  15087. source._geometry.applyToMesh(this);
  15088. }
  15089. // Deep copy
  15090. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  15091. // Pivot
  15092. this.setPivotMatrix(source.getPivotMatrix());
  15093. this.id = name + "." + source.id;
  15094. // Material
  15095. this.material = source.material;
  15096. var index;
  15097. if (!doNotCloneChildren) {
  15098. // Children
  15099. for (index = 0; index < scene.meshes.length; index++) {
  15100. var mesh = scene.meshes[index];
  15101. if (mesh.parent === source) {
  15102. // doNotCloneChildren is always going to be False
  15103. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15104. }
  15105. }
  15106. }
  15107. // Particles
  15108. for (index = 0; index < scene.particleSystems.length; index++) {
  15109. var system = scene.particleSystems[index];
  15110. if (system.emitter === source) {
  15111. system.clone(system.name, this);
  15112. }
  15113. }
  15114. this.computeWorldMatrix(true);
  15115. }
  15116. // Parent
  15117. if (parent !== null) {
  15118. this.parent = parent;
  15119. }
  15120. }
  15121. Object.defineProperty(Mesh, "FRONTSIDE", {
  15122. get: function () {
  15123. return Mesh._FRONTSIDE;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. Object.defineProperty(Mesh, "BACKSIDE", {
  15129. get: function () {
  15130. return Mesh._BACKSIDE;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15136. get: function () {
  15137. return Mesh._DOUBLESIDE;
  15138. },
  15139. enumerable: true,
  15140. configurable: true
  15141. });
  15142. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15143. get: function () {
  15144. return Mesh._DEFAULTSIDE;
  15145. },
  15146. enumerable: true,
  15147. configurable: true
  15148. });
  15149. Object.defineProperty(Mesh, "NO_CAP", {
  15150. get: function () {
  15151. return Mesh._NO_CAP;
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. Object.defineProperty(Mesh, "CAP_START", {
  15157. get: function () {
  15158. return Mesh._CAP_START;
  15159. },
  15160. enumerable: true,
  15161. configurable: true
  15162. });
  15163. Object.defineProperty(Mesh, "CAP_END", {
  15164. get: function () {
  15165. return Mesh._CAP_END;
  15166. },
  15167. enumerable: true,
  15168. configurable: true
  15169. });
  15170. Object.defineProperty(Mesh, "CAP_ALL", {
  15171. get: function () {
  15172. return Mesh._CAP_ALL;
  15173. },
  15174. enumerable: true,
  15175. configurable: true
  15176. });
  15177. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15178. // Methods
  15179. get: function () {
  15180. return this._LODLevels.length > 0;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Mesh.prototype._sortLODLevels = function () {
  15186. this._LODLevels.sort(function (a, b) {
  15187. if (a.distance < b.distance) {
  15188. return 1;
  15189. }
  15190. if (a.distance > b.distance) {
  15191. return -1;
  15192. }
  15193. return 0;
  15194. });
  15195. };
  15196. /**
  15197. * Add a mesh as LOD level triggered at the given distance.
  15198. * @param {number} distance - the distance from the center of the object to show this level
  15199. * @param {Mesh} mesh - the mesh to be added as LOD level
  15200. * @return {Mesh} this mesh (for chaining)
  15201. */
  15202. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15203. if (mesh && mesh._masterMesh) {
  15204. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15205. return this;
  15206. }
  15207. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15208. this._LODLevels.push(level);
  15209. if (mesh) {
  15210. mesh._masterMesh = this;
  15211. }
  15212. this._sortLODLevels();
  15213. return this;
  15214. };
  15215. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15216. for (var index = 0; index < this._LODLevels.length; index++) {
  15217. var level = this._LODLevels[index];
  15218. if (level.distance === distance) {
  15219. return level.mesh;
  15220. }
  15221. }
  15222. return null;
  15223. };
  15224. /**
  15225. * Remove a mesh from the LOD array
  15226. * @param {Mesh} mesh - the mesh to be removed.
  15227. * @return {Mesh} this mesh (for chaining)
  15228. */
  15229. Mesh.prototype.removeLODLevel = function (mesh) {
  15230. for (var index = 0; index < this._LODLevels.length; index++) {
  15231. if (this._LODLevels[index].mesh === mesh) {
  15232. this._LODLevels.splice(index, 1);
  15233. if (mesh) {
  15234. mesh._masterMesh = null;
  15235. }
  15236. }
  15237. }
  15238. this._sortLODLevels();
  15239. return this;
  15240. };
  15241. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15242. if (!this._LODLevels || this._LODLevels.length === 0) {
  15243. return this;
  15244. }
  15245. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15246. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15247. if (this.onLODLevelSelection) {
  15248. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15249. }
  15250. return this;
  15251. }
  15252. for (var index = 0; index < this._LODLevels.length; index++) {
  15253. var level = this._LODLevels[index];
  15254. if (level.distance < distanceToCamera) {
  15255. if (level.mesh) {
  15256. level.mesh._preActivate();
  15257. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15258. }
  15259. if (this.onLODLevelSelection) {
  15260. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15261. }
  15262. return level.mesh;
  15263. }
  15264. }
  15265. if (this.onLODLevelSelection) {
  15266. this.onLODLevelSelection(distanceToCamera, this, this);
  15267. }
  15268. return this;
  15269. };
  15270. Object.defineProperty(Mesh.prototype, "geometry", {
  15271. get: function () {
  15272. return this._geometry;
  15273. },
  15274. enumerable: true,
  15275. configurable: true
  15276. });
  15277. Mesh.prototype.getTotalVertices = function () {
  15278. if (!this._geometry) {
  15279. return 0;
  15280. }
  15281. return this._geometry.getTotalVertices();
  15282. };
  15283. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15284. if (!this._geometry) {
  15285. return null;
  15286. }
  15287. return this._geometry.getVerticesData(kind, copyWhenShared);
  15288. };
  15289. Mesh.prototype.getVertexBuffer = function (kind) {
  15290. if (!this._geometry) {
  15291. return undefined;
  15292. }
  15293. return this._geometry.getVertexBuffer(kind);
  15294. };
  15295. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15296. if (!this._geometry) {
  15297. if (this._delayInfo) {
  15298. return this._delayInfo.indexOf(kind) !== -1;
  15299. }
  15300. return false;
  15301. }
  15302. return this._geometry.isVerticesDataPresent(kind);
  15303. };
  15304. Mesh.prototype.getVerticesDataKinds = function () {
  15305. if (!this._geometry) {
  15306. var result = [];
  15307. if (this._delayInfo) {
  15308. for (var kind in this._delayInfo) {
  15309. result.push(kind);
  15310. }
  15311. }
  15312. return result;
  15313. }
  15314. return this._geometry.getVerticesDataKinds();
  15315. };
  15316. Mesh.prototype.getTotalIndices = function () {
  15317. if (!this._geometry) {
  15318. return 0;
  15319. }
  15320. return this._geometry.getTotalIndices();
  15321. };
  15322. Mesh.prototype.getIndices = function (copyWhenShared) {
  15323. if (!this._geometry) {
  15324. return [];
  15325. }
  15326. return this._geometry.getIndices(copyWhenShared);
  15327. };
  15328. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15329. get: function () {
  15330. return this._masterMesh !== null && this._masterMesh !== undefined;
  15331. },
  15332. enumerable: true,
  15333. configurable: true
  15334. });
  15335. Mesh.prototype.isReady = function () {
  15336. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15337. return false;
  15338. }
  15339. return _super.prototype.isReady.call(this);
  15340. };
  15341. Mesh.prototype.isDisposed = function () {
  15342. return this._isDisposed;
  15343. };
  15344. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15345. get: function () {
  15346. return this._sideOrientation;
  15347. },
  15348. set: function (sideO) {
  15349. this._sideOrientation = sideO;
  15350. },
  15351. enumerable: true,
  15352. configurable: true
  15353. });
  15354. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15355. get: function () {
  15356. return this._areNormalsFrozen;
  15357. },
  15358. enumerable: true,
  15359. configurable: true
  15360. });
  15361. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15362. Mesh.prototype.freezeNormals = function () {
  15363. this._areNormalsFrozen = true;
  15364. };
  15365. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15366. Mesh.prototype.unfreezeNormals = function () {
  15367. this._areNormalsFrozen = false;
  15368. };
  15369. // Methods
  15370. Mesh.prototype._preActivate = function () {
  15371. var sceneRenderId = this.getScene().getRenderId();
  15372. if (this._preActivateId === sceneRenderId) {
  15373. return;
  15374. }
  15375. this._preActivateId = sceneRenderId;
  15376. this._visibleInstances = null;
  15377. };
  15378. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15379. if (!this._visibleInstances) {
  15380. this._visibleInstances = {};
  15381. this._visibleInstances.defaultRenderId = renderId;
  15382. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15383. }
  15384. if (!this._visibleInstances[renderId]) {
  15385. this._visibleInstances[renderId] = new Array();
  15386. }
  15387. this._visibleInstances[renderId].push(instance);
  15388. };
  15389. Mesh.prototype.refreshBoundingInfo = function () {
  15390. if (this._boundingInfo.isLocked) {
  15391. return;
  15392. }
  15393. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15394. if (data) {
  15395. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15396. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15397. }
  15398. if (this.subMeshes) {
  15399. for (var index = 0; index < this.subMeshes.length; index++) {
  15400. this.subMeshes[index].refreshBoundingInfo();
  15401. }
  15402. }
  15403. this._updateBoundingInfo();
  15404. };
  15405. Mesh.prototype._createGlobalSubMesh = function () {
  15406. var totalVertices = this.getTotalVertices();
  15407. if (!totalVertices || !this.getIndices()) {
  15408. return null;
  15409. }
  15410. this.releaseSubMeshes();
  15411. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15412. };
  15413. Mesh.prototype.subdivide = function (count) {
  15414. if (count < 1) {
  15415. return;
  15416. }
  15417. var totalIndices = this.getTotalIndices();
  15418. var subdivisionSize = (totalIndices / count) | 0;
  15419. var offset = 0;
  15420. // Ensure that subdivisionSize is a multiple of 3
  15421. while (subdivisionSize % 3 !== 0) {
  15422. subdivisionSize++;
  15423. }
  15424. this.releaseSubMeshes();
  15425. for (var index = 0; index < count; index++) {
  15426. if (offset >= totalIndices) {
  15427. break;
  15428. }
  15429. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15430. offset += subdivisionSize;
  15431. }
  15432. this.synchronizeInstances();
  15433. };
  15434. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15435. if (!this._geometry) {
  15436. var vertexData = new BABYLON.VertexData();
  15437. vertexData.set(data, kind);
  15438. var scene = this.getScene();
  15439. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15440. }
  15441. else {
  15442. this._geometry.setVerticesData(kind, data, updatable, stride);
  15443. }
  15444. };
  15445. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15446. if (!this._geometry) {
  15447. return;
  15448. }
  15449. if (!makeItUnique) {
  15450. this._geometry.updateVerticesData(kind, data, updateExtends);
  15451. }
  15452. else {
  15453. this.makeGeometryUnique();
  15454. this.updateVerticesData(kind, data, updateExtends, false);
  15455. }
  15456. };
  15457. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15458. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15459. if (!this._geometry) {
  15460. return;
  15461. }
  15462. if (!makeItUnique) {
  15463. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15464. }
  15465. else {
  15466. this.makeGeometryUnique();
  15467. this.updateVerticesDataDirectly(kind, data, offset, false);
  15468. }
  15469. };
  15470. // Mesh positions update function :
  15471. // updates the mesh positions according to the positionFunction returned values.
  15472. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15473. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15474. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15475. if (computeNormals === void 0) { computeNormals = true; }
  15476. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15477. positionFunction(positions);
  15478. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15479. if (computeNormals) {
  15480. var indices = this.getIndices();
  15481. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15482. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15483. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15484. }
  15485. };
  15486. Mesh.prototype.makeGeometryUnique = function () {
  15487. if (!this._geometry) {
  15488. return;
  15489. }
  15490. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15491. geometry.applyToMesh(this);
  15492. };
  15493. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15494. if (!this._geometry) {
  15495. var vertexData = new BABYLON.VertexData();
  15496. vertexData.indices = indices;
  15497. var scene = this.getScene();
  15498. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15499. }
  15500. else {
  15501. this._geometry.setIndices(indices, totalVertices);
  15502. }
  15503. };
  15504. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15505. var engine = this.getScene().getEngine();
  15506. // Wireframe
  15507. var indexToBind;
  15508. if (this._unIndexed) {
  15509. indexToBind = null;
  15510. }
  15511. else {
  15512. switch (fillMode) {
  15513. case BABYLON.Material.PointFillMode:
  15514. indexToBind = null;
  15515. break;
  15516. case BABYLON.Material.WireFrameFillMode:
  15517. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15518. break;
  15519. default:
  15520. case BABYLON.Material.TriangleFillMode:
  15521. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15522. break;
  15523. }
  15524. }
  15525. // VBOs
  15526. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15527. };
  15528. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15529. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15530. return;
  15531. }
  15532. if (this.onBeforeDraw) {
  15533. this.onBeforeDraw();
  15534. }
  15535. var engine = this.getScene().getEngine();
  15536. // Draw order
  15537. switch (fillMode) {
  15538. case BABYLON.Material.PointFillMode:
  15539. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15540. break;
  15541. case BABYLON.Material.WireFrameFillMode:
  15542. if (this._unIndexed) {
  15543. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15544. }
  15545. else {
  15546. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15547. }
  15548. break;
  15549. default:
  15550. if (this._unIndexed) {
  15551. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15552. }
  15553. else {
  15554. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15555. }
  15556. }
  15557. };
  15558. Mesh.prototype.registerBeforeRender = function (func) {
  15559. this._onBeforeRenderCallbacks.push(func);
  15560. };
  15561. Mesh.prototype.unregisterBeforeRender = function (func) {
  15562. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15563. if (index > -1) {
  15564. this._onBeforeRenderCallbacks.splice(index, 1);
  15565. }
  15566. };
  15567. Mesh.prototype.registerAfterRender = function (func) {
  15568. this._onAfterRenderCallbacks.push(func);
  15569. };
  15570. Mesh.prototype.unregisterAfterRender = function (func) {
  15571. var index = this._onAfterRenderCallbacks.indexOf(func);
  15572. if (index > -1) {
  15573. this._onAfterRenderCallbacks.splice(index, 1);
  15574. }
  15575. };
  15576. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15577. var scene = this.getScene();
  15578. this._batchCache.mustReturn = false;
  15579. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15580. this._batchCache.visibleInstances[subMeshId] = null;
  15581. if (this._visibleInstances) {
  15582. var currentRenderId = scene.getRenderId();
  15583. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15584. var selfRenderId = this._renderId;
  15585. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15586. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15587. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15588. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15589. }
  15590. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15591. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15592. this._batchCache.mustReturn = true;
  15593. return this._batchCache;
  15594. }
  15595. if (currentRenderId !== selfRenderId) {
  15596. this._batchCache.renderSelf[subMeshId] = false;
  15597. }
  15598. }
  15599. this._renderIdForInstances[subMeshId] = currentRenderId;
  15600. }
  15601. return this._batchCache;
  15602. };
  15603. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15604. var visibleInstances = batch.visibleInstances[subMesh._id];
  15605. var matricesCount = visibleInstances.length + 1;
  15606. var bufferSize = matricesCount * 16 * 4;
  15607. while (this._instancesBufferSize < bufferSize) {
  15608. this._instancesBufferSize *= 2;
  15609. }
  15610. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15611. if (this._worldMatricesInstancesBuffer) {
  15612. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15613. }
  15614. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15615. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15616. }
  15617. var offset = 0;
  15618. var instancesCount = 0;
  15619. var world = this.getWorldMatrix();
  15620. if (batch.renderSelf[subMesh._id]) {
  15621. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15622. offset += 16;
  15623. instancesCount++;
  15624. }
  15625. if (visibleInstances) {
  15626. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15627. var instance = visibleInstances[instanceIndex];
  15628. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15629. offset += 16;
  15630. instancesCount++;
  15631. }
  15632. }
  15633. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15634. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15635. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15636. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15637. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15638. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15639. this._draw(subMesh, fillMode, instancesCount);
  15640. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15641. };
  15642. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15643. var scene = this.getScene();
  15644. var engine = scene.getEngine();
  15645. if (hardwareInstancedRendering) {
  15646. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15647. }
  15648. else {
  15649. if (batch.renderSelf[subMesh._id]) {
  15650. // Draw
  15651. if (onBeforeDraw) {
  15652. onBeforeDraw(false, this.getWorldMatrix());
  15653. }
  15654. this._draw(subMesh, fillMode);
  15655. }
  15656. if (batch.visibleInstances[subMesh._id]) {
  15657. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15658. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15659. // World
  15660. var world = instance.getWorldMatrix();
  15661. if (onBeforeDraw) {
  15662. onBeforeDraw(true, world);
  15663. }
  15664. // Draw
  15665. this._draw(subMesh, fillMode);
  15666. }
  15667. }
  15668. }
  15669. };
  15670. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15671. var scene = this.getScene();
  15672. // Managing instances
  15673. var batch = this._getInstancesRenderList(subMesh._id);
  15674. if (batch.mustReturn) {
  15675. return;
  15676. }
  15677. // Checking geometry state
  15678. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15679. return;
  15680. }
  15681. var callbackIndex;
  15682. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15683. this._onBeforeRenderCallbacks[callbackIndex](this);
  15684. }
  15685. var engine = scene.getEngine();
  15686. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15687. // Material
  15688. var effectiveMaterial = subMesh.getMaterial();
  15689. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15690. return;
  15691. }
  15692. // Outline - step 1
  15693. var savedDepthWrite = engine.getDepthWrite();
  15694. if (this.renderOutline) {
  15695. engine.setDepthWrite(false);
  15696. scene.getOutlineRenderer().render(subMesh, batch);
  15697. engine.setDepthWrite(savedDepthWrite);
  15698. }
  15699. effectiveMaterial._preBind();
  15700. var effect = effectiveMaterial.getEffect();
  15701. // Bind
  15702. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15703. this._bind(subMesh, effect, fillMode);
  15704. var world = this.getWorldMatrix();
  15705. effectiveMaterial.bind(world, this);
  15706. // Alpha mode
  15707. if (enableAlphaMode) {
  15708. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15709. }
  15710. // Draw
  15711. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15712. if (isInstance) {
  15713. effectiveMaterial.bindOnlyWorldMatrix(world);
  15714. }
  15715. });
  15716. // Unbind
  15717. effectiveMaterial.unbind();
  15718. // Outline - step 2
  15719. if (this.renderOutline && savedDepthWrite) {
  15720. engine.setDepthWrite(true);
  15721. engine.setColorWrite(false);
  15722. scene.getOutlineRenderer().render(subMesh, batch);
  15723. engine.setColorWrite(true);
  15724. }
  15725. // Overlay
  15726. if (this.renderOverlay) {
  15727. var currentMode = engine.getAlphaMode();
  15728. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15729. scene.getOutlineRenderer().render(subMesh, batch, true);
  15730. engine.setAlphaMode(currentMode);
  15731. }
  15732. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15733. this._onAfterRenderCallbacks[callbackIndex](this);
  15734. }
  15735. };
  15736. Mesh.prototype.getEmittedParticleSystems = function () {
  15737. var results = new Array();
  15738. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15739. var particleSystem = this.getScene().particleSystems[index];
  15740. if (particleSystem.emitter === this) {
  15741. results.push(particleSystem);
  15742. }
  15743. }
  15744. return results;
  15745. };
  15746. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15747. var results = new Array();
  15748. var descendants = this.getDescendants();
  15749. descendants.push(this);
  15750. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15751. var particleSystem = this.getScene().particleSystems[index];
  15752. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15753. results.push(particleSystem);
  15754. }
  15755. }
  15756. return results;
  15757. };
  15758. Mesh.prototype._checkDelayState = function () {
  15759. var _this = this;
  15760. var that = this;
  15761. var scene = this.getScene();
  15762. if (this._geometry) {
  15763. this._geometry.load(scene);
  15764. }
  15765. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15766. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15767. scene._addPendingData(that);
  15768. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15769. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15770. if (data instanceof ArrayBuffer) {
  15771. _this._delayLoadingFunction(data, _this);
  15772. }
  15773. else {
  15774. _this._delayLoadingFunction(JSON.parse(data), _this);
  15775. }
  15776. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15777. scene._removePendingData(_this);
  15778. }, function () { }, scene.database, getBinaryData);
  15779. }
  15780. };
  15781. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15782. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15783. return false;
  15784. }
  15785. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15786. return false;
  15787. }
  15788. this._checkDelayState();
  15789. return true;
  15790. };
  15791. Mesh.prototype.setMaterialByID = function (id) {
  15792. var materials = this.getScene().materials;
  15793. var index;
  15794. for (index = 0; index < materials.length; index++) {
  15795. if (materials[index].id === id) {
  15796. this.material = materials[index];
  15797. return;
  15798. }
  15799. }
  15800. // Multi
  15801. var multiMaterials = this.getScene().multiMaterials;
  15802. for (index = 0; index < multiMaterials.length; index++) {
  15803. if (multiMaterials[index].id === id) {
  15804. this.material = multiMaterials[index];
  15805. return;
  15806. }
  15807. }
  15808. };
  15809. Mesh.prototype.getAnimatables = function () {
  15810. var results = [];
  15811. if (this.material) {
  15812. results.push(this.material);
  15813. }
  15814. if (this.skeleton) {
  15815. results.push(this.skeleton);
  15816. }
  15817. return results;
  15818. };
  15819. // Geometry
  15820. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15821. // Position
  15822. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15823. return;
  15824. }
  15825. this._resetPointsArrayCache();
  15826. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15827. var temp = [];
  15828. var index;
  15829. for (index = 0; index < data.length; index += 3) {
  15830. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15831. }
  15832. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15833. // Normals
  15834. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15835. return;
  15836. }
  15837. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15838. temp = [];
  15839. for (index = 0; index < data.length; index += 3) {
  15840. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15841. }
  15842. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15843. // flip faces?
  15844. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15845. this.flipFaces();
  15846. }
  15847. };
  15848. // Will apply current transform to mesh and reset world matrix
  15849. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15850. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15851. this.scaling.copyFromFloats(1, 1, 1);
  15852. this.position.copyFromFloats(0, 0, 0);
  15853. this.rotation.copyFromFloats(0, 0, 0);
  15854. //only if quaternion is already set
  15855. if (this.rotationQuaternion) {
  15856. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15857. }
  15858. this._worldMatrix = BABYLON.Matrix.Identity();
  15859. };
  15860. // Cache
  15861. Mesh.prototype._resetPointsArrayCache = function () {
  15862. this._positions = null;
  15863. };
  15864. Mesh.prototype._generatePointsArray = function () {
  15865. if (this._positions)
  15866. return true;
  15867. this._positions = [];
  15868. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15869. if (!data) {
  15870. return false;
  15871. }
  15872. for (var index = 0; index < data.length; index += 3) {
  15873. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15874. }
  15875. return true;
  15876. };
  15877. // Clone
  15878. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15879. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15880. };
  15881. // Dispose
  15882. Mesh.prototype.dispose = function (doNotRecurse) {
  15883. if (this._geometry) {
  15884. this._geometry.releaseForMesh(this, true);
  15885. }
  15886. // Instances
  15887. if (this._worldMatricesInstancesBuffer) {
  15888. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15889. this._worldMatricesInstancesBuffer = null;
  15890. }
  15891. while (this.instances.length) {
  15892. this.instances[0].dispose();
  15893. }
  15894. _super.prototype.dispose.call(this, doNotRecurse);
  15895. };
  15896. // Geometric tools
  15897. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15898. var _this = this;
  15899. var scene = this.getScene();
  15900. var onload = function (img) {
  15901. // Getting height map data
  15902. var canvas = document.createElement("canvas");
  15903. var context = canvas.getContext("2d");
  15904. var heightMapWidth = img.width;
  15905. var heightMapHeight = img.height;
  15906. canvas.width = heightMapWidth;
  15907. canvas.height = heightMapHeight;
  15908. context.drawImage(img, 0, 0);
  15909. // Create VertexData from map data
  15910. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15911. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15912. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15913. //execute success callback, if set
  15914. if (onSuccess) {
  15915. onSuccess(_this);
  15916. }
  15917. };
  15918. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15919. };
  15920. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15921. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15922. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15923. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15924. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15925. return;
  15926. }
  15927. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15928. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15929. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15930. var position = BABYLON.Vector3.Zero();
  15931. var normal = BABYLON.Vector3.Zero();
  15932. var uv = BABYLON.Vector2.Zero();
  15933. for (var index = 0; index < positions.length; index += 3) {
  15934. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15935. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15936. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15937. // Compute height
  15938. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15939. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15940. var pos = (u + v * heightMapWidth) * 4;
  15941. var r = buffer[pos] / 255.0;
  15942. var g = buffer[pos + 1] / 255.0;
  15943. var b = buffer[pos + 2] / 255.0;
  15944. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15945. normal.normalize();
  15946. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15947. position = position.add(normal);
  15948. position.toArray(positions, index);
  15949. }
  15950. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15951. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15952. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15953. };
  15954. Mesh.prototype.convertToFlatShadedMesh = function () {
  15955. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15956. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15957. var kinds = this.getVerticesDataKinds();
  15958. var vbs = [];
  15959. var data = [];
  15960. var newdata = [];
  15961. var updatableNormals = false;
  15962. var kindIndex;
  15963. var kind;
  15964. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15965. kind = kinds[kindIndex];
  15966. var vertexBuffer = this.getVertexBuffer(kind);
  15967. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15968. updatableNormals = vertexBuffer.isUpdatable();
  15969. kinds.splice(kindIndex, 1);
  15970. kindIndex--;
  15971. continue;
  15972. }
  15973. vbs[kind] = vertexBuffer;
  15974. data[kind] = vbs[kind].getData();
  15975. newdata[kind] = [];
  15976. }
  15977. // Save previous submeshes
  15978. var previousSubmeshes = this.subMeshes.slice(0);
  15979. var indices = this.getIndices();
  15980. var totalIndices = this.getTotalIndices();
  15981. // Generating unique vertices per face
  15982. var index;
  15983. for (index = 0; index < totalIndices; index++) {
  15984. var vertexIndex = indices[index];
  15985. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15986. kind = kinds[kindIndex];
  15987. var stride = vbs[kind].getStrideSize();
  15988. for (var offset = 0; offset < stride; offset++) {
  15989. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15990. }
  15991. }
  15992. }
  15993. // Updating faces & normal
  15994. var normals = [];
  15995. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15996. for (index = 0; index < totalIndices; index += 3) {
  15997. indices[index] = index;
  15998. indices[index + 1] = index + 1;
  15999. indices[index + 2] = index + 2;
  16000. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16001. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16002. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16003. var p1p2 = p1.subtract(p2);
  16004. var p3p2 = p3.subtract(p2);
  16005. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16006. // Store same normals for every vertex
  16007. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16008. normals.push(normal.x);
  16009. normals.push(normal.y);
  16010. normals.push(normal.z);
  16011. }
  16012. }
  16013. this.setIndices(indices);
  16014. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16015. // Updating vertex buffers
  16016. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16017. kind = kinds[kindIndex];
  16018. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16019. }
  16020. // Updating submeshes
  16021. this.releaseSubMeshes();
  16022. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16023. var previousOne = previousSubmeshes[submeshIndex];
  16024. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16025. }
  16026. this.synchronizeInstances();
  16027. };
  16028. Mesh.prototype.convertToUnIndexedMesh = function () {
  16029. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16030. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16031. var kinds = this.getVerticesDataKinds();
  16032. var vbs = [];
  16033. var data = [];
  16034. var newdata = [];
  16035. var updatableNormals = false;
  16036. var kindIndex;
  16037. var kind;
  16038. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16039. kind = kinds[kindIndex];
  16040. var vertexBuffer = this.getVertexBuffer(kind);
  16041. vbs[kind] = vertexBuffer;
  16042. data[kind] = vbs[kind].getData();
  16043. newdata[kind] = [];
  16044. }
  16045. // Save previous submeshes
  16046. var previousSubmeshes = this.subMeshes.slice(0);
  16047. var indices = this.getIndices();
  16048. var totalIndices = this.getTotalIndices();
  16049. // Generating unique vertices per face
  16050. var index;
  16051. for (index = 0; index < totalIndices; index++) {
  16052. var vertexIndex = indices[index];
  16053. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16054. kind = kinds[kindIndex];
  16055. var stride = vbs[kind].getStrideSize();
  16056. for (var offset = 0; offset < stride; offset++) {
  16057. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16058. }
  16059. }
  16060. }
  16061. // Updating indices
  16062. for (index = 0; index < totalIndices; index += 3) {
  16063. indices[index] = index;
  16064. indices[index + 1] = index + 1;
  16065. indices[index + 2] = index + 2;
  16066. }
  16067. this.setIndices(indices);
  16068. // Updating vertex buffers
  16069. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16070. kind = kinds[kindIndex];
  16071. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16072. }
  16073. // Updating submeshes
  16074. this.releaseSubMeshes();
  16075. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16076. var previousOne = previousSubmeshes[submeshIndex];
  16077. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16078. }
  16079. this._unIndexed = true;
  16080. this.synchronizeInstances();
  16081. };
  16082. // will inverse faces orientations, and invert normals too if specified
  16083. Mesh.prototype.flipFaces = function (flipNormals) {
  16084. if (flipNormals === void 0) { flipNormals = false; }
  16085. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16086. var i;
  16087. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16088. for (i = 0; i < vertex_data.normals.length; i++) {
  16089. vertex_data.normals[i] *= -1;
  16090. }
  16091. }
  16092. var temp;
  16093. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16094. // reassign indices
  16095. temp = vertex_data.indices[i + 1];
  16096. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16097. vertex_data.indices[i + 2] = temp;
  16098. }
  16099. vertex_data.applyToMesh(this);
  16100. };
  16101. // Instances
  16102. Mesh.prototype.createInstance = function (name) {
  16103. return new BABYLON.InstancedMesh(name, this);
  16104. };
  16105. Mesh.prototype.synchronizeInstances = function () {
  16106. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16107. var instance = this.instances[instanceIndex];
  16108. instance._syncSubMeshes();
  16109. }
  16110. };
  16111. /**
  16112. * Simplify the mesh according to the given array of settings.
  16113. * Function will return immediately and will simplify async.
  16114. * @param settings a collection of simplification settings.
  16115. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16116. * @param type the type of simplification to run.
  16117. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16118. */
  16119. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16120. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16121. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16122. this.getScene().simplificationQueue.addTask({
  16123. settings: settings,
  16124. parallelProcessing: parallelProcessing,
  16125. mesh: this,
  16126. simplificationType: simplificationType,
  16127. successCallback: successCallback
  16128. });
  16129. };
  16130. /**
  16131. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16132. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16133. * This should be used together with the simplification to avoid disappearing triangles.
  16134. * @param successCallback an optional success callback to be called after the optimization finished.
  16135. */
  16136. Mesh.prototype.optimizeIndices = function (successCallback) {
  16137. var _this = this;
  16138. var indices = this.getIndices();
  16139. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16140. var vectorPositions = [];
  16141. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16142. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16143. }
  16144. var dupes = [];
  16145. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16146. var realPos = vectorPositions.length - 1 - iteration;
  16147. var testedPosition = vectorPositions[realPos];
  16148. for (var j = 0; j < realPos; ++j) {
  16149. var againstPosition = vectorPositions[j];
  16150. if (testedPosition.equals(againstPosition)) {
  16151. dupes[realPos] = j;
  16152. break;
  16153. }
  16154. }
  16155. }, function () {
  16156. for (var i = 0; i < indices.length; ++i) {
  16157. indices[i] = dupes[indices[i]] || indices[i];
  16158. }
  16159. //indices are now reordered
  16160. var originalSubMeshes = _this.subMeshes.slice(0);
  16161. _this.setIndices(indices);
  16162. _this.subMeshes = originalSubMeshes;
  16163. if (successCallback) {
  16164. successCallback(_this);
  16165. }
  16166. });
  16167. };
  16168. // Statics
  16169. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16170. var mesh = new Mesh(parsedMesh.name, scene);
  16171. mesh.id = parsedMesh.id;
  16172. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16173. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16174. if (parsedMesh.rotationQuaternion) {
  16175. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16176. }
  16177. else if (parsedMesh.rotation) {
  16178. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16179. }
  16180. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16181. if (parsedMesh.localMatrix) {
  16182. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16183. }
  16184. else if (parsedMesh.pivotMatrix) {
  16185. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16186. }
  16187. mesh.setEnabled(parsedMesh.isEnabled);
  16188. mesh.isVisible = parsedMesh.isVisible;
  16189. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16190. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16191. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16192. if (parsedMesh.applyFog !== undefined) {
  16193. mesh.applyFog = parsedMesh.applyFog;
  16194. }
  16195. if (parsedMesh.pickable !== undefined) {
  16196. mesh.isPickable = parsedMesh.pickable;
  16197. }
  16198. if (parsedMesh.alphaIndex !== undefined) {
  16199. mesh.alphaIndex = parsedMesh.alphaIndex;
  16200. }
  16201. mesh.receiveShadows = parsedMesh.receiveShadows;
  16202. mesh.billboardMode = parsedMesh.billboardMode;
  16203. if (parsedMesh.visibility !== undefined) {
  16204. mesh.visibility = parsedMesh.visibility;
  16205. }
  16206. mesh.checkCollisions = parsedMesh.checkCollisions;
  16207. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16208. // freezeWorldMatrix
  16209. if (parsedMesh.freezeWorldMatrix) {
  16210. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16211. }
  16212. // Parent
  16213. if (parsedMesh.parentId) {
  16214. mesh._waitingParentId = parsedMesh.parentId;
  16215. }
  16216. // Actions
  16217. if (parsedMesh.actions !== undefined) {
  16218. mesh._waitingActions = parsedMesh.actions;
  16219. }
  16220. // Geometry
  16221. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16222. if (parsedMesh.delayLoadingFile) {
  16223. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16224. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16225. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16226. if (parsedMesh._binaryInfo) {
  16227. mesh._binaryInfo = parsedMesh._binaryInfo;
  16228. }
  16229. mesh._delayInfo = [];
  16230. if (parsedMesh.hasUVs) {
  16231. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16232. }
  16233. if (parsedMesh.hasUVs2) {
  16234. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16235. }
  16236. if (parsedMesh.hasUVs3) {
  16237. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16238. }
  16239. if (parsedMesh.hasUVs4) {
  16240. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16241. }
  16242. if (parsedMesh.hasUVs5) {
  16243. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16244. }
  16245. if (parsedMesh.hasUVs6) {
  16246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16247. }
  16248. if (parsedMesh.hasColors) {
  16249. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16250. }
  16251. if (parsedMesh.hasMatricesIndices) {
  16252. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16253. }
  16254. if (parsedMesh.hasMatricesWeights) {
  16255. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16256. }
  16257. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16258. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16259. mesh._checkDelayState();
  16260. }
  16261. }
  16262. else {
  16263. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16264. }
  16265. // Material
  16266. if (parsedMesh.materialId) {
  16267. mesh.setMaterialByID(parsedMesh.materialId);
  16268. }
  16269. else {
  16270. mesh.material = null;
  16271. }
  16272. // Skeleton
  16273. if (parsedMesh.skeletonId > -1) {
  16274. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16275. if (parsedMesh.numBoneInfluencers) {
  16276. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16277. }
  16278. }
  16279. // Animations
  16280. if (parsedMesh.animations) {
  16281. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16282. var parsedAnimation = parsedMesh.animations[animationIndex];
  16283. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16284. }
  16285. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16286. }
  16287. if (parsedMesh.autoAnimate) {
  16288. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16289. }
  16290. // Layer Mask
  16291. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16292. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16293. }
  16294. else {
  16295. mesh.layerMask = 0x0FFFFFFF;
  16296. }
  16297. // Instances
  16298. if (parsedMesh.instances) {
  16299. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16300. var parsedInstance = parsedMesh.instances[index];
  16301. var instance = mesh.createInstance(parsedInstance.name);
  16302. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16303. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16304. if (parsedInstance.rotationQuaternion) {
  16305. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16306. }
  16307. else if (parsedInstance.rotation) {
  16308. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16309. }
  16310. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16311. instance.checkCollisions = mesh.checkCollisions;
  16312. if (parsedMesh.animations) {
  16313. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16314. parsedAnimation = parsedMesh.animations[animationIndex];
  16315. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16316. }
  16317. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16318. }
  16319. }
  16320. }
  16321. return mesh;
  16322. };
  16323. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16324. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16325. pathArray: pathArray,
  16326. closeArray: closeArray,
  16327. closePath: closePath,
  16328. offset: offset,
  16329. updatable: updatable,
  16330. sideOrientation: sideOrientation,
  16331. instance: instance
  16332. }, scene);
  16333. };
  16334. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16335. var options = {
  16336. radius: radius,
  16337. tessellation: tessellation,
  16338. sideOrientation: sideOrientation,
  16339. updatable: updatable
  16340. };
  16341. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16342. };
  16343. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16344. var options = {
  16345. size: size,
  16346. sideOrientation: sideOrientation,
  16347. updatable: updatable
  16348. };
  16349. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16350. };
  16351. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16352. var options = {
  16353. segments: segments,
  16354. diameterX: diameter,
  16355. diameterY: diameter,
  16356. diameterZ: diameter,
  16357. sideOrientation: sideOrientation,
  16358. updatable: updatable
  16359. };
  16360. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16361. };
  16362. // Cylinder and cone
  16363. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16364. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16365. if (scene !== undefined) {
  16366. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16367. updatable = scene;
  16368. }
  16369. scene = subdivisions;
  16370. subdivisions = 1;
  16371. }
  16372. var options = {
  16373. height: height,
  16374. diameterTop: diameterTop,
  16375. diameterBottom: diameterBottom,
  16376. tessellation: tessellation,
  16377. subdivisions: subdivisions,
  16378. sideOrientation: sideOrientation,
  16379. updatable: updatable
  16380. };
  16381. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16382. };
  16383. // Torus (Code from SharpDX.org)
  16384. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16385. var options = {
  16386. diameter: diameter,
  16387. thickness: thickness,
  16388. tessellation: tessellation,
  16389. sideOrientation: sideOrientation,
  16390. updatable: updatable
  16391. };
  16392. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16393. };
  16394. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16395. var options = {
  16396. radius: radius,
  16397. tube: tube,
  16398. radialSegments: radialSegments,
  16399. tubularSegments: tubularSegments,
  16400. p: p,
  16401. q: q,
  16402. sideOrientation: sideOrientation,
  16403. updatable: updatable
  16404. };
  16405. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16406. };
  16407. // Lines
  16408. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16409. var options = {
  16410. points: points,
  16411. updatable: updatable,
  16412. instance: instance
  16413. };
  16414. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16415. };
  16416. // Dashed Lines
  16417. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16418. var options = {
  16419. points: points,
  16420. dashSize: dashSize,
  16421. gapSize: gapSize,
  16422. dashNb: dashNb,
  16423. updatable: updatable
  16424. };
  16425. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16426. };
  16427. // Extrusion
  16428. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16429. var options = {
  16430. shape: shape,
  16431. path: path,
  16432. scale: scale,
  16433. rotation: rotation,
  16434. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16435. sideOrientation: sideOrientation,
  16436. instance: instance,
  16437. updatable: updatable
  16438. };
  16439. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16440. };
  16441. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16442. var options = {
  16443. shape: shape,
  16444. path: path,
  16445. scaleFunction: scaleFunction,
  16446. rotationFunction: rotationFunction,
  16447. ribbonCloseArray: ribbonCloseArray,
  16448. ribbonClosePath: ribbonClosePath,
  16449. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16450. sideOrientation: sideOrientation,
  16451. instance: instance,
  16452. updatable: updatable
  16453. };
  16454. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16455. };
  16456. // Lathe
  16457. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16458. var options = {
  16459. shape: shape,
  16460. radius: radius,
  16461. tessellation: tessellation,
  16462. sideOrientation: sideOrientation,
  16463. updatable: updatable
  16464. };
  16465. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16466. };
  16467. // Plane & ground
  16468. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16469. var options = {
  16470. size: size,
  16471. width: size,
  16472. height: size,
  16473. sideOrientation: sideOrientation,
  16474. updatable: updatable
  16475. };
  16476. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16477. };
  16478. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16479. var options = {
  16480. width: width,
  16481. height: height,
  16482. subdivisions: subdivisions,
  16483. updatable: updatable
  16484. };
  16485. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16486. };
  16487. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16488. var options = {
  16489. xmin: xmin,
  16490. zmin: zmin,
  16491. xmax: xmax,
  16492. zmax: zmax,
  16493. subdivisions: subdivisions,
  16494. precision: precision,
  16495. updatable: updatable
  16496. };
  16497. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16498. };
  16499. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16500. var options = {
  16501. width: width,
  16502. height: height,
  16503. subdivisions: subdivisions,
  16504. minHeight: minHeight,
  16505. maxHeight: maxHeight,
  16506. updatable: updatable,
  16507. onReady: onReady
  16508. };
  16509. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16510. };
  16511. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16512. var options = {
  16513. path: path,
  16514. radius: radius,
  16515. tessellation: tessellation,
  16516. radiusFunction: radiusFunction,
  16517. arc: 1,
  16518. cap: cap,
  16519. updatable: updatable,
  16520. sideOrientation: sideOrientation,
  16521. instance: instance
  16522. };
  16523. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16524. };
  16525. Mesh.CreatePolyhedron = function (name, options, scene) {
  16526. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16527. };
  16528. Mesh.CreateIcoSphere = function (name, options, scene) {
  16529. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16530. };
  16531. // Decals
  16532. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16533. var options = {
  16534. position: position,
  16535. normal: normal,
  16536. size: size,
  16537. angle: angle
  16538. };
  16539. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16540. };
  16541. // Skeletons
  16542. /**
  16543. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16544. */
  16545. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16546. var source;
  16547. if (!this._sourcePositions) {
  16548. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16549. this._sourcePositions = new Float32Array(source);
  16550. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16551. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16552. }
  16553. }
  16554. return this._sourcePositions;
  16555. };
  16556. /**
  16557. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16558. */
  16559. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16560. var source;
  16561. if (!this._sourceNormals) {
  16562. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16563. this._sourceNormals = new Float32Array(source);
  16564. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16565. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16566. }
  16567. }
  16568. return this._sourceNormals;
  16569. };
  16570. /**
  16571. * Update the vertex buffers by applying transformation from the bones
  16572. * @param {skeleton} skeleton to apply
  16573. */
  16574. Mesh.prototype.applySkeleton = function (skeleton) {
  16575. if (!this.geometry) {
  16576. return;
  16577. }
  16578. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16579. return;
  16580. }
  16581. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16582. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16583. return this;
  16584. }
  16585. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16586. return this;
  16587. }
  16588. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16589. return this;
  16590. }
  16591. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16592. return this;
  16593. }
  16594. if (!this._sourcePositions) {
  16595. this.setPositionsForCPUSkinning();
  16596. }
  16597. if (!this._sourceNormals) {
  16598. this.setNormalsForCPUSkinning();
  16599. }
  16600. // positionsData checks for not being Float32Array will only pass at most once
  16601. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16602. if (!(positionsData instanceof Float32Array)) {
  16603. positionsData = new Float32Array(positionsData);
  16604. }
  16605. // normalsData checks for not being Float32Array will only pass at most once
  16606. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16607. if (!(normalsData instanceof Float32Array)) {
  16608. normalsData = new Float32Array(normalsData);
  16609. }
  16610. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16611. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16612. var needExtras = this.numBoneInfluencers > 4;
  16613. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16614. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16615. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16616. var tempVector3 = BABYLON.Vector3.Zero();
  16617. var finalMatrix = new BABYLON.Matrix();
  16618. var tempMatrix = new BABYLON.Matrix();
  16619. var matWeightIdx = 0;
  16620. var inf;
  16621. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16622. var weight;
  16623. for (inf = 0; inf < 4; inf++) {
  16624. weight = matricesWeightsData[matWeightIdx + inf];
  16625. if (weight > 0) {
  16626. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16627. finalMatrix.addToSelf(tempMatrix);
  16628. }
  16629. else
  16630. break;
  16631. }
  16632. if (needExtras) {
  16633. for (inf = 0; inf < 4; inf++) {
  16634. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16635. if (weight > 0) {
  16636. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16637. finalMatrix.addToSelf(tempMatrix);
  16638. }
  16639. else
  16640. break;
  16641. }
  16642. }
  16643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16644. tempVector3.toArray(positionsData, index);
  16645. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16646. tempVector3.toArray(normalsData, index);
  16647. finalMatrix.reset();
  16648. }
  16649. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16650. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16651. return this;
  16652. };
  16653. // Tools
  16654. Mesh.MinMax = function (meshes) {
  16655. var minVector = null;
  16656. var maxVector = null;
  16657. for (var i in meshes) {
  16658. var mesh = meshes[i];
  16659. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16660. if (!minVector) {
  16661. minVector = boundingBox.minimumWorld;
  16662. maxVector = boundingBox.maximumWorld;
  16663. continue;
  16664. }
  16665. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16666. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16667. }
  16668. return {
  16669. min: minVector,
  16670. max: maxVector
  16671. };
  16672. };
  16673. Mesh.Center = function (meshesOrMinMaxVector) {
  16674. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16675. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16676. };
  16677. /**
  16678. * Merge the array of meshes into a single mesh for performance reasons.
  16679. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16680. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16681. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16682. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16683. */
  16684. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16685. if (disposeSource === void 0) { disposeSource = true; }
  16686. var index;
  16687. if (!allow32BitsIndices) {
  16688. var totalVertices = 0;
  16689. // Counting vertices
  16690. for (index = 0; index < meshes.length; index++) {
  16691. if (meshes[index]) {
  16692. totalVertices += meshes[index].getTotalVertices();
  16693. if (totalVertices > 65536) {
  16694. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16695. return null;
  16696. }
  16697. }
  16698. }
  16699. }
  16700. // Merge
  16701. var vertexData;
  16702. var otherVertexData;
  16703. var source;
  16704. for (index = 0; index < meshes.length; index++) {
  16705. if (meshes[index]) {
  16706. meshes[index].computeWorldMatrix(true);
  16707. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16708. otherVertexData.transform(meshes[index].getWorldMatrix());
  16709. if (vertexData) {
  16710. vertexData.merge(otherVertexData);
  16711. }
  16712. else {
  16713. vertexData = otherVertexData;
  16714. source = meshes[index];
  16715. }
  16716. }
  16717. }
  16718. if (!meshSubclass) {
  16719. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16720. }
  16721. vertexData.applyToMesh(meshSubclass);
  16722. // Setting properties
  16723. meshSubclass.material = source.material;
  16724. meshSubclass.checkCollisions = source.checkCollisions;
  16725. // Cleaning
  16726. if (disposeSource) {
  16727. for (index = 0; index < meshes.length; index++) {
  16728. if (meshes[index]) {
  16729. meshes[index].dispose();
  16730. }
  16731. }
  16732. }
  16733. return meshSubclass;
  16734. };
  16735. // Consts
  16736. Mesh._FRONTSIDE = 0;
  16737. Mesh._BACKSIDE = 1;
  16738. Mesh._DOUBLESIDE = 2;
  16739. Mesh._DEFAULTSIDE = 0;
  16740. Mesh._NO_CAP = 0;
  16741. Mesh._CAP_START = 1;
  16742. Mesh._CAP_END = 2;
  16743. Mesh._CAP_ALL = 3;
  16744. return Mesh;
  16745. })(BABYLON.AbstractMesh);
  16746. BABYLON.Mesh = Mesh;
  16747. })(BABYLON || (BABYLON = {}));
  16748. var BABYLON;
  16749. (function (BABYLON) {
  16750. var SubMesh = (function () {
  16751. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16752. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16753. this.materialIndex = materialIndex;
  16754. this.verticesStart = verticesStart;
  16755. this.verticesCount = verticesCount;
  16756. this.indexStart = indexStart;
  16757. this.indexCount = indexCount;
  16758. this._renderId = 0;
  16759. this._mesh = mesh;
  16760. this._renderingMesh = renderingMesh || mesh;
  16761. mesh.subMeshes.push(this);
  16762. this._trianglePlanes = [];
  16763. this._id = mesh.subMeshes.length - 1;
  16764. if (createBoundingBox) {
  16765. this.refreshBoundingInfo();
  16766. mesh.computeWorldMatrix(true);
  16767. }
  16768. }
  16769. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16770. get: function () {
  16771. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. SubMesh.prototype.getBoundingInfo = function () {
  16777. if (this.IsGlobal) {
  16778. return this._mesh.getBoundingInfo();
  16779. }
  16780. return this._boundingInfo;
  16781. };
  16782. SubMesh.prototype.getMesh = function () {
  16783. return this._mesh;
  16784. };
  16785. SubMesh.prototype.getRenderingMesh = function () {
  16786. return this._renderingMesh;
  16787. };
  16788. SubMesh.prototype.getMaterial = function () {
  16789. var rootMaterial = this._renderingMesh.material;
  16790. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16791. var multiMaterial = rootMaterial;
  16792. return multiMaterial.getSubMaterial(this.materialIndex);
  16793. }
  16794. if (!rootMaterial) {
  16795. return this._mesh.getScene().defaultMaterial;
  16796. }
  16797. return rootMaterial;
  16798. };
  16799. // Methods
  16800. SubMesh.prototype.refreshBoundingInfo = function () {
  16801. this._lastColliderWorldVertices = null;
  16802. if (this.IsGlobal) {
  16803. return;
  16804. }
  16805. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16806. if (!data) {
  16807. this._boundingInfo = this._mesh._boundingInfo;
  16808. return;
  16809. }
  16810. var indices = this._renderingMesh.getIndices();
  16811. var extend;
  16812. //is this the only submesh?
  16813. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16814. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16815. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16816. }
  16817. else {
  16818. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16819. }
  16820. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16821. };
  16822. SubMesh.prototype._checkCollision = function (collider) {
  16823. return this.getBoundingInfo()._checkCollision(collider);
  16824. };
  16825. SubMesh.prototype.updateBoundingInfo = function (world) {
  16826. if (!this.getBoundingInfo()) {
  16827. this.refreshBoundingInfo();
  16828. }
  16829. this.getBoundingInfo().update(world);
  16830. };
  16831. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16832. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16833. };
  16834. SubMesh.prototype.render = function (enableAlphaMode) {
  16835. this._renderingMesh.render(this, enableAlphaMode);
  16836. };
  16837. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16838. if (!this._linesIndexBuffer) {
  16839. var linesIndices = [];
  16840. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16841. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16842. }
  16843. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16844. this.linesIndexCount = linesIndices.length;
  16845. }
  16846. return this._linesIndexBuffer;
  16847. };
  16848. SubMesh.prototype.canIntersects = function (ray) {
  16849. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16850. };
  16851. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16852. var intersectInfo = null;
  16853. // Triangles test
  16854. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16855. var p0 = positions[indices[index]];
  16856. var p1 = positions[indices[index + 1]];
  16857. var p2 = positions[indices[index + 2]];
  16858. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16859. if (currentIntersectInfo) {
  16860. if (currentIntersectInfo.distance < 0) {
  16861. continue;
  16862. }
  16863. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16864. intersectInfo = currentIntersectInfo;
  16865. intersectInfo.faceId = index / 3;
  16866. if (fastCheck) {
  16867. break;
  16868. }
  16869. }
  16870. }
  16871. }
  16872. return intersectInfo;
  16873. };
  16874. // Clone
  16875. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16876. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16877. if (!this.IsGlobal) {
  16878. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16879. }
  16880. return result;
  16881. };
  16882. // Dispose
  16883. SubMesh.prototype.dispose = function () {
  16884. if (this._linesIndexBuffer) {
  16885. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16886. this._linesIndexBuffer = null;
  16887. }
  16888. // Remove from mesh
  16889. var index = this._mesh.subMeshes.indexOf(this);
  16890. this._mesh.subMeshes.splice(index, 1);
  16891. };
  16892. // Statics
  16893. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16894. var minVertexIndex = Number.MAX_VALUE;
  16895. var maxVertexIndex = -Number.MAX_VALUE;
  16896. renderingMesh = renderingMesh || mesh;
  16897. var indices = renderingMesh.getIndices();
  16898. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16899. var vertexIndex = indices[index];
  16900. if (vertexIndex < minVertexIndex)
  16901. minVertexIndex = vertexIndex;
  16902. if (vertexIndex > maxVertexIndex)
  16903. maxVertexIndex = vertexIndex;
  16904. }
  16905. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16906. };
  16907. return SubMesh;
  16908. })();
  16909. BABYLON.SubMesh = SubMesh;
  16910. })(BABYLON || (BABYLON = {}));
  16911. var BABYLON;
  16912. (function (BABYLON) {
  16913. var MeshBuilder = (function () {
  16914. function MeshBuilder() {
  16915. }
  16916. MeshBuilder.CreateBox = function (name, options, scene) {
  16917. var box = new BABYLON.Mesh(name, scene);
  16918. var vertexData = BABYLON.VertexData.CreateBox(options);
  16919. vertexData.applyToMesh(box, options.updatable);
  16920. return box;
  16921. };
  16922. MeshBuilder.CreateSphere = function (name, options, scene) {
  16923. var sphere = new BABYLON.Mesh(name, scene);
  16924. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16925. vertexData.applyToMesh(sphere, options.updatable);
  16926. return sphere;
  16927. };
  16928. MeshBuilder.CreateDisc = function (name, options, scene) {
  16929. var disc = new BABYLON.Mesh(name, scene);
  16930. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16931. vertexData.applyToMesh(disc, options.updatable);
  16932. return disc;
  16933. };
  16934. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16935. var sphere = new BABYLON.Mesh(name, scene);
  16936. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16937. vertexData.applyToMesh(sphere, options.updatable);
  16938. return sphere;
  16939. };
  16940. ;
  16941. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16942. var pathArray = options.pathArray;
  16943. var closeArray = options.closeArray;
  16944. var closePath = options.closePath;
  16945. var offset = options.offset;
  16946. var sideOrientation = options.sideOrientation;
  16947. var instance = options.instance;
  16948. var updatable = options.updatable;
  16949. if (instance) {
  16950. // positionFunction : ribbon case
  16951. // only pathArray and sideOrientation parameters are taken into account for positions update
  16952. var positionFunction = function (positions) {
  16953. var minlg = pathArray[0].length;
  16954. var i = 0;
  16955. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16956. for (var si = 1; si <= ns; si++) {
  16957. for (var p = 0; p < pathArray.length; p++) {
  16958. var path = pathArray[p];
  16959. var l = path.length;
  16960. minlg = (minlg < l) ? minlg : l;
  16961. var j = 0;
  16962. while (j < minlg) {
  16963. positions[i] = path[j].x;
  16964. positions[i + 1] = path[j].y;
  16965. positions[i + 2] = path[j].z;
  16966. j++;
  16967. i += 3;
  16968. }
  16969. if (instance._closePath) {
  16970. positions[i] = path[0].x;
  16971. positions[i + 1] = path[0].y;
  16972. positions[i + 2] = path[0].z;
  16973. i += 3;
  16974. }
  16975. }
  16976. }
  16977. };
  16978. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16979. positionFunction(positions);
  16980. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16981. if (!(instance.areNormalsFrozen)) {
  16982. var indices = instance.getIndices();
  16983. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16984. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16985. if (instance._closePath) {
  16986. var indexFirst = 0;
  16987. var indexLast = 0;
  16988. for (var p = 0; p < pathArray.length; p++) {
  16989. indexFirst = instance._idx[p] * 3;
  16990. if (p + 1 < pathArray.length) {
  16991. indexLast = (instance._idx[p + 1] - 1) * 3;
  16992. }
  16993. else {
  16994. indexLast = normals.length - 3;
  16995. }
  16996. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16997. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16998. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16999. normals[indexLast] = normals[indexFirst];
  17000. normals[indexLast + 1] = normals[indexFirst + 1];
  17001. normals[indexLast + 2] = normals[indexFirst + 2];
  17002. }
  17003. }
  17004. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17005. }
  17006. return instance;
  17007. }
  17008. else {
  17009. var ribbon = new BABYLON.Mesh(name, scene);
  17010. ribbon.sideOrientation = sideOrientation;
  17011. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17012. if (closePath) {
  17013. ribbon._idx = vertexData._idx;
  17014. }
  17015. ribbon._closePath = closePath;
  17016. ribbon._closeArray = closeArray;
  17017. vertexData.applyToMesh(ribbon, updatable);
  17018. return ribbon;
  17019. }
  17020. };
  17021. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17022. var cylinder = new BABYLON.Mesh(name, scene);
  17023. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17024. vertexData.applyToMesh(cylinder, options.updatable);
  17025. return cylinder;
  17026. };
  17027. MeshBuilder.CreateTorus = function (name, options, scene) {
  17028. var torus = new BABYLON.Mesh(name, scene);
  17029. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17030. vertexData.applyToMesh(torus, options.updatable);
  17031. return torus;
  17032. };
  17033. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17034. var torusKnot = new BABYLON.Mesh(name, scene);
  17035. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17036. vertexData.applyToMesh(torusKnot, options.updatable);
  17037. return torusKnot;
  17038. };
  17039. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17040. var instance = options.instance;
  17041. var lines = options.lines;
  17042. if (instance) {
  17043. var positionFunction = function (positions) {
  17044. var i = 0;
  17045. for (var l = 0; l < lines.length; l++) {
  17046. var points = lines[l];
  17047. for (var p = 0; p < points.length; p++) {
  17048. positions[i] = points[p].x;
  17049. positions[i + 1] = points[p].y;
  17050. positions[i + 2] = points[p].z;
  17051. i += 3;
  17052. }
  17053. }
  17054. };
  17055. instance.updateMeshPositions(positionFunction, false);
  17056. return instance;
  17057. }
  17058. // line system creation
  17059. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17060. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17061. vertexData.applyToMesh(lineSystem, options.updatable);
  17062. return lineSystem;
  17063. };
  17064. MeshBuilder.CreateLines = function (name, options, scene) {
  17065. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17066. return lines;
  17067. };
  17068. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17069. var points = options.points;
  17070. var instance = options.instance;
  17071. var gapSize = options.gapSize;
  17072. var dashNb = options.dashNb;
  17073. var dashSize = options.dashSize;
  17074. if (instance) {
  17075. var positionFunction = function (positions) {
  17076. var curvect = BABYLON.Vector3.Zero();
  17077. var nbSeg = positions.length / 6;
  17078. var lg = 0;
  17079. var nb = 0;
  17080. var shft = 0;
  17081. var dashshft = 0;
  17082. var curshft = 0;
  17083. var p = 0;
  17084. var i = 0;
  17085. var j = 0;
  17086. for (i = 0; i < points.length - 1; i++) {
  17087. points[i + 1].subtractToRef(points[i], curvect);
  17088. lg += curvect.length();
  17089. }
  17090. shft = lg / nbSeg;
  17091. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17092. for (i = 0; i < points.length - 1; i++) {
  17093. points[i + 1].subtractToRef(points[i], curvect);
  17094. nb = Math.floor(curvect.length() / shft);
  17095. curvect.normalize();
  17096. j = 0;
  17097. while (j < nb && p < positions.length) {
  17098. curshft = shft * j;
  17099. positions[p] = points[i].x + curshft * curvect.x;
  17100. positions[p + 1] = points[i].y + curshft * curvect.y;
  17101. positions[p + 2] = points[i].z + curshft * curvect.z;
  17102. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17103. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17104. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17105. p += 6;
  17106. j++;
  17107. }
  17108. }
  17109. while (p < positions.length) {
  17110. positions[p] = points[i].x;
  17111. positions[p + 1] = points[i].y;
  17112. positions[p + 2] = points[i].z;
  17113. p += 3;
  17114. }
  17115. };
  17116. instance.updateMeshPositions(positionFunction, false);
  17117. return instance;
  17118. }
  17119. // dashed lines creation
  17120. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17121. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17122. vertexData.applyToMesh(dashedLines, options.updatable);
  17123. dashedLines.dashSize = dashSize;
  17124. dashedLines.gapSize = gapSize;
  17125. return dashedLines;
  17126. };
  17127. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17128. var path = options.path;
  17129. var shape = options.shape;
  17130. var scale = options.scale || 1;
  17131. var rotation = options.rotation || 0;
  17132. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17133. var updatable = options.updatable;
  17134. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17135. var instance = options.instance;
  17136. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17137. };
  17138. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17139. var path = options.path;
  17140. var shape = options.shape;
  17141. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17142. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17143. var ribbonCloseArray = options.ribbonCloseArray || false;
  17144. var ribbonClosePath = options.ribbonClosePath || false;
  17145. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17146. var updatable = options.updatable;
  17147. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17148. var instance = options.instance;
  17149. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17150. };
  17151. MeshBuilder.CreateLathe = function (name, options, scene) {
  17152. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17153. var closed = (options.closed === undefined) ? true : options.closed;
  17154. var shape = options.shape;
  17155. var radius = options.radius || 1;
  17156. var tessellation = options.tessellation || 64;
  17157. var updatable = options.updatable;
  17158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17159. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17160. var pi2 = Math.PI * 2;
  17161. var paths = new Array();
  17162. var i = 0;
  17163. var p = 0;
  17164. var step = pi2 / tessellation * arc;
  17165. var rotated;
  17166. var path = new Array();
  17167. ;
  17168. for (i = 0; i <= tessellation; i++) {
  17169. var path = [];
  17170. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17171. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17172. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17173. }
  17174. for (p = 0; p < shape.length; p++) {
  17175. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17176. path.push(rotated);
  17177. }
  17178. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17179. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  17180. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17181. }
  17182. paths.push(path);
  17183. }
  17184. // lathe ribbon
  17185. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17186. return lathe;
  17187. };
  17188. MeshBuilder.CreatePlane = function (name, options, scene) {
  17189. var plane = new BABYLON.Mesh(name, scene);
  17190. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17191. vertexData.applyToMesh(plane, options.updatable);
  17192. if (options.sourcePlane) {
  17193. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17194. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17195. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17196. plane.rotate(vectorProduct, product);
  17197. }
  17198. return plane;
  17199. };
  17200. MeshBuilder.CreateGround = function (name, options, scene) {
  17201. var ground = new BABYLON.GroundMesh(name, scene);
  17202. ground._setReady(false);
  17203. ground._subdivisions = options.subdivisions || 1;
  17204. ground._width = options.width || 1;
  17205. ground._height = options.height || 1;
  17206. ground._maxX = ground._width / 2;
  17207. ground._maxZ = ground._height / 2;
  17208. ground._minX = -ground._maxX;
  17209. ground._minZ = -ground._maxZ;
  17210. var vertexData = BABYLON.VertexData.CreateGround(options);
  17211. vertexData.applyToMesh(ground, options.updatable);
  17212. ground._setReady(true);
  17213. return ground;
  17214. };
  17215. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17216. var tiledGround = new BABYLON.Mesh(name, scene);
  17217. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17218. vertexData.applyToMesh(tiledGround, options.updatable);
  17219. return tiledGround;
  17220. };
  17221. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17222. var width = options.width || 10;
  17223. var height = options.height || 10;
  17224. var subdivisions = options.subdivisions || 1;
  17225. var minHeight = options.minHeight;
  17226. var maxHeight = options.maxHeight || 10;
  17227. var updatable = options.updatable;
  17228. var onReady = options.onReady;
  17229. var ground = new BABYLON.GroundMesh(name, scene);
  17230. ground._subdivisions = subdivisions;
  17231. ground._width = width;
  17232. ground._height = height;
  17233. ground._maxX = ground._width / 2;
  17234. ground._maxZ = ground._height / 2;
  17235. ground._minX = -ground._maxX;
  17236. ground._minZ = -ground._maxZ;
  17237. ground._setReady(false);
  17238. var onload = function (img) {
  17239. // Getting height map data
  17240. var canvas = document.createElement("canvas");
  17241. var context = canvas.getContext("2d");
  17242. var bufferWidth = img.width;
  17243. var bufferHeight = img.height;
  17244. canvas.width = bufferWidth;
  17245. canvas.height = bufferHeight;
  17246. context.drawImage(img, 0, 0);
  17247. // Create VertexData from map data
  17248. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17249. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17250. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17251. width: width, height: height,
  17252. subdivisions: subdivisions,
  17253. minHeight: minHeight, maxHeight: maxHeight,
  17254. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17255. });
  17256. vertexData.applyToMesh(ground, updatable);
  17257. ground._setReady(true);
  17258. //execute ready callback, if set
  17259. if (onReady) {
  17260. onReady(ground);
  17261. }
  17262. };
  17263. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17264. return ground;
  17265. };
  17266. MeshBuilder.CreateTube = function (name, options, scene) {
  17267. var path = options.path;
  17268. var radius = options.radius || 1;
  17269. var tessellation = options.tessellation || 64;
  17270. var radiusFunction = options.radiusFunction;
  17271. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17272. var updatable = options.updatable;
  17273. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17274. var instance = options.instance;
  17275. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17276. // tube geometry
  17277. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17278. var tangents = path3D.getTangents();
  17279. var normals = path3D.getNormals();
  17280. var distances = path3D.getDistances();
  17281. var pi2 = Math.PI * 2;
  17282. var step = pi2 / tessellation * arc;
  17283. var returnRadius = function () { return radius; };
  17284. var radiusFunctionFinal = radiusFunction || returnRadius;
  17285. var circlePath;
  17286. var rad;
  17287. var normal;
  17288. var rotated;
  17289. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17290. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17291. for (var i = 0; i < path.length; i++) {
  17292. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17293. circlePath = Array(); // current circle array
  17294. normal = normals[i]; // current normal
  17295. for (var t = 0; t < tessellation; t++) {
  17296. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17297. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17298. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17299. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17300. circlePath[t] = rotated;
  17301. }
  17302. circlePaths[index] = circlePath;
  17303. index++;
  17304. }
  17305. // cap
  17306. var capPath = function (nbPoints, pathIndex) {
  17307. var pointCap = Array();
  17308. for (var i = 0; i < nbPoints; i++) {
  17309. pointCap.push(path[pathIndex]);
  17310. }
  17311. return pointCap;
  17312. };
  17313. switch (cap) {
  17314. case BABYLON.Mesh.NO_CAP:
  17315. break;
  17316. case BABYLON.Mesh.CAP_START:
  17317. circlePaths[0] = capPath(tessellation, 0);
  17318. circlePaths[1] = circlePaths[2].slice(0);
  17319. break;
  17320. case BABYLON.Mesh.CAP_END:
  17321. circlePaths[index] = circlePaths[index - 1].slice(0);
  17322. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17323. break;
  17324. case BABYLON.Mesh.CAP_ALL:
  17325. circlePaths[0] = capPath(tessellation, 0);
  17326. circlePaths[1] = circlePaths[2].slice(0);
  17327. circlePaths[index] = circlePaths[index - 1].slice(0);
  17328. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17329. break;
  17330. default:
  17331. break;
  17332. }
  17333. return circlePaths;
  17334. };
  17335. var path3D;
  17336. var pathArray;
  17337. if (instance) {
  17338. var arc = options.arc || instance.arc;
  17339. path3D = (instance.path3D).update(path);
  17340. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17341. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17342. instance.path3D = path3D;
  17343. instance.pathArray = pathArray;
  17344. instance.arc = arc;
  17345. return instance;
  17346. }
  17347. // tube creation
  17348. path3D = new BABYLON.Path3D(path);
  17349. var newPathArray = new Array();
  17350. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17351. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17352. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17353. tube.pathArray = pathArray;
  17354. tube.path3D = path3D;
  17355. tube.tessellation = tessellation;
  17356. tube.cap = cap;
  17357. tube.arc = options.arc;
  17358. return tube;
  17359. };
  17360. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17361. var polyhedron = new BABYLON.Mesh(name, scene);
  17362. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17363. vertexData.applyToMesh(polyhedron, options.updatable);
  17364. return polyhedron;
  17365. };
  17366. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17367. var indices = sourceMesh.getIndices();
  17368. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17369. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17370. var position = options.position || BABYLON.Vector3.Zero();
  17371. var normal = options.normal || BABYLON.Vector3.Up();
  17372. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17373. var angle = options.angle || 0;
  17374. // Getting correct rotation
  17375. if (!normal) {
  17376. var target = new BABYLON.Vector3(0, 0, 1);
  17377. var camera = sourceMesh.getScene().activeCamera;
  17378. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17379. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17380. }
  17381. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17382. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17383. var pitch = Math.atan2(normal.y, len);
  17384. // Matrix
  17385. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17386. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17387. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17388. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17389. var vertexData = new BABYLON.VertexData();
  17390. vertexData.indices = [];
  17391. vertexData.positions = [];
  17392. vertexData.normals = [];
  17393. vertexData.uvs = [];
  17394. var currentVertexDataIndex = 0;
  17395. var extractDecalVector3 = function (indexId) {
  17396. var vertexId = indices[indexId];
  17397. var result = new BABYLON.PositionNormalVertex();
  17398. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17399. // Send vector to decal local world
  17400. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17401. // Get normal
  17402. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17403. return result;
  17404. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17405. var clip = function (vertices, axis) {
  17406. if (vertices.length === 0) {
  17407. return vertices;
  17408. }
  17409. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17410. var clipVertices = function (v0, v1) {
  17411. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17412. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17413. };
  17414. var result = new Array();
  17415. for (var index = 0; index < vertices.length; index += 3) {
  17416. var v1Out;
  17417. var v2Out;
  17418. var v3Out;
  17419. var total = 0;
  17420. var nV1, nV2, nV3, nV4;
  17421. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17422. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17423. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17424. v1Out = d1 > 0;
  17425. v2Out = d2 > 0;
  17426. v3Out = d3 > 0;
  17427. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17428. switch (total) {
  17429. case 0:
  17430. result.push(vertices[index]);
  17431. result.push(vertices[index + 1]);
  17432. result.push(vertices[index + 2]);
  17433. break;
  17434. case 1:
  17435. if (v1Out) {
  17436. nV1 = vertices[index + 1];
  17437. nV2 = vertices[index + 2];
  17438. nV3 = clipVertices(vertices[index], nV1);
  17439. nV4 = clipVertices(vertices[index], nV2);
  17440. }
  17441. if (v2Out) {
  17442. nV1 = vertices[index];
  17443. nV2 = vertices[index + 2];
  17444. nV3 = clipVertices(vertices[index + 1], nV1);
  17445. nV4 = clipVertices(vertices[index + 1], nV2);
  17446. result.push(nV3);
  17447. result.push(nV2.clone());
  17448. result.push(nV1.clone());
  17449. result.push(nV2.clone());
  17450. result.push(nV3.clone());
  17451. result.push(nV4);
  17452. break;
  17453. }
  17454. if (v3Out) {
  17455. nV1 = vertices[index];
  17456. nV2 = vertices[index + 1];
  17457. nV3 = clipVertices(vertices[index + 2], nV1);
  17458. nV4 = clipVertices(vertices[index + 2], nV2);
  17459. }
  17460. result.push(nV1.clone());
  17461. result.push(nV2.clone());
  17462. result.push(nV3);
  17463. result.push(nV4);
  17464. result.push(nV3.clone());
  17465. result.push(nV2.clone());
  17466. break;
  17467. case 2:
  17468. if (!v1Out) {
  17469. nV1 = vertices[index].clone();
  17470. nV2 = clipVertices(nV1, vertices[index + 1]);
  17471. nV3 = clipVertices(nV1, vertices[index + 2]);
  17472. result.push(nV1);
  17473. result.push(nV2);
  17474. result.push(nV3);
  17475. }
  17476. if (!v2Out) {
  17477. nV1 = vertices[index + 1].clone();
  17478. nV2 = clipVertices(nV1, vertices[index + 2]);
  17479. nV3 = clipVertices(nV1, vertices[index]);
  17480. result.push(nV1);
  17481. result.push(nV2);
  17482. result.push(nV3);
  17483. }
  17484. if (!v3Out) {
  17485. nV1 = vertices[index + 2].clone();
  17486. nV2 = clipVertices(nV1, vertices[index]);
  17487. nV3 = clipVertices(nV1, vertices[index + 1]);
  17488. result.push(nV1);
  17489. result.push(nV2);
  17490. result.push(nV3);
  17491. }
  17492. break;
  17493. case 3:
  17494. break;
  17495. }
  17496. }
  17497. return result;
  17498. };
  17499. for (var index = 0; index < indices.length; index += 3) {
  17500. var faceVertices = new Array();
  17501. faceVertices.push(extractDecalVector3(index));
  17502. faceVertices.push(extractDecalVector3(index + 1));
  17503. faceVertices.push(extractDecalVector3(index + 2));
  17504. // Clip
  17505. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17506. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17507. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17508. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17509. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17510. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17511. if (faceVertices.length === 0) {
  17512. continue;
  17513. }
  17514. // Add UVs and get back to world
  17515. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17516. var vertex = faceVertices[vIndex];
  17517. //TODO check for Int32Array
  17518. vertexData.indices.push(currentVertexDataIndex);
  17519. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17520. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17521. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17522. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17523. currentVertexDataIndex++;
  17524. }
  17525. }
  17526. // Return mesh
  17527. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17528. vertexData.applyToMesh(decal);
  17529. decal.position = position.clone();
  17530. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17531. return decal;
  17532. };
  17533. // Privates
  17534. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17535. // extrusion geometry
  17536. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17537. var tangents = path3D.getTangents();
  17538. var normals = path3D.getNormals();
  17539. var binormals = path3D.getBinormals();
  17540. var distances = path3D.getDistances();
  17541. var angle = 0;
  17542. var returnScale = function () { return scale; };
  17543. var returnRotation = function () { return rotation; };
  17544. var rotate = custom ? rotateFunction : returnRotation;
  17545. var scl = custom ? scaleFunction : returnScale;
  17546. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17547. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17548. for (var i = 0; i < curve.length; i++) {
  17549. var shapePath = new Array();
  17550. var angleStep = rotate(i, distances[i]);
  17551. var scaleRatio = scl(i, distances[i]);
  17552. for (var p = 0; p < shape.length; p++) {
  17553. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17554. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17555. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17556. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17557. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17558. shapePath[p] = rotated;
  17559. }
  17560. shapePaths[index] = shapePath;
  17561. angle += angleStep;
  17562. index++;
  17563. }
  17564. // cap
  17565. var capPath = function (shapePath) {
  17566. var pointCap = Array();
  17567. var barycenter = BABYLON.Vector3.Zero();
  17568. var i;
  17569. for (i = 0; i < shapePath.length; i++) {
  17570. barycenter.addInPlace(shapePath[i]);
  17571. }
  17572. barycenter.scaleInPlace(1 / shapePath.length);
  17573. for (i = 0; i < shapePath.length; i++) {
  17574. pointCap.push(barycenter);
  17575. }
  17576. return pointCap;
  17577. };
  17578. switch (cap) {
  17579. case BABYLON.Mesh.NO_CAP:
  17580. break;
  17581. case BABYLON.Mesh.CAP_START:
  17582. shapePaths[0] = capPath(shapePaths[2]);
  17583. shapePaths[1] = shapePaths[2].slice(0);
  17584. break;
  17585. case BABYLON.Mesh.CAP_END:
  17586. shapePaths[index] = shapePaths[index - 1];
  17587. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17588. break;
  17589. case BABYLON.Mesh.CAP_ALL:
  17590. shapePaths[0] = capPath(shapePaths[2]);
  17591. shapePaths[1] = shapePaths[2].slice(0);
  17592. shapePaths[index] = shapePaths[index - 1];
  17593. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17594. break;
  17595. default:
  17596. break;
  17597. }
  17598. return shapePaths;
  17599. };
  17600. var path3D;
  17601. var pathArray;
  17602. if (instance) {
  17603. path3D = (instance.path3D).update(curve);
  17604. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17605. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17606. return instance;
  17607. }
  17608. // extruded shape creation
  17609. path3D = new BABYLON.Path3D(curve);
  17610. var newShapePaths = new Array();
  17611. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17612. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17613. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17614. extrudedGeneric.pathArray = pathArray;
  17615. extrudedGeneric.path3D = path3D;
  17616. extrudedGeneric.cap = cap;
  17617. return extrudedGeneric;
  17618. };
  17619. return MeshBuilder;
  17620. })();
  17621. BABYLON.MeshBuilder = MeshBuilder;
  17622. })(BABYLON || (BABYLON = {}));
  17623. var BABYLON;
  17624. (function (BABYLON) {
  17625. var BaseTexture = (function () {
  17626. function BaseTexture(scene) {
  17627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17628. this.hasAlpha = false;
  17629. this.getAlphaFromRGB = false;
  17630. this.level = 1;
  17631. this.isCube = false;
  17632. this.isRenderTarget = false;
  17633. this.animations = new Array();
  17634. this.coordinatesIndex = 0;
  17635. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17636. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17637. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17638. this.anisotropicFilteringLevel = 4;
  17639. this._scene = scene;
  17640. this._scene.textures.push(this);
  17641. }
  17642. BaseTexture.prototype.getScene = function () {
  17643. return this._scene;
  17644. };
  17645. BaseTexture.prototype.getTextureMatrix = function () {
  17646. return null;
  17647. };
  17648. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17649. return null;
  17650. };
  17651. BaseTexture.prototype.getInternalTexture = function () {
  17652. return this._texture;
  17653. };
  17654. BaseTexture.prototype.isReady = function () {
  17655. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17656. return true;
  17657. }
  17658. if (this._texture) {
  17659. return this._texture.isReady;
  17660. }
  17661. return false;
  17662. };
  17663. BaseTexture.prototype.getSize = function () {
  17664. if (this._texture._width) {
  17665. return { width: this._texture._width, height: this._texture._height };
  17666. }
  17667. if (this._texture._size) {
  17668. return { width: this._texture._size, height: this._texture._size };
  17669. }
  17670. return { width: 0, height: 0 };
  17671. };
  17672. BaseTexture.prototype.getBaseSize = function () {
  17673. if (!this.isReady())
  17674. return { width: 0, height: 0 };
  17675. if (this._texture._size) {
  17676. return { width: this._texture._size, height: this._texture._size };
  17677. }
  17678. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17679. };
  17680. BaseTexture.prototype.scale = function (ratio) {
  17681. };
  17682. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17683. get: function () {
  17684. return false;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17690. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17691. for (var index = 0; index < texturesCache.length; index++) {
  17692. var texturesCacheEntry = texturesCache[index];
  17693. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17694. texturesCache.splice(index, 1);
  17695. return;
  17696. }
  17697. }
  17698. };
  17699. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17700. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17701. for (var index = 0; index < texturesCache.length; index++) {
  17702. var texturesCacheEntry = texturesCache[index];
  17703. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17704. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17705. texturesCacheEntry.references++;
  17706. return texturesCacheEntry;
  17707. }
  17708. }
  17709. }
  17710. return null;
  17711. };
  17712. BaseTexture.prototype.delayLoad = function () {
  17713. };
  17714. BaseTexture.prototype.clone = function () {
  17715. return null;
  17716. };
  17717. BaseTexture.prototype.releaseInternalTexture = function () {
  17718. if (this._texture) {
  17719. this._scene.getEngine().releaseInternalTexture(this._texture);
  17720. delete this._texture;
  17721. }
  17722. };
  17723. BaseTexture.prototype.dispose = function () {
  17724. // Animations
  17725. this.getScene().stopAnimation(this);
  17726. // Remove from scene
  17727. var index = this._scene.textures.indexOf(this);
  17728. if (index >= 0) {
  17729. this._scene.textures.splice(index, 1);
  17730. }
  17731. if (this._texture === undefined) {
  17732. return;
  17733. }
  17734. // Release
  17735. this.releaseInternalTexture();
  17736. // Callback
  17737. if (this.onDispose) {
  17738. this.onDispose();
  17739. }
  17740. };
  17741. BaseTexture.prototype.serialize = function () {
  17742. var serializationObject = {};
  17743. if (!this.name) {
  17744. return null;
  17745. }
  17746. serializationObject.name = this.name;
  17747. serializationObject.hasAlpha = this.hasAlpha;
  17748. serializationObject.level = this.level;
  17749. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17750. serializationObject.coordinatesMode = this.coordinatesMode;
  17751. serializationObject.wrapU = this.wrapU;
  17752. serializationObject.wrapV = this.wrapV;
  17753. // Animations
  17754. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17755. return serializationObject;
  17756. };
  17757. return BaseTexture;
  17758. })();
  17759. BABYLON.BaseTexture = BaseTexture;
  17760. })(BABYLON || (BABYLON = {}));
  17761. var BABYLON;
  17762. (function (BABYLON) {
  17763. var Texture = (function (_super) {
  17764. __extends(Texture, _super);
  17765. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17766. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17767. if (onLoad === void 0) { onLoad = null; }
  17768. if (onError === void 0) { onError = null; }
  17769. if (buffer === void 0) { buffer = null; }
  17770. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17771. _super.call(this, scene);
  17772. this.uOffset = 0;
  17773. this.vOffset = 0;
  17774. this.uScale = 1.0;
  17775. this.vScale = 1.0;
  17776. this.uAng = 0;
  17777. this.vAng = 0;
  17778. this.wAng = 0;
  17779. this.name = url;
  17780. this.url = url;
  17781. this._noMipmap = noMipmap;
  17782. this._invertY = invertY;
  17783. this._samplingMode = samplingMode;
  17784. this._buffer = buffer;
  17785. this._deleteBuffer = deleteBuffer;
  17786. if (!url) {
  17787. return;
  17788. }
  17789. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17790. if (!this._texture) {
  17791. if (!scene.useDelayedTextureLoading) {
  17792. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17793. if (deleteBuffer) {
  17794. delete this._buffer;
  17795. }
  17796. }
  17797. else {
  17798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17799. this._delayedOnLoad = onLoad;
  17800. this._delayedOnError = onError;
  17801. }
  17802. }
  17803. else {
  17804. BABYLON.Tools.SetImmediate(function () {
  17805. if (onLoad) {
  17806. onLoad();
  17807. }
  17808. });
  17809. }
  17810. }
  17811. Texture.prototype.delayLoad = function () {
  17812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17813. return;
  17814. }
  17815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17816. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17817. if (!this._texture) {
  17818. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17819. if (this._deleteBuffer) {
  17820. delete this._buffer;
  17821. }
  17822. }
  17823. };
  17824. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17825. if (!this._texture) {
  17826. return;
  17827. }
  17828. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17829. };
  17830. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17831. x *= this.uScale;
  17832. y *= this.vScale;
  17833. x -= 0.5 * this.uScale;
  17834. y -= 0.5 * this.vScale;
  17835. z -= 0.5;
  17836. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17837. t.x += 0.5 * this.uScale + this.uOffset;
  17838. t.y += 0.5 * this.vScale + this.vOffset;
  17839. t.z += 0.5;
  17840. };
  17841. Texture.prototype.getTextureMatrix = function () {
  17842. if (this.uOffset === this._cachedUOffset &&
  17843. this.vOffset === this._cachedVOffset &&
  17844. this.uScale === this._cachedUScale &&
  17845. this.vScale === this._cachedVScale &&
  17846. this.uAng === this._cachedUAng &&
  17847. this.vAng === this._cachedVAng &&
  17848. this.wAng === this._cachedWAng) {
  17849. return this._cachedTextureMatrix;
  17850. }
  17851. this._cachedUOffset = this.uOffset;
  17852. this._cachedVOffset = this.vOffset;
  17853. this._cachedUScale = this.uScale;
  17854. this._cachedVScale = this.vScale;
  17855. this._cachedUAng = this.uAng;
  17856. this._cachedVAng = this.vAng;
  17857. this._cachedWAng = this.wAng;
  17858. if (!this._cachedTextureMatrix) {
  17859. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17860. this._rowGenerationMatrix = new BABYLON.Matrix();
  17861. this._t0 = BABYLON.Vector3.Zero();
  17862. this._t1 = BABYLON.Vector3.Zero();
  17863. this._t2 = BABYLON.Vector3.Zero();
  17864. }
  17865. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17866. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17867. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17868. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17869. this._t1.subtractInPlace(this._t0);
  17870. this._t2.subtractInPlace(this._t0);
  17871. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17872. this._cachedTextureMatrix.m[0] = this._t1.x;
  17873. this._cachedTextureMatrix.m[1] = this._t1.y;
  17874. this._cachedTextureMatrix.m[2] = this._t1.z;
  17875. this._cachedTextureMatrix.m[4] = this._t2.x;
  17876. this._cachedTextureMatrix.m[5] = this._t2.y;
  17877. this._cachedTextureMatrix.m[6] = this._t2.z;
  17878. this._cachedTextureMatrix.m[8] = this._t0.x;
  17879. this._cachedTextureMatrix.m[9] = this._t0.y;
  17880. this._cachedTextureMatrix.m[10] = this._t0.z;
  17881. return this._cachedTextureMatrix;
  17882. };
  17883. Texture.prototype.getReflectionTextureMatrix = function () {
  17884. if (this.uOffset === this._cachedUOffset &&
  17885. this.vOffset === this._cachedVOffset &&
  17886. this.uScale === this._cachedUScale &&
  17887. this.vScale === this._cachedVScale &&
  17888. this.coordinatesMode === this._cachedCoordinatesMode) {
  17889. return this._cachedTextureMatrix;
  17890. }
  17891. if (!this._cachedTextureMatrix) {
  17892. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17893. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17894. }
  17895. this._cachedCoordinatesMode = this.coordinatesMode;
  17896. switch (this.coordinatesMode) {
  17897. case Texture.PLANAR_MODE:
  17898. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17899. this._cachedTextureMatrix[0] = this.uScale;
  17900. this._cachedTextureMatrix[5] = this.vScale;
  17901. this._cachedTextureMatrix[12] = this.uOffset;
  17902. this._cachedTextureMatrix[13] = this.vOffset;
  17903. break;
  17904. case Texture.PROJECTION_MODE:
  17905. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17906. this._projectionModeMatrix.m[0] = 0.5;
  17907. this._projectionModeMatrix.m[5] = -0.5;
  17908. this._projectionModeMatrix.m[10] = 0.0;
  17909. this._projectionModeMatrix.m[12] = 0.5;
  17910. this._projectionModeMatrix.m[13] = 0.5;
  17911. this._projectionModeMatrix.m[14] = 1.0;
  17912. this._projectionModeMatrix.m[15] = 1.0;
  17913. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17914. break;
  17915. default:
  17916. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17917. break;
  17918. }
  17919. return this._cachedTextureMatrix;
  17920. };
  17921. Texture.prototype.clone = function () {
  17922. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17923. // Base texture
  17924. newTexture.hasAlpha = this.hasAlpha;
  17925. newTexture.level = this.level;
  17926. newTexture.wrapU = this.wrapU;
  17927. newTexture.wrapV = this.wrapV;
  17928. newTexture.coordinatesIndex = this.coordinatesIndex;
  17929. newTexture.coordinatesMode = this.coordinatesMode;
  17930. // Texture
  17931. newTexture.uOffset = this.uOffset;
  17932. newTexture.vOffset = this.vOffset;
  17933. newTexture.uScale = this.uScale;
  17934. newTexture.vScale = this.vScale;
  17935. newTexture.uAng = this.uAng;
  17936. newTexture.vAng = this.vAng;
  17937. newTexture.wAng = this.wAng;
  17938. return newTexture;
  17939. };
  17940. Texture.prototype.serialize = function () {
  17941. if (!this.name) {
  17942. return null;
  17943. }
  17944. var serializationObject = _super.prototype.serialize.call(this);
  17945. serializationObject.uOffset = this.uOffset;
  17946. serializationObject.vOffset = this.vOffset;
  17947. serializationObject.uScale = this.uScale;
  17948. serializationObject.vScale = this.vScale;
  17949. serializationObject.uAng = this.uAng;
  17950. serializationObject.vAng = this.vAng;
  17951. serializationObject.wAng = this.wAng;
  17952. return serializationObject;
  17953. };
  17954. // Statics
  17955. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17956. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17957. if (onLoad === void 0) { onLoad = null; }
  17958. if (onError === void 0) { onError = null; }
  17959. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17960. };
  17961. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17962. if (parsedTexture.isCube) {
  17963. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17964. }
  17965. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17966. return null;
  17967. }
  17968. var texture;
  17969. if (parsedTexture.mirrorPlane) {
  17970. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17971. texture._waitingRenderList = parsedTexture.renderList;
  17972. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17973. }
  17974. else if (parsedTexture.isRenderTarget) {
  17975. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17976. texture._waitingRenderList = parsedTexture.renderList;
  17977. }
  17978. else {
  17979. if (parsedTexture.base64String) {
  17980. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17981. }
  17982. else {
  17983. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17984. }
  17985. }
  17986. texture.name = parsedTexture.name;
  17987. texture.hasAlpha = parsedTexture.hasAlpha;
  17988. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17989. texture.level = parsedTexture.level;
  17990. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17991. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17992. texture.uOffset = parsedTexture.uOffset;
  17993. texture.vOffset = parsedTexture.vOffset;
  17994. texture.uScale = parsedTexture.uScale;
  17995. texture.vScale = parsedTexture.vScale;
  17996. texture.uAng = parsedTexture.uAng;
  17997. texture.vAng = parsedTexture.vAng;
  17998. texture.wAng = parsedTexture.wAng;
  17999. texture.wrapU = parsedTexture.wrapU;
  18000. texture.wrapV = parsedTexture.wrapV;
  18001. // Animations
  18002. if (parsedTexture.animations) {
  18003. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18004. var parsedAnimation = parsedTexture.animations[animationIndex];
  18005. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18006. }
  18007. }
  18008. return texture;
  18009. };
  18010. // Constants
  18011. Texture.NEAREST_SAMPLINGMODE = 1;
  18012. Texture.BILINEAR_SAMPLINGMODE = 2;
  18013. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18014. Texture.EXPLICIT_MODE = 0;
  18015. Texture.SPHERICAL_MODE = 1;
  18016. Texture.PLANAR_MODE = 2;
  18017. Texture.CUBIC_MODE = 3;
  18018. Texture.PROJECTION_MODE = 4;
  18019. Texture.SKYBOX_MODE = 5;
  18020. Texture.INVCUBIC_MODE = 6;
  18021. Texture.EQUIRECTANGULAR_MODE = 7;
  18022. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18023. Texture.CLAMP_ADDRESSMODE = 0;
  18024. Texture.WRAP_ADDRESSMODE = 1;
  18025. Texture.MIRROR_ADDRESSMODE = 2;
  18026. return Texture;
  18027. })(BABYLON.BaseTexture);
  18028. BABYLON.Texture = Texture;
  18029. })(BABYLON || (BABYLON = {}));
  18030. var BABYLON;
  18031. (function (BABYLON) {
  18032. var CubeTexture = (function (_super) {
  18033. __extends(CubeTexture, _super);
  18034. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18035. _super.call(this, scene);
  18036. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18037. this.name = rootUrl;
  18038. this.url = rootUrl;
  18039. this._noMipmap = noMipmap;
  18040. this.hasAlpha = false;
  18041. if (!rootUrl && !files) {
  18042. return;
  18043. }
  18044. this._texture = this._getFromCache(rootUrl, noMipmap);
  18045. if (!files) {
  18046. if (!extensions) {
  18047. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18048. }
  18049. files = [];
  18050. for (var index = 0; index < extensions.length; index++) {
  18051. files.push(rootUrl + extensions[index]);
  18052. }
  18053. this._extensions = extensions;
  18054. }
  18055. this._files = files;
  18056. if (!this._texture) {
  18057. if (!scene.useDelayedTextureLoading) {
  18058. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18059. }
  18060. else {
  18061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18062. }
  18063. }
  18064. this.isCube = true;
  18065. this._textureMatrix = BABYLON.Matrix.Identity();
  18066. }
  18067. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18068. return new CubeTexture("", scene, null, noMipmap, files);
  18069. };
  18070. CubeTexture.prototype.clone = function () {
  18071. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18072. // Base texture
  18073. newTexture.level = this.level;
  18074. newTexture.wrapU = this.wrapU;
  18075. newTexture.wrapV = this.wrapV;
  18076. newTexture.coordinatesIndex = this.coordinatesIndex;
  18077. newTexture.coordinatesMode = this.coordinatesMode;
  18078. return newTexture;
  18079. };
  18080. // Methods
  18081. CubeTexture.prototype.delayLoad = function () {
  18082. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18083. return;
  18084. }
  18085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18086. this._texture = this._getFromCache(this.url, this._noMipmap);
  18087. if (!this._texture) {
  18088. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18089. }
  18090. };
  18091. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18092. return this._textureMatrix;
  18093. };
  18094. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18095. var texture = null;
  18096. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18097. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18098. texture.name = parsedTexture.name;
  18099. texture.hasAlpha = parsedTexture.hasAlpha;
  18100. texture.level = parsedTexture.level;
  18101. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18102. }
  18103. return texture;
  18104. };
  18105. CubeTexture.prototype.serialize = function () {
  18106. if (!this.name) {
  18107. return null;
  18108. }
  18109. var serializationObject = {};
  18110. serializationObject.name = this.name;
  18111. serializationObject.hasAlpha = this.hasAlpha;
  18112. serializationObject.isCube = true;
  18113. serializationObject.level = this.level;
  18114. serializationObject.coordinatesMode = this.coordinatesMode;
  18115. return serializationObject;
  18116. };
  18117. return CubeTexture;
  18118. })(BABYLON.BaseTexture);
  18119. BABYLON.CubeTexture = CubeTexture;
  18120. })(BABYLON || (BABYLON = {}));
  18121. var BABYLON;
  18122. (function (BABYLON) {
  18123. var RenderTargetTexture = (function (_super) {
  18124. __extends(RenderTargetTexture, _super);
  18125. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18126. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18127. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18128. if (isCube === void 0) { isCube = false; }
  18129. _super.call(this, null, scene, !generateMipMaps);
  18130. this.isCube = isCube;
  18131. this.renderList = new Array();
  18132. this.renderParticles = true;
  18133. this.renderSprites = false;
  18134. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18135. this._currentRefreshId = -1;
  18136. this._refreshRate = 1;
  18137. this.name = name;
  18138. this.isRenderTarget = true;
  18139. this._size = size;
  18140. this._generateMipMaps = generateMipMaps;
  18141. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18142. if (isCube) {
  18143. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18144. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18145. this._textureMatrix = BABYLON.Matrix.Identity();
  18146. }
  18147. else {
  18148. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18149. }
  18150. // Rendering groups
  18151. this._renderingManager = new BABYLON.RenderingManager(scene);
  18152. }
  18153. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18154. get: function () {
  18155. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18156. },
  18157. enumerable: true,
  18158. configurable: true
  18159. });
  18160. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18161. get: function () {
  18162. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18163. },
  18164. enumerable: true,
  18165. configurable: true
  18166. });
  18167. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18168. get: function () {
  18169. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18175. this._currentRefreshId = -1;
  18176. };
  18177. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18178. get: function () {
  18179. return this._refreshRate;
  18180. },
  18181. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18182. set: function (value) {
  18183. this._refreshRate = value;
  18184. this.resetRefreshCounter();
  18185. },
  18186. enumerable: true,
  18187. configurable: true
  18188. });
  18189. RenderTargetTexture.prototype._shouldRender = function () {
  18190. if (this._currentRefreshId === -1) {
  18191. this._currentRefreshId = 1;
  18192. return true;
  18193. }
  18194. if (this.refreshRate === this._currentRefreshId) {
  18195. this._currentRefreshId = 1;
  18196. return true;
  18197. }
  18198. this._currentRefreshId++;
  18199. return false;
  18200. };
  18201. RenderTargetTexture.prototype.isReady = function () {
  18202. if (!this.getScene().renderTargetsEnabled) {
  18203. return false;
  18204. }
  18205. return _super.prototype.isReady.call(this);
  18206. };
  18207. RenderTargetTexture.prototype.getRenderSize = function () {
  18208. return this._size;
  18209. };
  18210. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18211. get: function () {
  18212. return true;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. RenderTargetTexture.prototype.scale = function (ratio) {
  18218. var newSize = this._size * ratio;
  18219. this.resize(newSize, this._generateMipMaps);
  18220. };
  18221. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18222. if (this.isCube) {
  18223. return this._textureMatrix;
  18224. }
  18225. return _super.prototype.getReflectionTextureMatrix.call(this);
  18226. };
  18227. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18228. this.releaseInternalTexture();
  18229. if (this.isCube) {
  18230. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18231. }
  18232. else {
  18233. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18234. }
  18235. };
  18236. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18237. var scene = this.getScene();
  18238. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18239. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18240. }
  18241. if (this._waitingRenderList) {
  18242. this.renderList = [];
  18243. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18244. var id = this._waitingRenderList[index];
  18245. this.renderList.push(scene.getMeshByID(id));
  18246. }
  18247. delete this._waitingRenderList;
  18248. }
  18249. if (this.renderList && this.renderList.length === 0) {
  18250. return;
  18251. }
  18252. // Prepare renderingManager
  18253. this._renderingManager.reset();
  18254. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18255. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18256. var mesh = currentRenderList[meshIndex];
  18257. if (mesh) {
  18258. if (!mesh.isReady()) {
  18259. // Reset _currentRefreshId
  18260. this.resetRefreshCounter();
  18261. continue;
  18262. }
  18263. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18264. mesh._activate(scene.getRenderId());
  18265. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18266. var subMesh = mesh.subMeshes[subIndex];
  18267. scene._activeIndices += subMesh.indexCount;
  18268. this._renderingManager.dispatch(subMesh);
  18269. }
  18270. }
  18271. }
  18272. }
  18273. if (this.isCube) {
  18274. for (var face = 0; face < 6; face++) {
  18275. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18276. scene.incrementRenderId();
  18277. }
  18278. }
  18279. else {
  18280. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18281. }
  18282. if (this.onAfterUnbind) {
  18283. this.onAfterUnbind();
  18284. }
  18285. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18286. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18287. }
  18288. scene.resetCachedMaterial();
  18289. };
  18290. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18291. var scene = this.getScene();
  18292. var engine = scene.getEngine();
  18293. // Bind
  18294. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18295. if (this.isCube) {
  18296. engine.bindFramebuffer(this._texture, faceIndex);
  18297. }
  18298. else {
  18299. engine.bindFramebuffer(this._texture);
  18300. }
  18301. }
  18302. if (this.onBeforeRender) {
  18303. this.onBeforeRender(faceIndex);
  18304. }
  18305. // Clear
  18306. if (this.onClear) {
  18307. this.onClear(engine);
  18308. }
  18309. else {
  18310. engine.clear(scene.clearColor, true, true);
  18311. }
  18312. if (!this._doNotChangeAspectRatio) {
  18313. scene.updateTransformMatrix(true);
  18314. }
  18315. // Render
  18316. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18317. if (useCameraPostProcess) {
  18318. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18319. }
  18320. if (!this._doNotChangeAspectRatio) {
  18321. scene.updateTransformMatrix(true);
  18322. }
  18323. if (this.onAfterRender) {
  18324. this.onAfterRender(faceIndex);
  18325. }
  18326. // Dump ?
  18327. if (dumpForDebug) {
  18328. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18329. }
  18330. // Unbind
  18331. if (!this.isCube || faceIndex === 5) {
  18332. if (this.isCube) {
  18333. if (faceIndex === 5) {
  18334. engine.generateMipMapsForCubemap(this._texture);
  18335. }
  18336. }
  18337. engine.unBindFramebuffer(this._texture, this.isCube);
  18338. }
  18339. };
  18340. RenderTargetTexture.prototype.clone = function () {
  18341. var textureSize = this.getSize();
  18342. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18343. // Base texture
  18344. newTexture.hasAlpha = this.hasAlpha;
  18345. newTexture.level = this.level;
  18346. // RenderTarget Texture
  18347. newTexture.coordinatesMode = this.coordinatesMode;
  18348. newTexture.renderList = this.renderList.slice(0);
  18349. return newTexture;
  18350. };
  18351. RenderTargetTexture.prototype.serialize = function () {
  18352. if (!this.name) {
  18353. return null;
  18354. }
  18355. var serializationObject = _super.prototype.serialize.call(this);
  18356. serializationObject.renderTargetSize = this.getRenderSize();
  18357. serializationObject.renderList = [];
  18358. for (var index = 0; index < this.renderList.length; index++) {
  18359. serializationObject.renderList.push(this.renderList[index].id);
  18360. }
  18361. return serializationObject;
  18362. };
  18363. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18364. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18365. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18366. return RenderTargetTexture;
  18367. })(BABYLON.Texture);
  18368. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18369. })(BABYLON || (BABYLON = {}));
  18370. var BABYLON;
  18371. (function (BABYLON) {
  18372. var ProceduralTexture = (function (_super) {
  18373. __extends(ProceduralTexture, _super);
  18374. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18375. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18376. if (isCube === void 0) { isCube = false; }
  18377. _super.call(this, null, scene, !generateMipMaps);
  18378. this.isCube = isCube;
  18379. this.isEnabled = true;
  18380. this._currentRefreshId = -1;
  18381. this._refreshRate = 1;
  18382. this._vertexDeclaration = [2];
  18383. this._vertexStrideSize = 2 * 4;
  18384. this._uniforms = new Array();
  18385. this._samplers = new Array();
  18386. this._textures = new Array();
  18387. this._floats = new Array();
  18388. this._floatsArrays = {};
  18389. this._colors3 = new Array();
  18390. this._colors4 = new Array();
  18391. this._vectors2 = new Array();
  18392. this._vectors3 = new Array();
  18393. this._matrices = new Array();
  18394. this._fallbackTextureUsed = false;
  18395. scene._proceduralTextures.push(this);
  18396. this.name = name;
  18397. this.isRenderTarget = true;
  18398. this._size = size;
  18399. this._generateMipMaps = generateMipMaps;
  18400. this.setFragment(fragment);
  18401. this._fallbackTexture = fallbackTexture;
  18402. if (isCube) {
  18403. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18404. this.setFloat("face", 0);
  18405. }
  18406. else {
  18407. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18408. }
  18409. // VBO
  18410. var vertices = [];
  18411. vertices.push(1, 1);
  18412. vertices.push(-1, 1);
  18413. vertices.push(-1, -1);
  18414. vertices.push(1, -1);
  18415. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18416. // Indices
  18417. var indices = [];
  18418. indices.push(0);
  18419. indices.push(1);
  18420. indices.push(2);
  18421. indices.push(0);
  18422. indices.push(2);
  18423. indices.push(3);
  18424. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18425. }
  18426. ProceduralTexture.prototype.reset = function () {
  18427. if (this._effect === undefined) {
  18428. return;
  18429. }
  18430. var engine = this.getScene().getEngine();
  18431. engine._releaseEffect(this._effect);
  18432. };
  18433. ProceduralTexture.prototype.isReady = function () {
  18434. var _this = this;
  18435. var engine = this.getScene().getEngine();
  18436. var shaders;
  18437. if (!this._fragment) {
  18438. return false;
  18439. }
  18440. if (this._fallbackTextureUsed) {
  18441. return true;
  18442. }
  18443. if (this._fragment.fragmentElement !== undefined) {
  18444. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18445. }
  18446. else {
  18447. shaders = { vertex: "procedural", fragment: this._fragment };
  18448. }
  18449. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18450. _this.releaseInternalTexture();
  18451. if (_this._fallbackTexture) {
  18452. _this._texture = _this._fallbackTexture._texture;
  18453. _this._texture.references++;
  18454. }
  18455. _this._fallbackTextureUsed = true;
  18456. });
  18457. return this._effect.isReady();
  18458. };
  18459. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18460. this._currentRefreshId = -1;
  18461. };
  18462. ProceduralTexture.prototype.setFragment = function (fragment) {
  18463. this._fragment = fragment;
  18464. };
  18465. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18466. get: function () {
  18467. return this._refreshRate;
  18468. },
  18469. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18470. set: function (value) {
  18471. this._refreshRate = value;
  18472. this.resetRefreshCounter();
  18473. },
  18474. enumerable: true,
  18475. configurable: true
  18476. });
  18477. ProceduralTexture.prototype._shouldRender = function () {
  18478. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18479. return false;
  18480. }
  18481. if (this._fallbackTextureUsed) {
  18482. return false;
  18483. }
  18484. if (this._currentRefreshId === -1) {
  18485. this._currentRefreshId = 1;
  18486. return true;
  18487. }
  18488. if (this.refreshRate === this._currentRefreshId) {
  18489. this._currentRefreshId = 1;
  18490. return true;
  18491. }
  18492. this._currentRefreshId++;
  18493. return false;
  18494. };
  18495. ProceduralTexture.prototype.getRenderSize = function () {
  18496. return this._size;
  18497. };
  18498. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18499. if (this._fallbackTextureUsed) {
  18500. return;
  18501. }
  18502. this.releaseInternalTexture();
  18503. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18504. };
  18505. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18506. if (this._uniforms.indexOf(uniformName) === -1) {
  18507. this._uniforms.push(uniformName);
  18508. }
  18509. };
  18510. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18511. if (this._samplers.indexOf(name) === -1) {
  18512. this._samplers.push(name);
  18513. }
  18514. this._textures[name] = texture;
  18515. return this;
  18516. };
  18517. ProceduralTexture.prototype.setFloat = function (name, value) {
  18518. this._checkUniform(name);
  18519. this._floats[name] = value;
  18520. return this;
  18521. };
  18522. ProceduralTexture.prototype.setFloats = function (name, value) {
  18523. this._checkUniform(name);
  18524. this._floatsArrays[name] = value;
  18525. return this;
  18526. };
  18527. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18528. this._checkUniform(name);
  18529. this._colors3[name] = value;
  18530. return this;
  18531. };
  18532. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18533. this._checkUniform(name);
  18534. this._colors4[name] = value;
  18535. return this;
  18536. };
  18537. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18538. this._checkUniform(name);
  18539. this._vectors2[name] = value;
  18540. return this;
  18541. };
  18542. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18543. this._checkUniform(name);
  18544. this._vectors3[name] = value;
  18545. return this;
  18546. };
  18547. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18548. this._checkUniform(name);
  18549. this._matrices[name] = value;
  18550. return this;
  18551. };
  18552. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18553. var scene = this.getScene();
  18554. var engine = scene.getEngine();
  18555. // Render
  18556. engine.enableEffect(this._effect);
  18557. engine.setState(false);
  18558. // Texture
  18559. for (var name in this._textures) {
  18560. this._effect.setTexture(name, this._textures[name]);
  18561. }
  18562. // Float
  18563. for (name in this._floats) {
  18564. this._effect.setFloat(name, this._floats[name]);
  18565. }
  18566. // Floats
  18567. for (name in this._floatsArrays) {
  18568. this._effect.setArray(name, this._floatsArrays[name]);
  18569. }
  18570. // Color3
  18571. for (name in this._colors3) {
  18572. this._effect.setColor3(name, this._colors3[name]);
  18573. }
  18574. // Color4
  18575. for (name in this._colors4) {
  18576. var color = this._colors4[name];
  18577. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18578. }
  18579. // Vector2
  18580. for (name in this._vectors2) {
  18581. this._effect.setVector2(name, this._vectors2[name]);
  18582. }
  18583. // Vector3
  18584. for (name in this._vectors3) {
  18585. this._effect.setVector3(name, this._vectors3[name]);
  18586. }
  18587. // Matrix
  18588. for (name in this._matrices) {
  18589. this._effect.setMatrix(name, this._matrices[name]);
  18590. }
  18591. // VBOs
  18592. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18593. if (this.isCube) {
  18594. for (var face = 0; face < 6; face++) {
  18595. engine.bindFramebuffer(this._texture, face);
  18596. this._effect.setFloat("face", face);
  18597. // Clear
  18598. engine.clear(scene.clearColor, true, true);
  18599. // Draw order
  18600. engine.draw(true, 0, 6);
  18601. // Mipmaps
  18602. if (face === 5) {
  18603. engine.generateMipMapsForCubemap(this._texture);
  18604. }
  18605. }
  18606. }
  18607. else {
  18608. engine.bindFramebuffer(this._texture);
  18609. // Clear
  18610. engine.clear(scene.clearColor, true, true);
  18611. // Draw order
  18612. engine.draw(true, 0, 6);
  18613. }
  18614. // Unbind
  18615. engine.unBindFramebuffer(this._texture, this.isCube);
  18616. if (this.onGenerated) {
  18617. this.onGenerated();
  18618. }
  18619. };
  18620. ProceduralTexture.prototype.clone = function () {
  18621. var textureSize = this.getSize();
  18622. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18623. // Base texture
  18624. newTexture.hasAlpha = this.hasAlpha;
  18625. newTexture.level = this.level;
  18626. // RenderTarget Texture
  18627. newTexture.coordinatesMode = this.coordinatesMode;
  18628. return newTexture;
  18629. };
  18630. ProceduralTexture.prototype.dispose = function () {
  18631. var index = this.getScene()._proceduralTextures.indexOf(this);
  18632. if (index >= 0) {
  18633. this.getScene()._proceduralTextures.splice(index, 1);
  18634. }
  18635. _super.prototype.dispose.call(this);
  18636. };
  18637. return ProceduralTexture;
  18638. })(BABYLON.Texture);
  18639. BABYLON.ProceduralTexture = ProceduralTexture;
  18640. })(BABYLON || (BABYLON = {}));
  18641. var BABYLON;
  18642. (function (BABYLON) {
  18643. var MirrorTexture = (function (_super) {
  18644. __extends(MirrorTexture, _super);
  18645. function MirrorTexture(name, size, scene, generateMipMaps) {
  18646. var _this = this;
  18647. _super.call(this, name, size, scene, generateMipMaps, true);
  18648. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18649. this._transformMatrix = BABYLON.Matrix.Zero();
  18650. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18651. this.onBeforeRender = function () {
  18652. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18653. _this._savedViewMatrix = scene.getViewMatrix();
  18654. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18655. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18656. scene.clipPlane = _this.mirrorPlane;
  18657. scene.getEngine().cullBackFaces = false;
  18658. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18659. };
  18660. this.onAfterRender = function () {
  18661. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18662. scene.getEngine().cullBackFaces = true;
  18663. scene._mirroredCameraPosition = null;
  18664. delete scene.clipPlane;
  18665. };
  18666. }
  18667. MirrorTexture.prototype.clone = function () {
  18668. var textureSize = this.getSize();
  18669. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18670. // Base texture
  18671. newTexture.hasAlpha = this.hasAlpha;
  18672. newTexture.level = this.level;
  18673. // Mirror Texture
  18674. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18675. newTexture.renderList = this.renderList.slice(0);
  18676. return newTexture;
  18677. };
  18678. MirrorTexture.prototype.serialize = function () {
  18679. if (!this.name) {
  18680. return null;
  18681. }
  18682. var serializationObject = _super.prototype.serialize.call(this);
  18683. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18684. return serializationObject;
  18685. };
  18686. return MirrorTexture;
  18687. })(BABYLON.RenderTargetTexture);
  18688. BABYLON.MirrorTexture = MirrorTexture;
  18689. })(BABYLON || (BABYLON = {}));
  18690. var BABYLON;
  18691. (function (BABYLON) {
  18692. /**
  18693. * Creates a refraction texture used by refraction channel of the standard material.
  18694. * @param name the texture name
  18695. * @param size size of the underlying texture
  18696. * @param scene root scene
  18697. */
  18698. var RefractionTexture = (function (_super) {
  18699. __extends(RefractionTexture, _super);
  18700. function RefractionTexture(name, size, scene, generateMipMaps) {
  18701. var _this = this;
  18702. _super.call(this, name, size, scene, generateMipMaps, true);
  18703. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18704. this.depth = 2.0;
  18705. this.onBeforeRender = function () {
  18706. scene.clipPlane = _this.refractionPlane;
  18707. };
  18708. this.onAfterRender = function () {
  18709. delete scene.clipPlane;
  18710. };
  18711. }
  18712. RefractionTexture.prototype.clone = function () {
  18713. var textureSize = this.getSize();
  18714. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18715. // Base texture
  18716. newTexture.hasAlpha = this.hasAlpha;
  18717. newTexture.level = this.level;
  18718. // Refraction Texture
  18719. newTexture.refractionPlane = this.refractionPlane.clone();
  18720. newTexture.renderList = this.renderList.slice(0);
  18721. newTexture.depth = this.depth;
  18722. return newTexture;
  18723. };
  18724. RefractionTexture.prototype.serialize = function () {
  18725. if (!this.name) {
  18726. return null;
  18727. }
  18728. var serializationObject = _super.prototype.serialize.call(this);
  18729. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18730. serializationObject.depth = this.depth;
  18731. return serializationObject;
  18732. };
  18733. return RefractionTexture;
  18734. })(BABYLON.RenderTargetTexture);
  18735. BABYLON.RefractionTexture = RefractionTexture;
  18736. })(BABYLON || (BABYLON = {}));
  18737. var BABYLON;
  18738. (function (BABYLON) {
  18739. var DynamicTexture = (function (_super) {
  18740. __extends(DynamicTexture, _super);
  18741. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18743. _super.call(this, null, scene, !generateMipMaps);
  18744. this.name = name;
  18745. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18746. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18747. this._generateMipMaps = generateMipMaps;
  18748. if (options.getContext) {
  18749. this._canvas = options;
  18750. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18751. }
  18752. else {
  18753. this._canvas = document.createElement("canvas");
  18754. if (options.width) {
  18755. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18756. }
  18757. else {
  18758. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18759. }
  18760. }
  18761. var textureSize = this.getSize();
  18762. this._canvas.width = textureSize.width;
  18763. this._canvas.height = textureSize.height;
  18764. this._context = this._canvas.getContext("2d");
  18765. }
  18766. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18767. get: function () {
  18768. return true;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. DynamicTexture.prototype.scale = function (ratio) {
  18774. var textureSize = this.getSize();
  18775. textureSize.width *= ratio;
  18776. textureSize.height *= ratio;
  18777. this._canvas.width = textureSize.width;
  18778. this._canvas.height = textureSize.height;
  18779. this.releaseInternalTexture();
  18780. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18781. };
  18782. DynamicTexture.prototype.getContext = function () {
  18783. return this._context;
  18784. };
  18785. DynamicTexture.prototype.clear = function () {
  18786. var size = this.getSize();
  18787. this._context.fillRect(0, 0, size.width, size.height);
  18788. };
  18789. DynamicTexture.prototype.update = function (invertY) {
  18790. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18791. };
  18792. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18793. if (update === void 0) { update = true; }
  18794. var size = this.getSize();
  18795. if (clearColor) {
  18796. this._context.fillStyle = clearColor;
  18797. this._context.fillRect(0, 0, size.width, size.height);
  18798. }
  18799. this._context.font = font;
  18800. if (x === null) {
  18801. var textSize = this._context.measureText(text);
  18802. x = (size.width - textSize.width) / 2;
  18803. }
  18804. this._context.fillStyle = color;
  18805. this._context.fillText(text, x, y);
  18806. if (update) {
  18807. this.update(invertY);
  18808. }
  18809. };
  18810. DynamicTexture.prototype.clone = function () {
  18811. var textureSize = this.getSize();
  18812. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18813. // Base texture
  18814. newTexture.hasAlpha = this.hasAlpha;
  18815. newTexture.level = this.level;
  18816. // Dynamic Texture
  18817. newTexture.wrapU = this.wrapU;
  18818. newTexture.wrapV = this.wrapV;
  18819. return newTexture;
  18820. };
  18821. return DynamicTexture;
  18822. })(BABYLON.Texture);
  18823. BABYLON.DynamicTexture = DynamicTexture;
  18824. })(BABYLON || (BABYLON = {}));
  18825. var BABYLON;
  18826. (function (BABYLON) {
  18827. var VideoTexture = (function (_super) {
  18828. __extends(VideoTexture, _super);
  18829. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18830. var _this = this;
  18831. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18832. if (invertY === void 0) { invertY = false; }
  18833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18834. _super.call(this, null, scene, !generateMipMaps, invertY);
  18835. this._autoLaunch = true;
  18836. this.name = name;
  18837. this.video = document.createElement("video");
  18838. this.video.autoplay = false;
  18839. this.video.loop = true;
  18840. this.video.addEventListener("canplaythrough", function () {
  18841. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18842. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18843. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18844. }
  18845. else {
  18846. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18847. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18848. generateMipMaps = false;
  18849. }
  18850. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18851. _this._texture.isReady = true;
  18852. });
  18853. urls.forEach(function (url) {
  18854. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18855. var source = document.createElement("source");
  18856. source.src = url;
  18857. _this.video.appendChild(source);
  18858. });
  18859. this._lastUpdate = BABYLON.Tools.Now;
  18860. }
  18861. VideoTexture.prototype.update = function () {
  18862. if (this._autoLaunch) {
  18863. this._autoLaunch = false;
  18864. this.video.play();
  18865. }
  18866. var now = BABYLON.Tools.Now;
  18867. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18868. return false;
  18869. }
  18870. this._lastUpdate = now;
  18871. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18872. return true;
  18873. };
  18874. return VideoTexture;
  18875. })(BABYLON.Texture);
  18876. BABYLON.VideoTexture = VideoTexture;
  18877. })(BABYLON || (BABYLON = {}));
  18878. var BABYLON;
  18879. (function (BABYLON) {
  18880. var CustomProceduralTexture = (function (_super) {
  18881. __extends(CustomProceduralTexture, _super);
  18882. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18883. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18884. this._animate = true;
  18885. this._time = 0;
  18886. this._texturePath = texturePath;
  18887. //Try to load json
  18888. this.loadJson(texturePath);
  18889. this.refreshRate = 1;
  18890. }
  18891. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18892. var _this = this;
  18893. var that = this;
  18894. function noConfigFile() {
  18895. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18896. try {
  18897. that.setFragment(that._texturePath);
  18898. }
  18899. catch (ex) {
  18900. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18901. }
  18902. }
  18903. var configFileUrl = jsonUrl + "/config.json";
  18904. var xhr = new XMLHttpRequest();
  18905. xhr.open("GET", configFileUrl, true);
  18906. xhr.addEventListener("load", function () {
  18907. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18908. try {
  18909. _this._config = JSON.parse(xhr.response);
  18910. _this.updateShaderUniforms();
  18911. _this.updateTextures();
  18912. _this.setFragment(_this._texturePath + "/custom");
  18913. _this._animate = _this._config.animate;
  18914. _this.refreshRate = _this._config.refreshrate;
  18915. }
  18916. catch (ex) {
  18917. noConfigFile();
  18918. }
  18919. }
  18920. else {
  18921. noConfigFile();
  18922. }
  18923. }, false);
  18924. xhr.addEventListener("error", function () {
  18925. noConfigFile();
  18926. }, false);
  18927. try {
  18928. xhr.send();
  18929. }
  18930. catch (ex) {
  18931. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18932. }
  18933. };
  18934. CustomProceduralTexture.prototype.isReady = function () {
  18935. if (!_super.prototype.isReady.call(this)) {
  18936. return false;
  18937. }
  18938. for (var name in this._textures) {
  18939. var texture = this._textures[name];
  18940. if (!texture.isReady()) {
  18941. return false;
  18942. }
  18943. }
  18944. return true;
  18945. };
  18946. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18947. if (this._animate) {
  18948. this._time += this.getScene().getAnimationRatio() * 0.03;
  18949. this.updateShaderUniforms();
  18950. }
  18951. _super.prototype.render.call(this, useCameraPostProcess);
  18952. };
  18953. CustomProceduralTexture.prototype.updateTextures = function () {
  18954. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18955. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18956. }
  18957. };
  18958. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18959. if (this._config) {
  18960. for (var j = 0; j < this._config.uniforms.length; j++) {
  18961. var uniform = this._config.uniforms[j];
  18962. switch (uniform.type) {
  18963. case "float":
  18964. this.setFloat(uniform.name, uniform.value);
  18965. break;
  18966. case "color3":
  18967. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18968. break;
  18969. case "color4":
  18970. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18971. break;
  18972. case "vector2":
  18973. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18974. break;
  18975. case "vector3":
  18976. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18977. break;
  18978. }
  18979. }
  18980. }
  18981. this.setFloat("time", this._time);
  18982. };
  18983. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18984. get: function () {
  18985. return this._animate;
  18986. },
  18987. set: function (value) {
  18988. this._animate = value;
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. return CustomProceduralTexture;
  18994. })(BABYLON.ProceduralTexture);
  18995. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18996. })(BABYLON || (BABYLON = {}));
  18997. var BABYLON;
  18998. (function (BABYLON) {
  18999. var EffectFallbacks = (function () {
  19000. function EffectFallbacks() {
  19001. this._defines = {};
  19002. this._currentRank = 32;
  19003. this._maxRank = -1;
  19004. }
  19005. EffectFallbacks.prototype.addFallback = function (rank, define) {
  19006. if (!this._defines[rank]) {
  19007. if (rank < this._currentRank) {
  19008. this._currentRank = rank;
  19009. }
  19010. if (rank > this._maxRank) {
  19011. this._maxRank = rank;
  19012. }
  19013. this._defines[rank] = new Array();
  19014. }
  19015. this._defines[rank].push(define);
  19016. };
  19017. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19018. this._meshRank = rank;
  19019. this._mesh = mesh;
  19020. if (rank > this._maxRank) {
  19021. this._maxRank = rank;
  19022. }
  19023. };
  19024. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19025. get: function () {
  19026. return this._currentRank <= this._maxRank;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19032. var currentFallbacks = this._defines[this._currentRank];
  19033. for (var index = 0; index < currentFallbacks.length; index++) {
  19034. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19035. }
  19036. if (this._mesh && this._currentRank === this._meshRank) {
  19037. this._mesh.computeBonesUsingShaders = false;
  19038. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19039. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19040. }
  19041. this._currentRank++;
  19042. return currentDefines;
  19043. };
  19044. return EffectFallbacks;
  19045. })();
  19046. BABYLON.EffectFallbacks = EffectFallbacks;
  19047. var Effect = (function () {
  19048. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19049. var _this = this;
  19050. this._isReady = false;
  19051. this._compilationError = "";
  19052. this._valueCache = [];
  19053. this._engine = engine;
  19054. this.name = baseName;
  19055. this.defines = defines;
  19056. this._uniformsNames = uniformsNames.concat(samplers);
  19057. this._samplers = samplers;
  19058. this._attributesNames = attributesNames;
  19059. this.onError = onError;
  19060. this.onCompiled = onCompiled;
  19061. var vertexSource;
  19062. var fragmentSource;
  19063. if (baseName.vertexElement) {
  19064. vertexSource = document.getElementById(baseName.vertexElement);
  19065. if (!vertexSource) {
  19066. vertexSource = baseName.vertexElement;
  19067. }
  19068. }
  19069. else {
  19070. vertexSource = baseName.vertex || baseName;
  19071. }
  19072. if (baseName.fragmentElement) {
  19073. fragmentSource = document.getElementById(baseName.fragmentElement);
  19074. if (!fragmentSource) {
  19075. fragmentSource = baseName.fragmentElement;
  19076. }
  19077. }
  19078. else {
  19079. fragmentSource = baseName.fragment || baseName;
  19080. }
  19081. this._loadVertexShader(vertexSource, function (vertexCode) {
  19082. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19083. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19084. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19085. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19086. });
  19087. });
  19088. });
  19089. });
  19090. }
  19091. // Properties
  19092. Effect.prototype.isReady = function () {
  19093. return this._isReady;
  19094. };
  19095. Effect.prototype.getProgram = function () {
  19096. return this._program;
  19097. };
  19098. Effect.prototype.getAttributesNames = function () {
  19099. return this._attributesNames;
  19100. };
  19101. Effect.prototype.getAttributeLocation = function (index) {
  19102. return this._attributes[index];
  19103. };
  19104. Effect.prototype.getAttributeLocationByName = function (name) {
  19105. var index = this._attributesNames.indexOf(name);
  19106. return this._attributes[index];
  19107. };
  19108. Effect.prototype.getAttributesCount = function () {
  19109. return this._attributes.length;
  19110. };
  19111. Effect.prototype.getUniformIndex = function (uniformName) {
  19112. return this._uniformsNames.indexOf(uniformName);
  19113. };
  19114. Effect.prototype.getUniform = function (uniformName) {
  19115. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19116. };
  19117. Effect.prototype.getSamplers = function () {
  19118. return this._samplers;
  19119. };
  19120. Effect.prototype.getCompilationError = function () {
  19121. return this._compilationError;
  19122. };
  19123. // Methods
  19124. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19125. // DOM element ?
  19126. if (vertex instanceof HTMLElement) {
  19127. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19128. callback(vertexCode);
  19129. return;
  19130. }
  19131. // Is in local store ?
  19132. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19133. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19134. return;
  19135. }
  19136. var vertexShaderUrl;
  19137. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19138. vertexShaderUrl = vertex;
  19139. }
  19140. else {
  19141. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19142. }
  19143. // Vertex shader
  19144. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19145. };
  19146. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19147. // DOM element ?
  19148. if (fragment instanceof HTMLElement) {
  19149. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19150. callback(fragmentCode);
  19151. return;
  19152. }
  19153. // Is in local store ?
  19154. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19155. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19156. return;
  19157. }
  19158. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19159. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19160. return;
  19161. }
  19162. var fragmentShaderUrl;
  19163. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19164. fragmentShaderUrl = fragment;
  19165. }
  19166. else {
  19167. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19168. }
  19169. // Fragment shader
  19170. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19171. };
  19172. Effect.prototype._dumpShadersName = function () {
  19173. if (this.name.vertexElement) {
  19174. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19175. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19176. }
  19177. else if (this.name.vertex) {
  19178. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19179. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19180. }
  19181. else {
  19182. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19183. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19184. }
  19185. };
  19186. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19187. var _this = this;
  19188. var regex = /#include<(.+)>(\((.*)\))*/g;
  19189. var match = regex.exec(sourceCode);
  19190. var returnValue = new String(sourceCode);
  19191. while (match != null) {
  19192. var includeFile = match[1];
  19193. if (Effect.IncludesShadersStore[includeFile]) {
  19194. // Substitution
  19195. var includeContent = Effect.IncludesShadersStore[includeFile];
  19196. if (match[2]) {
  19197. var splits = match[2].substr(1, match[2].length - 2).split(",");
  19198. for (var index = 0; index < splits.length; index += 2) {
  19199. var source = new RegExp(splits[index], "g");
  19200. var dest = splits[index + 1];
  19201. includeContent = includeContent.replace(source, dest);
  19202. }
  19203. }
  19204. // Replace
  19205. returnValue = returnValue.replace(match[0], includeContent);
  19206. }
  19207. else {
  19208. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19209. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19210. Effect.IncludesShadersStore[includeFile] = fileContent;
  19211. _this._processIncludes(returnValue, callback);
  19212. });
  19213. return;
  19214. }
  19215. match = regex.exec(sourceCode);
  19216. }
  19217. callback(returnValue);
  19218. };
  19219. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19220. try {
  19221. var engine = this._engine;
  19222. // Precision
  19223. if (!engine.getCaps().highPrecisionShaderSupported) {
  19224. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19225. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19226. }
  19227. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19228. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19229. this._attributes = engine.getAttributes(this._program, attributesNames);
  19230. for (var index = 0; index < this._samplers.length; index++) {
  19231. var sampler = this.getUniform(this._samplers[index]);
  19232. if (sampler == null) {
  19233. this._samplers.splice(index, 1);
  19234. index--;
  19235. }
  19236. }
  19237. engine.bindSamplers(this);
  19238. this._isReady = true;
  19239. if (this.onCompiled) {
  19240. this.onCompiled(this);
  19241. }
  19242. }
  19243. catch (e) {
  19244. // Is it a problem with precision?
  19245. if (e.message.indexOf("highp") !== -1) {
  19246. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19247. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19248. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19249. return;
  19250. }
  19251. // Let's go through fallbacks then
  19252. if (fallbacks && fallbacks.isMoreFallbacks) {
  19253. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19254. this._dumpShadersName();
  19255. defines = fallbacks.reduce(defines);
  19256. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19257. }
  19258. else {
  19259. BABYLON.Tools.Error("Unable to compile effect: ");
  19260. this._dumpShadersName();
  19261. BABYLON.Tools.Error("Defines: " + defines);
  19262. BABYLON.Tools.Error("Error: " + e.message);
  19263. this._compilationError = e.message;
  19264. if (this.onError) {
  19265. this.onError(this, this._compilationError);
  19266. }
  19267. }
  19268. }
  19269. };
  19270. Object.defineProperty(Effect.prototype, "isSupported", {
  19271. get: function () {
  19272. return this._compilationError === "";
  19273. },
  19274. enumerable: true,
  19275. configurable: true
  19276. });
  19277. Effect.prototype._bindTexture = function (channel, texture) {
  19278. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19279. };
  19280. Effect.prototype.setTexture = function (channel, texture) {
  19281. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19282. };
  19283. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19284. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19285. };
  19286. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19287. if (!this._valueCache[uniformName]) {
  19288. this._valueCache[uniformName] = new BABYLON.Matrix();
  19289. }
  19290. for (var index = 0; index < 16; index++) {
  19291. this._valueCache[uniformName].m[index] = matrix.m[index];
  19292. }
  19293. };
  19294. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19295. if (!this._valueCache[uniformName]) {
  19296. this._valueCache[uniformName] = [x, y];
  19297. return;
  19298. }
  19299. this._valueCache[uniformName][0] = x;
  19300. this._valueCache[uniformName][1] = y;
  19301. };
  19302. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19303. if (!this._valueCache[uniformName]) {
  19304. this._valueCache[uniformName] = [x, y, z];
  19305. return;
  19306. }
  19307. this._valueCache[uniformName][0] = x;
  19308. this._valueCache[uniformName][1] = y;
  19309. this._valueCache[uniformName][2] = z;
  19310. };
  19311. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19312. if (!this._valueCache[uniformName]) {
  19313. this._valueCache[uniformName] = [x, y, z, w];
  19314. return;
  19315. }
  19316. this._valueCache[uniformName][0] = x;
  19317. this._valueCache[uniformName][1] = y;
  19318. this._valueCache[uniformName][2] = z;
  19319. this._valueCache[uniformName][3] = w;
  19320. };
  19321. Effect.prototype.setArray = function (uniformName, array) {
  19322. this._engine.setArray(this.getUniform(uniformName), array);
  19323. return this;
  19324. };
  19325. Effect.prototype.setArray2 = function (uniformName, array) {
  19326. this._engine.setArray2(this.getUniform(uniformName), array);
  19327. return this;
  19328. };
  19329. Effect.prototype.setArray3 = function (uniformName, array) {
  19330. this._engine.setArray3(this.getUniform(uniformName), array);
  19331. return this;
  19332. };
  19333. Effect.prototype.setArray4 = function (uniformName, array) {
  19334. this._engine.setArray4(this.getUniform(uniformName), array);
  19335. return this;
  19336. };
  19337. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19338. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19339. return this;
  19340. };
  19341. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19342. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19343. // return this;
  19344. // this._cacheMatrix(uniformName, matrix);
  19345. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19346. return this;
  19347. };
  19348. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19349. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19350. return this;
  19351. };
  19352. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19353. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19354. return this;
  19355. };
  19356. Effect.prototype.setFloat = function (uniformName, value) {
  19357. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19358. return this;
  19359. this._valueCache[uniformName] = value;
  19360. this._engine.setFloat(this.getUniform(uniformName), value);
  19361. return this;
  19362. };
  19363. Effect.prototype.setBool = function (uniformName, bool) {
  19364. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19365. return this;
  19366. this._valueCache[uniformName] = bool;
  19367. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19368. return this;
  19369. };
  19370. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19371. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19372. return this;
  19373. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19374. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19375. return this;
  19376. };
  19377. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19378. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19379. return this;
  19380. this._cacheFloat2(uniformName, x, y);
  19381. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19382. return this;
  19383. };
  19384. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19385. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19386. return this;
  19387. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19388. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19389. return this;
  19390. };
  19391. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19392. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19393. return this;
  19394. this._cacheFloat3(uniformName, x, y, z);
  19395. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19396. return this;
  19397. };
  19398. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19399. 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)
  19400. return this;
  19401. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19402. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19403. return this;
  19404. };
  19405. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19406. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19407. return this;
  19408. this._cacheFloat4(uniformName, x, y, z, w);
  19409. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19410. return this;
  19411. };
  19412. Effect.prototype.setColor3 = function (uniformName, color3) {
  19413. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19414. return this;
  19415. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19416. this._engine.setColor3(this.getUniform(uniformName), color3);
  19417. return this;
  19418. };
  19419. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19420. 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)
  19421. return this;
  19422. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19423. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19424. return this;
  19425. };
  19426. // Statics
  19427. Effect.ShadersStore = {};
  19428. Effect.IncludesShadersStore = {};
  19429. return Effect;
  19430. })();
  19431. BABYLON.Effect = Effect;
  19432. })(BABYLON || (BABYLON = {}));
  19433. var BABYLON;
  19434. (function (BABYLON) {
  19435. var maxSimultaneousLights = 4;
  19436. var MaterialHelper = (function () {
  19437. function MaterialHelper() {
  19438. }
  19439. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19440. var lightIndex = 0;
  19441. var needNormals = false;
  19442. for (var index = 0; index < scene.lights.length; index++) {
  19443. var light = scene.lights[index];
  19444. if (!light.isEnabled()) {
  19445. continue;
  19446. }
  19447. // Excluded check
  19448. if (light._excludedMeshesIds.length > 0) {
  19449. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19450. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19451. if (excludedMesh) {
  19452. light.excludedMeshes.push(excludedMesh);
  19453. }
  19454. }
  19455. light._excludedMeshesIds = [];
  19456. }
  19457. // Included check
  19458. if (light._includedOnlyMeshesIds.length > 0) {
  19459. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19460. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19461. if (includedOnlyMesh) {
  19462. light.includedOnlyMeshes.push(includedOnlyMesh);
  19463. }
  19464. }
  19465. light._includedOnlyMeshesIds = [];
  19466. }
  19467. if (!light.canAffectMesh(mesh)) {
  19468. continue;
  19469. }
  19470. needNormals = true;
  19471. defines["LIGHT" + lightIndex] = true;
  19472. var type;
  19473. if (light instanceof BABYLON.SpotLight) {
  19474. type = "SPOTLIGHT" + lightIndex;
  19475. }
  19476. else if (light instanceof BABYLON.HemisphericLight) {
  19477. type = "HEMILIGHT" + lightIndex;
  19478. }
  19479. else if (light instanceof BABYLON.PointLight) {
  19480. type = "POINTLIGHT" + lightIndex;
  19481. }
  19482. else {
  19483. type = "DIRLIGHT" + lightIndex;
  19484. }
  19485. defines[type] = true;
  19486. // Specular
  19487. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19488. defines["SPECULARTERM"] = true;
  19489. }
  19490. // Shadows
  19491. if (scene.shadowsEnabled) {
  19492. var shadowGenerator = light.getShadowGenerator();
  19493. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19494. defines["SHADOW" + lightIndex] = true;
  19495. defines["SHADOWS"] = true;
  19496. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19497. defines["SHADOWVSM" + lightIndex] = true;
  19498. }
  19499. if (shadowGenerator.usePoissonSampling) {
  19500. defines["SHADOWPCF" + lightIndex] = true;
  19501. }
  19502. }
  19503. }
  19504. lightIndex++;
  19505. if (lightIndex === maxSimultaneousLights)
  19506. break;
  19507. }
  19508. return needNormals;
  19509. };
  19510. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19511. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19512. if (!defines["LIGHT" + lightIndex]) {
  19513. continue;
  19514. }
  19515. if (lightIndex > 0) {
  19516. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19517. }
  19518. if (defines["SHADOW" + lightIndex]) {
  19519. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19520. }
  19521. if (defines["SHADOWPCF" + lightIndex]) {
  19522. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19523. }
  19524. if (defines["SHADOWVSM" + lightIndex]) {
  19525. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19526. }
  19527. }
  19528. };
  19529. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19530. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19531. fallbacks.addCPUSkinningFallback(0, mesh);
  19532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19534. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19535. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19536. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19537. }
  19538. }
  19539. };
  19540. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19541. if (defines["INSTANCES"]) {
  19542. attribs.push("world0");
  19543. attribs.push("world1");
  19544. attribs.push("world2");
  19545. attribs.push("world3");
  19546. }
  19547. };
  19548. // Bindings
  19549. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19550. var shadowGenerator = light.getShadowGenerator();
  19551. if (mesh.receiveShadows && shadowGenerator) {
  19552. if (!light.needCube()) {
  19553. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19554. }
  19555. else {
  19556. if (!depthValuesAlreadySet) {
  19557. depthValuesAlreadySet = true;
  19558. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19559. }
  19560. }
  19561. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19562. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19563. }
  19564. return depthValuesAlreadySet;
  19565. };
  19566. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19567. if (light instanceof BABYLON.PointLight) {
  19568. // Point Light
  19569. light.transferToEffect(effect, "vLightData" + lightIndex);
  19570. }
  19571. else if (light instanceof BABYLON.DirectionalLight) {
  19572. // Directional Light
  19573. light.transferToEffect(effect, "vLightData" + lightIndex);
  19574. }
  19575. else if (light instanceof BABYLON.SpotLight) {
  19576. // Spot Light
  19577. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19578. }
  19579. else if (light instanceof BABYLON.HemisphericLight) {
  19580. // Hemispheric Light
  19581. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19582. }
  19583. };
  19584. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19585. var lightIndex = 0;
  19586. var depthValuesAlreadySet = false;
  19587. for (var index = 0; index < scene.lights.length; index++) {
  19588. var light = scene.lights[index];
  19589. if (!light.isEnabled()) {
  19590. continue;
  19591. }
  19592. if (!light.canAffectMesh(mesh)) {
  19593. continue;
  19594. }
  19595. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19596. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19597. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19598. if (defines["SPECULARTERM"]) {
  19599. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19600. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19601. }
  19602. // Shadows
  19603. if (scene.shadowsEnabled) {
  19604. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19605. }
  19606. lightIndex++;
  19607. if (lightIndex === maxSimultaneousLights)
  19608. break;
  19609. }
  19610. };
  19611. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19612. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19613. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19614. effect.setColor3("vFogColor", scene.fogColor);
  19615. }
  19616. };
  19617. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19618. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19619. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19620. }
  19621. };
  19622. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19623. if (defines["LOGARITHMICDEPTH"]) {
  19624. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19625. }
  19626. };
  19627. MaterialHelper.BindClipPlane = function (effect, scene) {
  19628. if (scene.clipPlane) {
  19629. var clipPlane = scene.clipPlane;
  19630. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19631. }
  19632. };
  19633. return MaterialHelper;
  19634. })();
  19635. BABYLON.MaterialHelper = MaterialHelper;
  19636. })(BABYLON || (BABYLON = {}));
  19637. var BABYLON;
  19638. (function (BABYLON) {
  19639. var FresnelParameters = (function () {
  19640. function FresnelParameters() {
  19641. this.isEnabled = true;
  19642. this.leftColor = BABYLON.Color3.White();
  19643. this.rightColor = BABYLON.Color3.Black();
  19644. this.bias = 0;
  19645. this.power = 1;
  19646. }
  19647. FresnelParameters.prototype.clone = function () {
  19648. var newFresnelParameters = new FresnelParameters();
  19649. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19650. return new FresnelParameters;
  19651. };
  19652. FresnelParameters.prototype.serialize = function () {
  19653. var serializationObject = {};
  19654. serializationObject.isEnabled = this.isEnabled;
  19655. serializationObject.leftColor = this.leftColor;
  19656. serializationObject.rightColor = this.rightColor;
  19657. serializationObject.bias = this.bias;
  19658. serializationObject.power = this.power;
  19659. return serializationObject;
  19660. };
  19661. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19662. var fresnelParameters = new FresnelParameters();
  19663. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19664. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19665. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19666. fresnelParameters.bias = parsedFresnelParameters.bias;
  19667. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19668. return fresnelParameters;
  19669. };
  19670. return FresnelParameters;
  19671. })();
  19672. BABYLON.FresnelParameters = FresnelParameters;
  19673. })(BABYLON || (BABYLON = {}));
  19674. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19675. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19676. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19677. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19678. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19679. };
  19680. var BABYLON;
  19681. (function (BABYLON) {
  19682. var MaterialDefines = (function () {
  19683. function MaterialDefines() {
  19684. }
  19685. MaterialDefines.prototype.isEqual = function (other) {
  19686. for (var index = 0; index < this._keys.length; index++) {
  19687. var prop = this._keys[index];
  19688. if (this[prop] !== other[prop]) {
  19689. return false;
  19690. }
  19691. }
  19692. return true;
  19693. };
  19694. MaterialDefines.prototype.cloneTo = function (other) {
  19695. for (var index = 0; index < this._keys.length; index++) {
  19696. var prop = this._keys[index];
  19697. other[prop] = this[prop];
  19698. }
  19699. };
  19700. MaterialDefines.prototype.reset = function () {
  19701. for (var index = 0; index < this._keys.length; index++) {
  19702. var prop = this._keys[index];
  19703. if (typeof (this[prop]) === "number") {
  19704. this[prop] = 0;
  19705. }
  19706. else {
  19707. this[prop] = false;
  19708. }
  19709. }
  19710. };
  19711. MaterialDefines.prototype.toString = function () {
  19712. var result = "";
  19713. for (var index = 0; index < this._keys.length; index++) {
  19714. var prop = this._keys[index];
  19715. if (typeof (this[prop]) === "number") {
  19716. result += "#define " + prop + " " + this[prop] + "\n";
  19717. }
  19718. else if (this[prop]) {
  19719. result += "#define " + prop + "\n";
  19720. }
  19721. }
  19722. return result;
  19723. };
  19724. return MaterialDefines;
  19725. })();
  19726. BABYLON.MaterialDefines = MaterialDefines;
  19727. var Material = (function () {
  19728. function Material(name, scene, doNotAdd) {
  19729. this.name = name;
  19730. this.checkReadyOnEveryCall = false;
  19731. this.checkReadyOnlyOnce = false;
  19732. this.state = "";
  19733. this.alpha = 1.0;
  19734. this.backFaceCulling = true;
  19735. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19736. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19737. this.disableDepthWrite = false;
  19738. this.fogEnabled = true;
  19739. this.pointSize = 1.0;
  19740. this.zOffset = 0;
  19741. this._wasPreviouslyReady = false;
  19742. this._fillMode = Material.TriangleFillMode;
  19743. this.id = name;
  19744. this._scene = scene;
  19745. if (!doNotAdd) {
  19746. scene.materials.push(this);
  19747. }
  19748. }
  19749. Object.defineProperty(Material, "TriangleFillMode", {
  19750. get: function () {
  19751. return Material._TriangleFillMode;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(Material, "WireFrameFillMode", {
  19757. get: function () {
  19758. return Material._WireFrameFillMode;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Material, "PointFillMode", {
  19764. get: function () {
  19765. return Material._PointFillMode;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19771. get: function () {
  19772. return Material._ClockWiseSideOrientation;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19778. get: function () {
  19779. return Material._CounterClockWiseSideOrientation;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(Material.prototype, "wireframe", {
  19785. get: function () {
  19786. return this._fillMode === Material.WireFrameFillMode;
  19787. },
  19788. set: function (value) {
  19789. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Material.prototype, "pointsCloud", {
  19795. get: function () {
  19796. return this._fillMode === Material.PointFillMode;
  19797. },
  19798. set: function (value) {
  19799. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Material.prototype, "fillMode", {
  19805. get: function () {
  19806. return this._fillMode;
  19807. },
  19808. set: function (value) {
  19809. this._fillMode = value;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(Material.prototype, "isFrozen", {
  19815. get: function () {
  19816. return this.checkReadyOnlyOnce;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Material.prototype.freeze = function () {
  19822. this.checkReadyOnlyOnce = true;
  19823. };
  19824. Material.prototype.unfreeze = function () {
  19825. this.checkReadyOnlyOnce = false;
  19826. };
  19827. Material.prototype.isReady = function (mesh, useInstances) {
  19828. return true;
  19829. };
  19830. Material.prototype.getEffect = function () {
  19831. return this._effect;
  19832. };
  19833. Material.prototype.getScene = function () {
  19834. return this._scene;
  19835. };
  19836. Material.prototype.needAlphaBlending = function () {
  19837. return (this.alpha < 1.0);
  19838. };
  19839. Material.prototype.needAlphaTesting = function () {
  19840. return false;
  19841. };
  19842. Material.prototype.getAlphaTestTexture = function () {
  19843. return null;
  19844. };
  19845. Material.prototype.trackCreation = function (onCompiled, onError) {
  19846. };
  19847. Material.prototype.markDirty = function () {
  19848. this._wasPreviouslyReady = false;
  19849. };
  19850. Material.prototype._preBind = function () {
  19851. var engine = this._scene.getEngine();
  19852. engine.enableEffect(this._effect);
  19853. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19854. };
  19855. Material.prototype.bind = function (world, mesh) {
  19856. this._scene._cachedMaterial = this;
  19857. if (this.onBind) {
  19858. this.onBind(this, mesh);
  19859. }
  19860. if (this.disableDepthWrite) {
  19861. var engine = this._scene.getEngine();
  19862. this._cachedDepthWriteState = engine.getDepthWrite();
  19863. engine.setDepthWrite(false);
  19864. }
  19865. };
  19866. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19867. };
  19868. Material.prototype.unbind = function () {
  19869. if (this.disableDepthWrite) {
  19870. var engine = this._scene.getEngine();
  19871. engine.setDepthWrite(this._cachedDepthWriteState);
  19872. }
  19873. };
  19874. Material.prototype.clone = function (name) {
  19875. return null;
  19876. };
  19877. Material.prototype.getBindedMeshes = function () {
  19878. var result = new Array();
  19879. for (var index = 0; index < this._scene.meshes.length; index++) {
  19880. var mesh = this._scene.meshes[index];
  19881. if (mesh.material === this) {
  19882. result.push(mesh);
  19883. }
  19884. }
  19885. return result;
  19886. };
  19887. Material.prototype.dispose = function (forceDisposeEffect) {
  19888. // Animations
  19889. this.getScene().stopAnimation(this);
  19890. // Remove from scene
  19891. var index = this._scene.materials.indexOf(this);
  19892. if (index >= 0) {
  19893. this._scene.materials.splice(index, 1);
  19894. }
  19895. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19896. if (forceDisposeEffect && this._effect) {
  19897. this._scene.getEngine()._releaseEffect(this._effect);
  19898. this._effect = null;
  19899. }
  19900. // Remove from meshes
  19901. for (index = 0; index < this._scene.meshes.length; index++) {
  19902. var mesh = this._scene.meshes[index];
  19903. if (mesh.material === this) {
  19904. mesh.material = null;
  19905. }
  19906. }
  19907. // Callback
  19908. if (this.onDispose) {
  19909. this.onDispose();
  19910. }
  19911. };
  19912. Material.prototype.serialize = function () {
  19913. return BABYLON.SerializationHelper.Serialize(this);
  19914. };
  19915. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19916. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19917. multiMaterial.id = parsedMultiMaterial.id;
  19918. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19919. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19920. var subMatId = parsedMultiMaterial.materials[matIndex];
  19921. if (subMatId) {
  19922. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19923. }
  19924. else {
  19925. multiMaterial.subMaterials.push(null);
  19926. }
  19927. }
  19928. return multiMaterial;
  19929. };
  19930. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19931. if (!parsedMaterial.customType) {
  19932. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19933. }
  19934. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19935. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19936. ;
  19937. };
  19938. Material._TriangleFillMode = 0;
  19939. Material._WireFrameFillMode = 1;
  19940. Material._PointFillMode = 2;
  19941. Material._ClockWiseSideOrientation = 0;
  19942. Material._CounterClockWiseSideOrientation = 1;
  19943. __decorate([
  19944. BABYLON.serialize()
  19945. ], Material.prototype, "id", void 0);
  19946. __decorate([
  19947. BABYLON.serialize()
  19948. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19949. __decorate([
  19950. BABYLON.serialize()
  19951. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19952. __decorate([
  19953. BABYLON.serialize()
  19954. ], Material.prototype, "state", void 0);
  19955. __decorate([
  19956. BABYLON.serialize()
  19957. ], Material.prototype, "alpha", void 0);
  19958. __decorate([
  19959. BABYLON.serialize()
  19960. ], Material.prototype, "backFaceCulling", void 0);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Material.prototype, "sideOrientation", void 0);
  19964. __decorate([
  19965. BABYLON.serialize()
  19966. ], Material.prototype, "alphaMode", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Material.prototype, "disableDepthWrite", void 0);
  19970. __decorate([
  19971. BABYLON.serialize()
  19972. ], Material.prototype, "fogEnabled", void 0);
  19973. __decorate([
  19974. BABYLON.serialize()
  19975. ], Material.prototype, "pointSize", void 0);
  19976. __decorate([
  19977. BABYLON.serialize()
  19978. ], Material.prototype, "zOffset", void 0);
  19979. __decorate([
  19980. BABYLON.serialize()
  19981. ], Material.prototype, "wireframe", null);
  19982. __decorate([
  19983. BABYLON.serialize()
  19984. ], Material.prototype, "pointsCloud", null);
  19985. __decorate([
  19986. BABYLON.serialize()
  19987. ], Material.prototype, "fillMode", null);
  19988. return Material;
  19989. })();
  19990. BABYLON.Material = Material;
  19991. })(BABYLON || (BABYLON = {}));
  19992. var BABYLON;
  19993. (function (BABYLON) {
  19994. var StandardMaterialDefines = (function (_super) {
  19995. __extends(StandardMaterialDefines, _super);
  19996. function StandardMaterialDefines() {
  19997. _super.call(this);
  19998. this.DIFFUSE = false;
  19999. this.AMBIENT = false;
  20000. this.OPACITY = false;
  20001. this.OPACITYRGB = false;
  20002. this.REFLECTION = false;
  20003. this.EMISSIVE = false;
  20004. this.SPECULAR = false;
  20005. this.BUMP = false;
  20006. this.SPECULAROVERALPHA = false;
  20007. this.CLIPPLANE = false;
  20008. this.ALPHATEST = false;
  20009. this.ALPHAFROMDIFFUSE = false;
  20010. this.POINTSIZE = false;
  20011. this.FOG = false;
  20012. this.LIGHT0 = false;
  20013. this.LIGHT1 = false;
  20014. this.LIGHT2 = false;
  20015. this.LIGHT3 = false;
  20016. this.SPOTLIGHT0 = false;
  20017. this.SPOTLIGHT1 = false;
  20018. this.SPOTLIGHT2 = false;
  20019. this.SPOTLIGHT3 = false;
  20020. this.HEMILIGHT0 = false;
  20021. this.HEMILIGHT1 = false;
  20022. this.HEMILIGHT2 = false;
  20023. this.HEMILIGHT3 = false;
  20024. this.POINTLIGHT0 = false;
  20025. this.POINTLIGHT1 = false;
  20026. this.POINTLIGHT2 = false;
  20027. this.POINTLIGHT3 = false;
  20028. this.DIRLIGHT0 = false;
  20029. this.DIRLIGHT1 = false;
  20030. this.DIRLIGHT2 = false;
  20031. this.DIRLIGHT3 = false;
  20032. this.SPECULARTERM = false;
  20033. this.SHADOW0 = false;
  20034. this.SHADOW1 = false;
  20035. this.SHADOW2 = false;
  20036. this.SHADOW3 = false;
  20037. this.SHADOWS = false;
  20038. this.SHADOWVSM0 = false;
  20039. this.SHADOWVSM1 = false;
  20040. this.SHADOWVSM2 = false;
  20041. this.SHADOWVSM3 = false;
  20042. this.SHADOWPCF0 = false;
  20043. this.SHADOWPCF1 = false;
  20044. this.SHADOWPCF2 = false;
  20045. this.SHADOWPCF3 = false;
  20046. this.DIFFUSEFRESNEL = false;
  20047. this.OPACITYFRESNEL = false;
  20048. this.REFLECTIONFRESNEL = false;
  20049. this.REFRACTIONFRESNEL = false;
  20050. this.EMISSIVEFRESNEL = false;
  20051. this.FRESNEL = false;
  20052. this.NORMAL = false;
  20053. this.UV1 = false;
  20054. this.UV2 = false;
  20055. this.VERTEXCOLOR = false;
  20056. this.VERTEXALPHA = false;
  20057. this.NUM_BONE_INFLUENCERS = 0;
  20058. this.BonesPerMesh = 0;
  20059. this.INSTANCES = false;
  20060. this.GLOSSINESS = false;
  20061. this.ROUGHNESS = false;
  20062. this.EMISSIVEASILLUMINATION = false;
  20063. this.LINKEMISSIVEWITHDIFFUSE = false;
  20064. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20065. this.LIGHTMAP = false;
  20066. this.USELIGHTMAPASSHADOWMAP = false;
  20067. this.REFLECTIONMAP_3D = false;
  20068. this.REFLECTIONMAP_SPHERICAL = false;
  20069. this.REFLECTIONMAP_PLANAR = false;
  20070. this.REFLECTIONMAP_CUBIC = false;
  20071. this.REFLECTIONMAP_PROJECTION = false;
  20072. this.REFLECTIONMAP_SKYBOX = false;
  20073. this.REFLECTIONMAP_EXPLICIT = false;
  20074. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20075. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20076. this.INVERTCUBICMAP = false;
  20077. this.LOGARITHMICDEPTH = false;
  20078. this.REFRACTION = false;
  20079. this.REFRACTIONMAP_3D = false;
  20080. this.REFLECTIONOVERALPHA = false;
  20081. this._keys = Object.keys(this);
  20082. }
  20083. return StandardMaterialDefines;
  20084. })(BABYLON.MaterialDefines);
  20085. var StandardMaterial = (function (_super) {
  20086. __extends(StandardMaterial, _super);
  20087. function StandardMaterial(name, scene) {
  20088. var _this = this;
  20089. _super.call(this, name, scene);
  20090. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20091. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20092. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20093. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20094. this.specularPower = 64;
  20095. this.useAlphaFromDiffuseTexture = false;
  20096. this.useEmissiveAsIllumination = false;
  20097. this.linkEmissiveWithDiffuse = false;
  20098. this.useReflectionFresnelFromSpecular = false;
  20099. this.useSpecularOverAlpha = false;
  20100. this.useReflectionOverAlpha = false;
  20101. this.disableLighting = false;
  20102. this.roughness = 0;
  20103. this.indexOfRefraction = 0.98;
  20104. this.invertRefractionY = true;
  20105. this.useLightmapAsShadowmap = false;
  20106. this.useGlossinessFromSpecularMapAlpha = false;
  20107. this._renderTargets = new BABYLON.SmartArray(16);
  20108. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20109. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20110. this._defines = new StandardMaterialDefines();
  20111. this._cachedDefines = new StandardMaterialDefines();
  20112. this._cachedDefines.BonesPerMesh = -1;
  20113. this.getRenderTargetTextures = function () {
  20114. _this._renderTargets.reset();
  20115. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20116. _this._renderTargets.push(_this.reflectionTexture);
  20117. }
  20118. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20119. _this._renderTargets.push(_this.refractionTexture);
  20120. }
  20121. return _this._renderTargets;
  20122. };
  20123. }
  20124. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20125. get: function () {
  20126. return this._useLogarithmicDepth;
  20127. },
  20128. set: function (value) {
  20129. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. StandardMaterial.prototype.needAlphaBlending = function () {
  20135. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20136. };
  20137. StandardMaterial.prototype.needAlphaTesting = function () {
  20138. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20139. };
  20140. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20141. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20142. };
  20143. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20144. return this.diffuseTexture;
  20145. };
  20146. // Methods
  20147. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20148. if (!mesh) {
  20149. return true;
  20150. }
  20151. if (this._defines.INSTANCES !== useInstances) {
  20152. return false;
  20153. }
  20154. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20155. return true;
  20156. }
  20157. return false;
  20158. };
  20159. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20160. if (this.isFrozen) {
  20161. if (this._wasPreviouslyReady) {
  20162. return true;
  20163. }
  20164. }
  20165. var scene = this.getScene();
  20166. if (!this.checkReadyOnEveryCall) {
  20167. if (this._renderId === scene.getRenderId()) {
  20168. if (this._checkCache(scene, mesh, useInstances)) {
  20169. return true;
  20170. }
  20171. }
  20172. }
  20173. var engine = scene.getEngine();
  20174. var needNormals = false;
  20175. var needUVs = false;
  20176. this._defines.reset();
  20177. // Textures
  20178. if (scene.texturesEnabled) {
  20179. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20180. if (!this.diffuseTexture.isReady()) {
  20181. return false;
  20182. }
  20183. else {
  20184. needUVs = true;
  20185. this._defines.DIFFUSE = true;
  20186. }
  20187. }
  20188. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20189. if (!this.ambientTexture.isReady()) {
  20190. return false;
  20191. }
  20192. else {
  20193. needUVs = true;
  20194. this._defines.AMBIENT = true;
  20195. }
  20196. }
  20197. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20198. if (!this.opacityTexture.isReady()) {
  20199. return false;
  20200. }
  20201. else {
  20202. needUVs = true;
  20203. this._defines.OPACITY = true;
  20204. if (this.opacityTexture.getAlphaFromRGB) {
  20205. this._defines.OPACITYRGB = true;
  20206. }
  20207. }
  20208. }
  20209. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20210. if (!this.reflectionTexture.isReady()) {
  20211. return false;
  20212. }
  20213. else {
  20214. needNormals = true;
  20215. this._defines.REFLECTION = true;
  20216. if (this.roughness > 0) {
  20217. this._defines.ROUGHNESS = true;
  20218. }
  20219. if (this.useReflectionOverAlpha) {
  20220. this._defines.REFLECTIONOVERALPHA = true;
  20221. }
  20222. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20223. this._defines.INVERTCUBICMAP = true;
  20224. }
  20225. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20226. switch (this.reflectionTexture.coordinatesMode) {
  20227. case BABYLON.Texture.CUBIC_MODE:
  20228. case BABYLON.Texture.INVCUBIC_MODE:
  20229. this._defines.REFLECTIONMAP_CUBIC = true;
  20230. break;
  20231. case BABYLON.Texture.EXPLICIT_MODE:
  20232. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20233. break;
  20234. case BABYLON.Texture.PLANAR_MODE:
  20235. this._defines.REFLECTIONMAP_PLANAR = true;
  20236. break;
  20237. case BABYLON.Texture.PROJECTION_MODE:
  20238. this._defines.REFLECTIONMAP_PROJECTION = true;
  20239. break;
  20240. case BABYLON.Texture.SKYBOX_MODE:
  20241. this._defines.REFLECTIONMAP_SKYBOX = true;
  20242. break;
  20243. case BABYLON.Texture.SPHERICAL_MODE:
  20244. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20245. break;
  20246. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20247. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20248. break;
  20249. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20250. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20251. break;
  20252. }
  20253. }
  20254. }
  20255. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20256. if (!this.emissiveTexture.isReady()) {
  20257. return false;
  20258. }
  20259. else {
  20260. needUVs = true;
  20261. this._defines.EMISSIVE = true;
  20262. }
  20263. }
  20264. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20265. if (!this.lightmapTexture.isReady()) {
  20266. return false;
  20267. }
  20268. else {
  20269. needUVs = true;
  20270. this._defines.LIGHTMAP = true;
  20271. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20272. }
  20273. }
  20274. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20275. if (!this.specularTexture.isReady()) {
  20276. return false;
  20277. }
  20278. else {
  20279. needUVs = true;
  20280. this._defines.SPECULAR = true;
  20281. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20282. }
  20283. }
  20284. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20285. if (!this.bumpTexture.isReady()) {
  20286. return false;
  20287. }
  20288. else {
  20289. needUVs = true;
  20290. this._defines.BUMP = true;
  20291. }
  20292. }
  20293. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20294. if (!this.refractionTexture.isReady()) {
  20295. return false;
  20296. }
  20297. else {
  20298. needUVs = true;
  20299. this._defines.REFRACTION = true;
  20300. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20301. }
  20302. }
  20303. }
  20304. // Effect
  20305. if (scene.clipPlane) {
  20306. this._defines.CLIPPLANE = true;
  20307. }
  20308. if (engine.getAlphaTesting()) {
  20309. this._defines.ALPHATEST = true;
  20310. }
  20311. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20312. this._defines.ALPHAFROMDIFFUSE = true;
  20313. }
  20314. if (this.useEmissiveAsIllumination) {
  20315. this._defines.EMISSIVEASILLUMINATION = true;
  20316. }
  20317. if (this.linkEmissiveWithDiffuse) {
  20318. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20319. }
  20320. if (this.useLogarithmicDepth) {
  20321. this._defines.LOGARITHMICDEPTH = true;
  20322. }
  20323. // Point size
  20324. if (this.pointsCloud || scene.forcePointsCloud) {
  20325. this._defines.POINTSIZE = true;
  20326. }
  20327. // Fog
  20328. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20329. this._defines.FOG = true;
  20330. }
  20331. if (scene.lightsEnabled && !this.disableLighting) {
  20332. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20333. }
  20334. if (StandardMaterial.FresnelEnabled) {
  20335. // Fresnel
  20336. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20337. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20338. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20339. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20340. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20341. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20342. this._defines.DIFFUSEFRESNEL = true;
  20343. }
  20344. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20345. this._defines.OPACITYFRESNEL = true;
  20346. }
  20347. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20348. this._defines.REFLECTIONFRESNEL = true;
  20349. if (this.useReflectionFresnelFromSpecular) {
  20350. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20351. }
  20352. }
  20353. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20354. this._defines.REFRACTIONFRESNEL = true;
  20355. }
  20356. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20357. this._defines.EMISSIVEFRESNEL = true;
  20358. }
  20359. needNormals = true;
  20360. this._defines.FRESNEL = true;
  20361. }
  20362. }
  20363. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20364. this._defines.SPECULAROVERALPHA = true;
  20365. }
  20366. // Attribs
  20367. if (mesh) {
  20368. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20369. this._defines.NORMAL = true;
  20370. }
  20371. if (needUVs) {
  20372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20373. this._defines.UV1 = true;
  20374. }
  20375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20376. this._defines.UV2 = true;
  20377. }
  20378. }
  20379. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20380. this._defines.VERTEXCOLOR = true;
  20381. if (mesh.hasVertexAlpha) {
  20382. this._defines.VERTEXALPHA = true;
  20383. }
  20384. }
  20385. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20386. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20387. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20388. }
  20389. // Instances
  20390. if (useInstances) {
  20391. this._defines.INSTANCES = true;
  20392. }
  20393. }
  20394. // Get correct effect
  20395. if (!this._defines.isEqual(this._cachedDefines)) {
  20396. this._defines.cloneTo(this._cachedDefines);
  20397. scene.resetCachedMaterial();
  20398. // Fallbacks
  20399. var fallbacks = new BABYLON.EffectFallbacks();
  20400. if (this._defines.REFLECTION) {
  20401. fallbacks.addFallback(0, "REFLECTION");
  20402. }
  20403. if (this._defines.SPECULAR) {
  20404. fallbacks.addFallback(0, "SPECULAR");
  20405. }
  20406. if (this._defines.BUMP) {
  20407. fallbacks.addFallback(0, "BUMP");
  20408. }
  20409. if (this._defines.SPECULAROVERALPHA) {
  20410. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20411. }
  20412. if (this._defines.FOG) {
  20413. fallbacks.addFallback(1, "FOG");
  20414. }
  20415. if (this._defines.POINTSIZE) {
  20416. fallbacks.addFallback(0, "POINTSIZE");
  20417. }
  20418. if (this._defines.LOGARITHMICDEPTH) {
  20419. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20420. }
  20421. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20422. if (this._defines.SPECULARTERM) {
  20423. fallbacks.addFallback(0, "SPECULARTERM");
  20424. }
  20425. if (this._defines.DIFFUSEFRESNEL) {
  20426. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20427. }
  20428. if (this._defines.OPACITYFRESNEL) {
  20429. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20430. }
  20431. if (this._defines.REFLECTIONFRESNEL) {
  20432. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20433. }
  20434. if (this._defines.EMISSIVEFRESNEL) {
  20435. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20436. }
  20437. if (this._defines.FRESNEL) {
  20438. fallbacks.addFallback(4, "FRESNEL");
  20439. }
  20440. //Attributes
  20441. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20442. if (this._defines.NORMAL) {
  20443. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20444. }
  20445. if (this._defines.UV1) {
  20446. attribs.push(BABYLON.VertexBuffer.UVKind);
  20447. }
  20448. if (this._defines.UV2) {
  20449. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20450. }
  20451. if (this._defines.VERTEXCOLOR) {
  20452. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20453. }
  20454. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20455. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20456. // Legacy browser patch
  20457. var shaderName = "default";
  20458. if (!scene.getEngine().getCaps().standardDerivatives) {
  20459. shaderName = "legacydefault";
  20460. }
  20461. var join = this._defines.toString();
  20462. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20463. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20464. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20465. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20466. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20467. "vFogInfos", "vFogColor", "pointSize",
  20468. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20469. "mBones",
  20470. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20471. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20472. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20473. "logarithmicDepthConstant"
  20474. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20475. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20476. ], join, fallbacks, this.onCompiled, this.onError);
  20477. }
  20478. if (!this._effect.isReady()) {
  20479. return false;
  20480. }
  20481. this._renderId = scene.getRenderId();
  20482. this._wasPreviouslyReady = true;
  20483. if (mesh) {
  20484. if (!mesh._materialDefines) {
  20485. mesh._materialDefines = new StandardMaterialDefines();
  20486. }
  20487. this._defines.cloneTo(mesh._materialDefines);
  20488. }
  20489. return true;
  20490. };
  20491. StandardMaterial.prototype.unbind = function () {
  20492. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20493. this._effect.setTexture("reflection2DSampler", null);
  20494. }
  20495. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20496. this._effect.setTexture("refraction2DSampler", null);
  20497. }
  20498. _super.prototype.unbind.call(this);
  20499. };
  20500. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20501. this._effect.setMatrix("world", world);
  20502. };
  20503. StandardMaterial.prototype.bind = function (world, mesh) {
  20504. var scene = this.getScene();
  20505. // Matrices
  20506. this.bindOnlyWorldMatrix(world);
  20507. // Bones
  20508. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20509. if (scene.getCachedMaterial() !== this) {
  20510. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20511. if (StandardMaterial.FresnelEnabled) {
  20512. // Fresnel
  20513. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20514. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20515. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20516. }
  20517. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20518. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20519. }
  20520. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20521. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20522. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20523. }
  20524. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20525. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20526. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20527. }
  20528. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20529. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20530. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20531. }
  20532. }
  20533. // Textures
  20534. if (scene.texturesEnabled) {
  20535. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20536. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20537. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20538. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20539. }
  20540. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20541. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20542. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20543. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20544. }
  20545. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20546. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20547. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20548. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20549. }
  20550. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20551. if (this.reflectionTexture.isCube) {
  20552. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20553. }
  20554. else {
  20555. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20556. }
  20557. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20558. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20559. }
  20560. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20561. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20562. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20563. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20564. }
  20565. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20566. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20567. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20568. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20569. }
  20570. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20571. this._effect.setTexture("specularSampler", this.specularTexture);
  20572. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20573. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20574. }
  20575. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20576. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20577. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20578. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20579. }
  20580. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20581. var depth = 1.0;
  20582. if (this.refractionTexture.isCube) {
  20583. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20584. }
  20585. else {
  20586. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20587. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20588. if (this.refractionTexture.depth) {
  20589. depth = this.refractionTexture.depth;
  20590. }
  20591. }
  20592. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20593. }
  20594. }
  20595. // Clip plane
  20596. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20597. // Point size
  20598. if (this.pointsCloud) {
  20599. this._effect.setFloat("pointSize", this.pointSize);
  20600. }
  20601. // Colors
  20602. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20603. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20604. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20605. if (this._defines.SPECULARTERM) {
  20606. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20607. }
  20608. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20609. }
  20610. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20611. // Diffuse
  20612. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20613. // Lights
  20614. if (scene.lightsEnabled && !this.disableLighting) {
  20615. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20616. }
  20617. // View
  20618. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20619. this._effect.setMatrix("view", scene.getViewMatrix());
  20620. }
  20621. // Fog
  20622. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20623. // Log. depth
  20624. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20625. }
  20626. _super.prototype.bind.call(this, world, mesh);
  20627. };
  20628. StandardMaterial.prototype.getAnimatables = function () {
  20629. var results = [];
  20630. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20631. results.push(this.diffuseTexture);
  20632. }
  20633. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20634. results.push(this.ambientTexture);
  20635. }
  20636. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20637. results.push(this.opacityTexture);
  20638. }
  20639. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20640. results.push(this.reflectionTexture);
  20641. }
  20642. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20643. results.push(this.emissiveTexture);
  20644. }
  20645. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20646. results.push(this.specularTexture);
  20647. }
  20648. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20649. results.push(this.bumpTexture);
  20650. }
  20651. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20652. results.push(this.lightmapTexture);
  20653. }
  20654. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20655. results.push(this.refractionTexture);
  20656. }
  20657. return results;
  20658. };
  20659. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20660. if (this.diffuseTexture) {
  20661. this.diffuseTexture.dispose();
  20662. }
  20663. if (this.ambientTexture) {
  20664. this.ambientTexture.dispose();
  20665. }
  20666. if (this.opacityTexture) {
  20667. this.opacityTexture.dispose();
  20668. }
  20669. if (this.reflectionTexture) {
  20670. this.reflectionTexture.dispose();
  20671. }
  20672. if (this.emissiveTexture) {
  20673. this.emissiveTexture.dispose();
  20674. }
  20675. if (this.specularTexture) {
  20676. this.specularTexture.dispose();
  20677. }
  20678. if (this.bumpTexture) {
  20679. this.bumpTexture.dispose();
  20680. }
  20681. if (this.lightmapTexture) {
  20682. this.lightmapTexture.dispose();
  20683. }
  20684. if (this.refractionTexture) {
  20685. this.refractionTexture.dispose();
  20686. }
  20687. _super.prototype.dispose.call(this, forceDisposeEffect);
  20688. };
  20689. StandardMaterial.prototype.clone = function (name) {
  20690. var _this = this;
  20691. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20692. };
  20693. StandardMaterial.prototype.serialize = function () {
  20694. return BABYLON.SerializationHelper.Serialize(this);
  20695. };
  20696. // Statics
  20697. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20698. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20699. };
  20700. // Flags used to enable or disable a type of texture for all Standard Materials
  20701. StandardMaterial.DiffuseTextureEnabled = true;
  20702. StandardMaterial.AmbientTextureEnabled = true;
  20703. StandardMaterial.OpacityTextureEnabled = true;
  20704. StandardMaterial.ReflectionTextureEnabled = true;
  20705. StandardMaterial.EmissiveTextureEnabled = true;
  20706. StandardMaterial.SpecularTextureEnabled = true;
  20707. StandardMaterial.BumpTextureEnabled = true;
  20708. StandardMaterial.FresnelEnabled = true;
  20709. StandardMaterial.LightmapTextureEnabled = true;
  20710. StandardMaterial.RefractionTextureEnabled = true;
  20711. __decorate([
  20712. BABYLON.serializeAsTexture()
  20713. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20714. __decorate([
  20715. BABYLON.serializeAsTexture()
  20716. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20717. __decorate([
  20718. BABYLON.serializeAsTexture()
  20719. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20720. __decorate([
  20721. BABYLON.serializeAsTexture()
  20722. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20723. __decorate([
  20724. BABYLON.serializeAsTexture()
  20725. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20726. __decorate([
  20727. BABYLON.serializeAsTexture()
  20728. ], StandardMaterial.prototype, "specularTexture", void 0);
  20729. __decorate([
  20730. BABYLON.serializeAsTexture()
  20731. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20732. __decorate([
  20733. BABYLON.serializeAsTexture()
  20734. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20735. __decorate([
  20736. BABYLON.serializeAsTexture()
  20737. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20738. __decorate([
  20739. BABYLON.serializeAsColor3("ambient")
  20740. ], StandardMaterial.prototype, "ambientColor", void 0);
  20741. __decorate([
  20742. BABYLON.serializeAsColor3("diffuse")
  20743. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20744. __decorate([
  20745. BABYLON.serializeAsColor3("specular")
  20746. ], StandardMaterial.prototype, "specularColor", void 0);
  20747. __decorate([
  20748. BABYLON.serializeAsColor3("emissive")
  20749. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20750. __decorate([
  20751. BABYLON.serialize()
  20752. ], StandardMaterial.prototype, "specularPower", void 0);
  20753. __decorate([
  20754. BABYLON.serialize()
  20755. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20756. __decorate([
  20757. BABYLON.serialize()
  20758. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20759. __decorate([
  20760. BABYLON.serialize()
  20761. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20762. __decorate([
  20763. BABYLON.serialize()
  20764. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20765. __decorate([
  20766. BABYLON.serialize()
  20767. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20768. __decorate([
  20769. BABYLON.serialize()
  20770. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20771. __decorate([
  20772. BABYLON.serialize()
  20773. ], StandardMaterial.prototype, "disableLighting", void 0);
  20774. __decorate([
  20775. BABYLON.serialize()
  20776. ], StandardMaterial.prototype, "roughness", void 0);
  20777. __decorate([
  20778. BABYLON.serialize()
  20779. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20780. __decorate([
  20781. BABYLON.serialize()
  20782. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20783. __decorate([
  20784. BABYLON.serialize()
  20785. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20786. __decorate([
  20787. BABYLON.serializeAsFresnelParameters()
  20788. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20789. __decorate([
  20790. BABYLON.serializeAsFresnelParameters()
  20791. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20792. __decorate([
  20793. BABYLON.serializeAsFresnelParameters()
  20794. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20795. __decorate([
  20796. BABYLON.serializeAsFresnelParameters()
  20797. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20798. __decorate([
  20799. BABYLON.serializeAsFresnelParameters()
  20800. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20801. __decorate([
  20802. BABYLON.serialize()
  20803. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20804. __decorate([
  20805. BABYLON.serialize()
  20806. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20807. return StandardMaterial;
  20808. })(BABYLON.Material);
  20809. BABYLON.StandardMaterial = StandardMaterial;
  20810. })(BABYLON || (BABYLON = {}));
  20811. var BABYLON;
  20812. (function (BABYLON) {
  20813. var MultiMaterial = (function (_super) {
  20814. __extends(MultiMaterial, _super);
  20815. function MultiMaterial(name, scene) {
  20816. _super.call(this, name, scene, true);
  20817. this.subMaterials = new Array();
  20818. scene.multiMaterials.push(this);
  20819. }
  20820. // Properties
  20821. MultiMaterial.prototype.getSubMaterial = function (index) {
  20822. if (index < 0 || index >= this.subMaterials.length) {
  20823. return this.getScene().defaultMaterial;
  20824. }
  20825. return this.subMaterials[index];
  20826. };
  20827. // Methods
  20828. MultiMaterial.prototype.isReady = function (mesh) {
  20829. for (var index = 0; index < this.subMaterials.length; index++) {
  20830. var subMaterial = this.subMaterials[index];
  20831. if (subMaterial) {
  20832. if (!this.subMaterials[index].isReady(mesh)) {
  20833. return false;
  20834. }
  20835. }
  20836. }
  20837. return true;
  20838. };
  20839. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20840. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20841. for (var index = 0; index < this.subMaterials.length; index++) {
  20842. var subMaterial = null;
  20843. if (cloneChildren) {
  20844. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20845. }
  20846. else {
  20847. subMaterial = this.subMaterials[index];
  20848. }
  20849. newMultiMaterial.subMaterials.push(subMaterial);
  20850. }
  20851. return newMultiMaterial;
  20852. };
  20853. MultiMaterial.prototype.serialize = function () {
  20854. var serializationObject = {};
  20855. serializationObject.name = this.name;
  20856. serializationObject.id = this.id;
  20857. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20858. serializationObject.materials = [];
  20859. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20860. var subMat = this.subMaterials[matIndex];
  20861. if (subMat) {
  20862. serializationObject.materials.push(subMat.id);
  20863. }
  20864. else {
  20865. serializationObject.materials.push(null);
  20866. }
  20867. }
  20868. return serializationObject;
  20869. };
  20870. return MultiMaterial;
  20871. })(BABYLON.Material);
  20872. BABYLON.MultiMaterial = MultiMaterial;
  20873. })(BABYLON || (BABYLON = {}));
  20874. var BABYLON;
  20875. (function (BABYLON) {
  20876. var SceneLoader = (function () {
  20877. function SceneLoader() {
  20878. }
  20879. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20880. get: function () {
  20881. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20882. },
  20883. set: function (value) {
  20884. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20885. },
  20886. enumerable: true,
  20887. configurable: true
  20888. });
  20889. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20890. get: function () {
  20891. return SceneLoader._ShowLoadingScreen;
  20892. },
  20893. set: function (value) {
  20894. SceneLoader._ShowLoadingScreen = value;
  20895. },
  20896. enumerable: true,
  20897. configurable: true
  20898. });
  20899. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20900. var dotPosition = sceneFilename.lastIndexOf(".");
  20901. var queryStringPosition = sceneFilename.indexOf("?");
  20902. if (queryStringPosition === -1) {
  20903. queryStringPosition = sceneFilename.length;
  20904. }
  20905. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20906. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20907. var plugin = this._registeredPlugins[index];
  20908. if (plugin.extensions.indexOf(extension) !== -1) {
  20909. return plugin;
  20910. }
  20911. }
  20912. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20913. };
  20914. // Public functions
  20915. SceneLoader.GetPluginForExtension = function (extension) {
  20916. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20917. var plugin = this._registeredPlugins[index];
  20918. if (plugin.extensions.indexOf(extension) !== -1) {
  20919. return plugin;
  20920. }
  20921. }
  20922. return null;
  20923. };
  20924. SceneLoader.RegisterPlugin = function (plugin) {
  20925. plugin.extensions = plugin.extensions.toLowerCase();
  20926. SceneLoader._registeredPlugins.push(plugin);
  20927. };
  20928. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20929. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20930. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20931. return;
  20932. }
  20933. var loadingToken = {};
  20934. scene._addPendingData(loadingToken);
  20935. var manifestChecked = function (success) {
  20936. scene.database = database;
  20937. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20938. var importMeshFromData = function (data) {
  20939. var meshes = [];
  20940. var particleSystems = [];
  20941. var skeletons = [];
  20942. try {
  20943. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20944. if (onerror) {
  20945. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20946. }
  20947. scene._removePendingData(loadingToken);
  20948. return;
  20949. }
  20950. }
  20951. catch (e) {
  20952. if (onerror) {
  20953. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20954. }
  20955. scene._removePendingData(loadingToken);
  20956. return;
  20957. }
  20958. if (onsuccess) {
  20959. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20960. onsuccess(meshes, particleSystems, skeletons);
  20961. scene._removePendingData(loadingToken);
  20962. }
  20963. };
  20964. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20965. // Direct load
  20966. importMeshFromData(sceneFilename.substr(5));
  20967. return;
  20968. }
  20969. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20970. importMeshFromData(data);
  20971. }, progressCallBack, database);
  20972. };
  20973. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  20974. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20975. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20976. }
  20977. else {
  20978. // If the scene is a data stream or offline support is not enabled, it's a direct load
  20979. manifestChecked(true);
  20980. }
  20981. };
  20982. /**
  20983. * Load a scene
  20984. * @param rootUrl a string that defines the root url for scene and resources
  20985. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20986. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20987. */
  20988. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20989. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20990. };
  20991. /**
  20992. * Append a scene
  20993. * @param rootUrl a string that defines the root url for scene and resources
  20994. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20995. * @param scene is the instance of BABYLON.Scene to append to
  20996. */
  20997. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20998. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20999. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21000. return;
  21001. }
  21002. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21003. var database;
  21004. var loadingToken = {};
  21005. scene._addPendingData(loadingToken);
  21006. if (SceneLoader.ShowLoadingScreen) {
  21007. scene.getEngine().displayLoadingUI();
  21008. }
  21009. var loadSceneFromData = function (data) {
  21010. scene.database = database;
  21011. if (!plugin.load(scene, data, rootUrl)) {
  21012. if (onerror) {
  21013. onerror(scene);
  21014. }
  21015. scene._removePendingData(loadingToken);
  21016. scene.getEngine().hideLoadingUI();
  21017. return;
  21018. }
  21019. if (onsuccess) {
  21020. onsuccess(scene);
  21021. }
  21022. scene._removePendingData(loadingToken);
  21023. if (SceneLoader.ShowLoadingScreen) {
  21024. scene.executeWhenReady(function () {
  21025. scene.getEngine().hideLoadingUI();
  21026. });
  21027. }
  21028. };
  21029. var manifestChecked = function (success) {
  21030. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21031. };
  21032. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21033. // Direct load
  21034. loadSceneFromData(sceneFilename.substr(5));
  21035. return;
  21036. }
  21037. if (rootUrl.indexOf("file:") === -1) {
  21038. if (scene.getEngine().enableOfflineSupport) {
  21039. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21040. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21041. }
  21042. else {
  21043. manifestChecked(true);
  21044. }
  21045. }
  21046. else {
  21047. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21048. }
  21049. };
  21050. // Flags
  21051. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21052. SceneLoader._ShowLoadingScreen = true;
  21053. // Members
  21054. SceneLoader._registeredPlugins = new Array();
  21055. return SceneLoader;
  21056. })();
  21057. BABYLON.SceneLoader = SceneLoader;
  21058. ;
  21059. })(BABYLON || (BABYLON = {}));
  21060. var BABYLON;
  21061. (function (BABYLON) {
  21062. var Internals;
  21063. (function (Internals) {
  21064. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21065. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21066. var parsedMaterial = parsedData.materials[index];
  21067. if (parsedMaterial.id === id) {
  21068. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21069. }
  21070. }
  21071. return null;
  21072. };
  21073. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21074. names = (names instanceof Array) ? names : [names];
  21075. for (var i in names) {
  21076. if (mesh.name === names[i]) {
  21077. hierarchyIds.push(mesh.id);
  21078. return true;
  21079. }
  21080. }
  21081. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21082. hierarchyIds.push(mesh.id);
  21083. return true;
  21084. }
  21085. return false;
  21086. };
  21087. BABYLON.SceneLoader.RegisterPlugin({
  21088. extensions: ".babylon",
  21089. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21090. var parsedData = JSON.parse(data);
  21091. var loadedSkeletonsIds = [];
  21092. var loadedMaterialsIds = [];
  21093. var hierarchyIds = [];
  21094. var index;
  21095. var cache;
  21096. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21097. var parsedMesh = parsedData.meshes[index];
  21098. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21099. if (meshesNames instanceof Array) {
  21100. // Remove found mesh name from list.
  21101. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21102. }
  21103. //Geometry?
  21104. if (parsedMesh.geometryId) {
  21105. //does the file contain geometries?
  21106. if (parsedData.geometries) {
  21107. //find the correct geometry and add it to the scene
  21108. var found = false;
  21109. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21110. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21111. return;
  21112. }
  21113. else {
  21114. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21115. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21116. switch (geometryType) {
  21117. case "boxes":
  21118. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21119. break;
  21120. case "spheres":
  21121. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21122. break;
  21123. case "cylinders":
  21124. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21125. break;
  21126. case "toruses":
  21127. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21128. break;
  21129. case "grounds":
  21130. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21131. break;
  21132. case "planes":
  21133. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21134. break;
  21135. case "torusKnots":
  21136. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21137. break;
  21138. case "vertexData":
  21139. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21140. break;
  21141. }
  21142. found = true;
  21143. }
  21144. });
  21145. }
  21146. });
  21147. if (!found) {
  21148. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21149. }
  21150. }
  21151. }
  21152. // Material ?
  21153. if (parsedMesh.materialId) {
  21154. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21155. if (!materialFound && parsedData.multiMaterials) {
  21156. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21157. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21158. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21159. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21160. var subMatId = parsedMultiMaterial.materials[matIndex];
  21161. loadedMaterialsIds.push(subMatId);
  21162. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21163. }
  21164. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21165. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21166. materialFound = true;
  21167. break;
  21168. }
  21169. }
  21170. }
  21171. if (!materialFound) {
  21172. loadedMaterialsIds.push(parsedMesh.materialId);
  21173. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21174. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21175. }
  21176. }
  21177. }
  21178. // Skeleton ?
  21179. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21180. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21181. if (!skeletonAlreadyLoaded) {
  21182. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21183. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21184. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21185. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21186. loadedSkeletonsIds.push(parsedSkeleton.id);
  21187. }
  21188. }
  21189. }
  21190. }
  21191. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21192. meshes.push(mesh);
  21193. }
  21194. }
  21195. // Connecting parents
  21196. var currentMesh;
  21197. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21198. currentMesh = scene.meshes[index];
  21199. if (currentMesh._waitingParentId) {
  21200. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21201. currentMesh._waitingParentId = undefined;
  21202. }
  21203. }
  21204. // freeze and compute world matrix application
  21205. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21206. currentMesh = scene.meshes[index];
  21207. if (currentMesh._waitingFreezeWorldMatrix) {
  21208. currentMesh.freezeWorldMatrix();
  21209. currentMesh._waitingFreezeWorldMatrix = undefined;
  21210. }
  21211. else {
  21212. currentMesh.computeWorldMatrix(true);
  21213. }
  21214. }
  21215. // Particles
  21216. if (parsedData.particleSystems) {
  21217. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21218. var parsedParticleSystem = parsedData.particleSystems[index];
  21219. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21220. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21221. }
  21222. }
  21223. }
  21224. return true;
  21225. },
  21226. load: function (scene, data, rootUrl) {
  21227. var parsedData = JSON.parse(data);
  21228. // Scene
  21229. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21230. scene.autoClear = parsedData.autoClear;
  21231. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21232. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21233. if (parsedData.gravity) {
  21234. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21235. }
  21236. // Fog
  21237. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21238. scene.fogMode = parsedData.fogMode;
  21239. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21240. scene.fogStart = parsedData.fogStart;
  21241. scene.fogEnd = parsedData.fogEnd;
  21242. scene.fogDensity = parsedData.fogDensity;
  21243. }
  21244. //Physics
  21245. if (parsedData.physicsEnabled) {
  21246. var physicsPlugin;
  21247. if (parsedData.physicsEngine === "cannon") {
  21248. physicsPlugin = new BABYLON.CannonJSPlugin();
  21249. }
  21250. else if (parsedData.physicsEngine === "oimo") {
  21251. physicsPlugin = new BABYLON.OimoJSPlugin();
  21252. }
  21253. //else - default engine, which is currently oimo
  21254. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21255. scene.enablePhysics(physicsGravity, physicsPlugin);
  21256. }
  21257. //collisions, if defined. otherwise, default is true
  21258. if (parsedData.collisionsEnabled != undefined) {
  21259. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21260. }
  21261. scene.workerCollisions = !!parsedData.workerCollisions;
  21262. var index;
  21263. var cache;
  21264. // Lights
  21265. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21266. var parsedLight = parsedData.lights[index];
  21267. BABYLON.Light.Parse(parsedLight, scene);
  21268. }
  21269. // Animations
  21270. if (parsedData.animations) {
  21271. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21272. var parsedAnimation = parsedData.animations[index];
  21273. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21274. }
  21275. }
  21276. // Materials
  21277. if (parsedData.materials) {
  21278. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21279. var parsedMaterial = parsedData.materials[index];
  21280. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21281. }
  21282. }
  21283. if (parsedData.multiMaterials) {
  21284. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21285. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21286. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21287. }
  21288. }
  21289. // Skeletons
  21290. if (parsedData.skeletons) {
  21291. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21292. var parsedSkeleton = parsedData.skeletons[index];
  21293. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21294. }
  21295. }
  21296. // Geometries
  21297. var geometries = parsedData.geometries;
  21298. if (geometries) {
  21299. // Boxes
  21300. var boxes = geometries.boxes;
  21301. if (boxes) {
  21302. for (index = 0, cache = boxes.length; index < cache; index++) {
  21303. var parsedBox = boxes[index];
  21304. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21305. }
  21306. }
  21307. // Spheres
  21308. var spheres = geometries.spheres;
  21309. if (spheres) {
  21310. for (index = 0, cache = spheres.length; index < cache; index++) {
  21311. var parsedSphere = spheres[index];
  21312. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21313. }
  21314. }
  21315. // Cylinders
  21316. var cylinders = geometries.cylinders;
  21317. if (cylinders) {
  21318. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21319. var parsedCylinder = cylinders[index];
  21320. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21321. }
  21322. }
  21323. // Toruses
  21324. var toruses = geometries.toruses;
  21325. if (toruses) {
  21326. for (index = 0, cache = toruses.length; index < cache; index++) {
  21327. var parsedTorus = toruses[index];
  21328. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21329. }
  21330. }
  21331. // Grounds
  21332. var grounds = geometries.grounds;
  21333. if (grounds) {
  21334. for (index = 0, cache = grounds.length; index < cache; index++) {
  21335. var parsedGround = grounds[index];
  21336. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21337. }
  21338. }
  21339. // Planes
  21340. var planes = geometries.planes;
  21341. if (planes) {
  21342. for (index = 0, cache = planes.length; index < cache; index++) {
  21343. var parsedPlane = planes[index];
  21344. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21345. }
  21346. }
  21347. // TorusKnots
  21348. var torusKnots = geometries.torusKnots;
  21349. if (torusKnots) {
  21350. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21351. var parsedTorusKnot = torusKnots[index];
  21352. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21353. }
  21354. }
  21355. // VertexData
  21356. var vertexData = geometries.vertexData;
  21357. if (vertexData) {
  21358. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21359. var parsedVertexData = vertexData[index];
  21360. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21361. }
  21362. }
  21363. }
  21364. // Meshes
  21365. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21366. var parsedMesh = parsedData.meshes[index];
  21367. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21368. }
  21369. // Cameras
  21370. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21371. var parsedCamera = parsedData.cameras[index];
  21372. BABYLON.Camera.Parse(parsedCamera, scene);
  21373. }
  21374. if (parsedData.activeCameraID) {
  21375. scene.setActiveCameraByID(parsedData.activeCameraID);
  21376. }
  21377. // Browsing all the graph to connect the dots
  21378. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21379. var camera = scene.cameras[index];
  21380. if (camera._waitingParentId) {
  21381. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21382. camera._waitingParentId = undefined;
  21383. }
  21384. }
  21385. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21386. var light = scene.lights[index];
  21387. if (light._waitingParentId) {
  21388. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21389. light._waitingParentId = undefined;
  21390. }
  21391. }
  21392. // Sounds
  21393. var loadedSounds = [];
  21394. var loadedSound;
  21395. if (BABYLON.AudioEngine && parsedData.sounds) {
  21396. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21397. var parsedSound = parsedData.sounds[index];
  21398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21399. if (!parsedSound.url)
  21400. parsedSound.url = parsedSound.name;
  21401. if (!loadedSounds[parsedSound.url]) {
  21402. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21403. loadedSounds[parsedSound.url] = loadedSound;
  21404. }
  21405. else {
  21406. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21407. }
  21408. }
  21409. else {
  21410. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21411. }
  21412. }
  21413. }
  21414. loadedSounds = [];
  21415. // Connect parents & children and parse actions
  21416. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21417. var mesh = scene.meshes[index];
  21418. if (mesh._waitingParentId) {
  21419. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21420. mesh._waitingParentId = undefined;
  21421. }
  21422. if (mesh._waitingActions) {
  21423. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21424. mesh._waitingActions = undefined;
  21425. }
  21426. }
  21427. // freeze world matrix application
  21428. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21429. var currentMesh = scene.meshes[index];
  21430. if (currentMesh._waitingFreezeWorldMatrix) {
  21431. currentMesh.freezeWorldMatrix();
  21432. currentMesh._waitingFreezeWorldMatrix = undefined;
  21433. }
  21434. else {
  21435. currentMesh.computeWorldMatrix(true);
  21436. }
  21437. }
  21438. // Particles Systems
  21439. if (parsedData.particleSystems) {
  21440. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21441. var parsedParticleSystem = parsedData.particleSystems[index];
  21442. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21443. }
  21444. }
  21445. // Lens flares
  21446. if (parsedData.lensFlareSystems) {
  21447. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21448. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21449. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21450. }
  21451. }
  21452. // Shadows
  21453. if (parsedData.shadowGenerators) {
  21454. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21455. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21456. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21457. }
  21458. }
  21459. // Actions (scene)
  21460. if (parsedData.actions) {
  21461. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21462. }
  21463. // Finish
  21464. return true;
  21465. }
  21466. });
  21467. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21468. })(BABYLON || (BABYLON = {}));
  21469. var BABYLON;
  21470. (function (BABYLON) {
  21471. var SpriteManager = (function () {
  21472. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21474. this.name = name;
  21475. this.cellSize = cellSize;
  21476. this.sprites = new Array();
  21477. this.renderingGroupId = 0;
  21478. this.layerMask = 0x0FFFFFFF;
  21479. this.fogEnabled = true;
  21480. this.isPickable = false;
  21481. this._vertexDeclaration = [4, 4, 4, 4];
  21482. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21483. this._capacity = capacity;
  21484. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21485. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21486. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21487. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21488. this._scene = scene;
  21489. this._scene.spriteManagers.push(this);
  21490. // VBO
  21491. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21492. var indices = [];
  21493. var index = 0;
  21494. for (var count = 0; count < capacity; count++) {
  21495. indices.push(index);
  21496. indices.push(index + 1);
  21497. indices.push(index + 2);
  21498. indices.push(index);
  21499. indices.push(index + 2);
  21500. indices.push(index + 3);
  21501. index += 4;
  21502. }
  21503. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21504. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21505. // Effects
  21506. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21507. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21508. }
  21509. Object.defineProperty(SpriteManager.prototype, "texture", {
  21510. get: function () {
  21511. return this._spriteTexture;
  21512. },
  21513. set: function (value) {
  21514. this._spriteTexture = value;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21520. var arrayOffset = index * 16;
  21521. if (offsetX === 0)
  21522. offsetX = this._epsilon;
  21523. else if (offsetX === 1)
  21524. offsetX = 1 - this._epsilon;
  21525. if (offsetY === 0)
  21526. offsetY = this._epsilon;
  21527. else if (offsetY === 1)
  21528. offsetY = 1 - this._epsilon;
  21529. this._vertices[arrayOffset] = sprite.position.x;
  21530. this._vertices[arrayOffset + 1] = sprite.position.y;
  21531. this._vertices[arrayOffset + 2] = sprite.position.z;
  21532. this._vertices[arrayOffset + 3] = sprite.angle;
  21533. this._vertices[arrayOffset + 4] = sprite.width;
  21534. this._vertices[arrayOffset + 5] = sprite.height;
  21535. this._vertices[arrayOffset + 6] = offsetX;
  21536. this._vertices[arrayOffset + 7] = offsetY;
  21537. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21538. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21539. var offset = (sprite.cellIndex / rowSize) >> 0;
  21540. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21541. this._vertices[arrayOffset + 11] = offset;
  21542. // Color
  21543. this._vertices[arrayOffset + 12] = sprite.color.r;
  21544. this._vertices[arrayOffset + 13] = sprite.color.g;
  21545. this._vertices[arrayOffset + 14] = sprite.color.b;
  21546. this._vertices[arrayOffset + 15] = sprite.color.a;
  21547. };
  21548. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21549. var count = Math.min(this._capacity, this.sprites.length);
  21550. var min = BABYLON.Vector3.Zero();
  21551. var max = BABYLON.Vector3.Zero();
  21552. var distance = Number.MAX_VALUE;
  21553. var currentSprite;
  21554. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21555. var cameraView = camera.getViewMatrix();
  21556. for (var index = 0; index < count; index++) {
  21557. var sprite = this.sprites[index];
  21558. if (!sprite) {
  21559. continue;
  21560. }
  21561. if (predicate) {
  21562. if (!predicate(sprite)) {
  21563. continue;
  21564. }
  21565. }
  21566. else if (!sprite.isPickable) {
  21567. continue;
  21568. }
  21569. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21570. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21571. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21572. if (ray.intersectsBoxMinMax(min, max)) {
  21573. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21574. if (distance > currentDistance) {
  21575. distance = currentDistance;
  21576. currentSprite = sprite;
  21577. if (fastCheck) {
  21578. break;
  21579. }
  21580. }
  21581. }
  21582. }
  21583. if (currentSprite) {
  21584. var result = new BABYLON.PickingInfo();
  21585. result.hit = true;
  21586. result.pickedSprite = currentSprite;
  21587. result.distance = distance;
  21588. return result;
  21589. }
  21590. return null;
  21591. };
  21592. SpriteManager.prototype.render = function () {
  21593. // Check
  21594. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21595. return;
  21596. var engine = this._scene.getEngine();
  21597. var baseSize = this._spriteTexture.getBaseSize();
  21598. // Sprites
  21599. var deltaTime = engine.getDeltaTime();
  21600. var max = Math.min(this._capacity, this.sprites.length);
  21601. var rowSize = baseSize.width / this.cellSize;
  21602. var offset = 0;
  21603. for (var index = 0; index < max; index++) {
  21604. var sprite = this.sprites[index];
  21605. if (!sprite) {
  21606. continue;
  21607. }
  21608. sprite._animate(deltaTime);
  21609. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21610. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21611. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21612. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21613. }
  21614. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21615. // Render
  21616. var effect = this._effectBase;
  21617. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21618. effect = this._effectFog;
  21619. }
  21620. engine.enableEffect(effect);
  21621. var viewMatrix = this._scene.getViewMatrix();
  21622. effect.setTexture("diffuseSampler", this._spriteTexture);
  21623. effect.setMatrix("view", viewMatrix);
  21624. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21625. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21626. // Fog
  21627. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21628. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21629. effect.setColor3("vFogColor", this._scene.fogColor);
  21630. }
  21631. // VBOs
  21632. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21633. // Draw order
  21634. engine.setDepthFunctionToLessOrEqual();
  21635. effect.setBool("alphaTest", true);
  21636. engine.setColorWrite(false);
  21637. engine.draw(true, 0, max * 6);
  21638. engine.setColorWrite(true);
  21639. effect.setBool("alphaTest", false);
  21640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21641. engine.draw(true, 0, max * 6);
  21642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21643. };
  21644. SpriteManager.prototype.dispose = function () {
  21645. if (this._vertexBuffer) {
  21646. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21647. this._vertexBuffer = null;
  21648. }
  21649. if (this._indexBuffer) {
  21650. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21651. this._indexBuffer = null;
  21652. }
  21653. if (this._spriteTexture) {
  21654. this._spriteTexture.dispose();
  21655. this._spriteTexture = null;
  21656. }
  21657. // Remove from scene
  21658. var index = this._scene.spriteManagers.indexOf(this);
  21659. this._scene.spriteManagers.splice(index, 1);
  21660. // Callback
  21661. if (this.onDispose) {
  21662. this.onDispose();
  21663. }
  21664. };
  21665. return SpriteManager;
  21666. })();
  21667. BABYLON.SpriteManager = SpriteManager;
  21668. })(BABYLON || (BABYLON = {}));
  21669. var BABYLON;
  21670. (function (BABYLON) {
  21671. var Sprite = (function () {
  21672. function Sprite(name, manager) {
  21673. this.name = name;
  21674. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21675. this.width = 1.0;
  21676. this.height = 1.0;
  21677. this.angle = 0;
  21678. this.cellIndex = 0;
  21679. this.invertU = 0;
  21680. this.invertV = 0;
  21681. this.animations = new Array();
  21682. this.isPickable = false;
  21683. this._animationStarted = false;
  21684. this._loopAnimation = false;
  21685. this._fromIndex = 0;
  21686. this._toIndex = 0;
  21687. this._delay = 0;
  21688. this._direction = 1;
  21689. this._frameCount = 0;
  21690. this._time = 0;
  21691. this._manager = manager;
  21692. this._manager.sprites.push(this);
  21693. this.position = BABYLON.Vector3.Zero();
  21694. }
  21695. Object.defineProperty(Sprite.prototype, "size", {
  21696. get: function () {
  21697. return this.width;
  21698. },
  21699. set: function (value) {
  21700. this.width = value;
  21701. this.height = value;
  21702. },
  21703. enumerable: true,
  21704. configurable: true
  21705. });
  21706. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21707. this._fromIndex = from;
  21708. this._toIndex = to;
  21709. this._loopAnimation = loop;
  21710. this._delay = delay;
  21711. this._animationStarted = true;
  21712. this._direction = from < to ? 1 : -1;
  21713. this.cellIndex = from;
  21714. this._time = 0;
  21715. };
  21716. Sprite.prototype.stopAnimation = function () {
  21717. this._animationStarted = false;
  21718. };
  21719. Sprite.prototype._animate = function (deltaTime) {
  21720. if (!this._animationStarted)
  21721. return;
  21722. this._time += deltaTime;
  21723. if (this._time > this._delay) {
  21724. this._time = this._time % this._delay;
  21725. this.cellIndex += this._direction;
  21726. if (this.cellIndex == this._toIndex) {
  21727. if (this._loopAnimation) {
  21728. this.cellIndex = this._fromIndex;
  21729. }
  21730. else {
  21731. this._animationStarted = false;
  21732. if (this.disposeWhenFinishedAnimating) {
  21733. this.dispose();
  21734. }
  21735. }
  21736. }
  21737. }
  21738. };
  21739. Sprite.prototype.dispose = function () {
  21740. for (var i = 0; i < this._manager.sprites.length; i++) {
  21741. if (this._manager.sprites[i] == this) {
  21742. this._manager.sprites.splice(i, 1);
  21743. }
  21744. }
  21745. };
  21746. return Sprite;
  21747. })();
  21748. BABYLON.Sprite = Sprite;
  21749. })(BABYLON || (BABYLON = {}));
  21750. var BABYLON;
  21751. (function (BABYLON) {
  21752. var Layer = (function () {
  21753. function Layer(name, imgUrl, scene, isBackground, color) {
  21754. this.name = name;
  21755. this.scale = new BABYLON.Vector2(1, 1);
  21756. this.offset = new BABYLON.Vector2(0, 0);
  21757. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21758. this._vertexDeclaration = [2];
  21759. this._vertexStrideSize = 2 * 4;
  21760. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21761. this.isBackground = isBackground === undefined ? true : isBackground;
  21762. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21763. this._scene = scene;
  21764. this._scene.layers.push(this);
  21765. // VBO
  21766. var vertices = [];
  21767. vertices.push(1, 1);
  21768. vertices.push(-1, 1);
  21769. vertices.push(-1, -1);
  21770. vertices.push(1, -1);
  21771. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21772. // Indices
  21773. var indices = [];
  21774. indices.push(0);
  21775. indices.push(1);
  21776. indices.push(2);
  21777. indices.push(0);
  21778. indices.push(2);
  21779. indices.push(3);
  21780. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21781. // Effects
  21782. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21783. }
  21784. Layer.prototype.render = function () {
  21785. // Check
  21786. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21787. return;
  21788. var engine = this._scene.getEngine();
  21789. // Render
  21790. engine.enableEffect(this._effect);
  21791. engine.setState(false);
  21792. // Texture
  21793. this._effect.setTexture("textureSampler", this.texture);
  21794. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21795. // Color
  21796. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21797. // Scale / offset
  21798. this._effect.setVector2("offset", this.offset);
  21799. this._effect.setVector2("scale", this.scale);
  21800. // VBOs
  21801. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21802. // Draw order
  21803. engine.setAlphaMode(this.alphaBlendingMode);
  21804. engine.draw(true, 0, 6);
  21805. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21806. };
  21807. Layer.prototype.dispose = function () {
  21808. if (this._vertexBuffer) {
  21809. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21810. this._vertexBuffer = null;
  21811. }
  21812. if (this._indexBuffer) {
  21813. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21814. this._indexBuffer = null;
  21815. }
  21816. if (this.texture) {
  21817. this.texture.dispose();
  21818. this.texture = null;
  21819. }
  21820. // Remove from scene
  21821. var index = this._scene.layers.indexOf(this);
  21822. this._scene.layers.splice(index, 1);
  21823. // Callback
  21824. if (this.onDispose) {
  21825. this.onDispose();
  21826. }
  21827. };
  21828. return Layer;
  21829. })();
  21830. BABYLON.Layer = Layer;
  21831. })(BABYLON || (BABYLON = {}));
  21832. var BABYLON;
  21833. (function (BABYLON) {
  21834. var Particle = (function () {
  21835. function Particle() {
  21836. this.position = BABYLON.Vector3.Zero();
  21837. this.direction = BABYLON.Vector3.Zero();
  21838. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21839. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21840. this.lifeTime = 1.0;
  21841. this.age = 0;
  21842. this.size = 0;
  21843. this.angle = 0;
  21844. this.angularSpeed = 0;
  21845. }
  21846. Particle.prototype.copyTo = function (other) {
  21847. other.position.copyFrom(this.position);
  21848. other.direction.copyFrom(this.direction);
  21849. other.color.copyFrom(this.color);
  21850. other.colorStep.copyFrom(this.colorStep);
  21851. other.lifeTime = this.lifeTime;
  21852. other.age = this.age;
  21853. other.size = this.size;
  21854. other.angle = this.angle;
  21855. other.angularSpeed = this.angularSpeed;
  21856. };
  21857. return Particle;
  21858. })();
  21859. BABYLON.Particle = Particle;
  21860. })(BABYLON || (BABYLON = {}));
  21861. var BABYLON;
  21862. (function (BABYLON) {
  21863. var randomNumber = function (min, max) {
  21864. if (min === max) {
  21865. return (min);
  21866. }
  21867. var random = Math.random();
  21868. return ((random * (max - min)) + min);
  21869. };
  21870. var ParticleSystem = (function () {
  21871. function ParticleSystem(name, capacity, scene, customEffect) {
  21872. var _this = this;
  21873. this.name = name;
  21874. // Members
  21875. this.animations = [];
  21876. this.renderingGroupId = 0;
  21877. this.emitter = null;
  21878. this.emitRate = 10;
  21879. this.manualEmitCount = -1;
  21880. this.updateSpeed = 0.01;
  21881. this.targetStopDuration = 0;
  21882. this.disposeOnStop = false;
  21883. this.minEmitPower = 1;
  21884. this.maxEmitPower = 1;
  21885. this.minLifeTime = 1;
  21886. this.maxLifeTime = 1;
  21887. this.minSize = 1;
  21888. this.maxSize = 1;
  21889. this.minAngularSpeed = 0;
  21890. this.maxAngularSpeed = 0;
  21891. this.layerMask = 0x0FFFFFFF;
  21892. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21893. this.forceDepthWrite = false;
  21894. this.gravity = BABYLON.Vector3.Zero();
  21895. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21896. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21897. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21898. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21899. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21900. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21901. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21902. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21903. this.particles = new Array();
  21904. this._vertexDeclaration = [3, 4, 4];
  21905. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21906. this._stockParticles = new Array();
  21907. this._newPartsExcess = 0;
  21908. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21909. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21910. this._scaledDirection = BABYLON.Vector3.Zero();
  21911. this._scaledGravity = BABYLON.Vector3.Zero();
  21912. this._currentRenderId = -1;
  21913. this._started = false;
  21914. this._stopped = false;
  21915. this._actualFrame = 0;
  21916. this.id = name;
  21917. this._capacity = capacity;
  21918. this._scene = scene;
  21919. this._customEffect = customEffect;
  21920. scene.particleSystems.push(this);
  21921. // VBO
  21922. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21923. var indices = [];
  21924. var index = 0;
  21925. for (var count = 0; count < capacity; count++) {
  21926. indices.push(index);
  21927. indices.push(index + 1);
  21928. indices.push(index + 2);
  21929. indices.push(index);
  21930. indices.push(index + 2);
  21931. indices.push(index + 3);
  21932. index += 4;
  21933. }
  21934. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21935. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21936. // Default behaviors
  21937. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21938. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21939. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21940. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21941. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21942. };
  21943. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21944. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21945. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21946. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21947. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21948. };
  21949. this.updateFunction = function (particles) {
  21950. for (var index = 0; index < particles.length; index++) {
  21951. var particle = particles[index];
  21952. particle.age += _this._scaledUpdateSpeed;
  21953. if (particle.age >= particle.lifeTime) {
  21954. _this.recycleParticle(particle);
  21955. index--;
  21956. continue;
  21957. }
  21958. else {
  21959. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21960. particle.color.addInPlace(_this._scaledColorStep);
  21961. if (particle.color.a < 0)
  21962. particle.color.a = 0;
  21963. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21964. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21965. particle.position.addInPlace(_this._scaledDirection);
  21966. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21967. particle.direction.addInPlace(_this._scaledGravity);
  21968. }
  21969. }
  21970. };
  21971. }
  21972. ParticleSystem.prototype.recycleParticle = function (particle) {
  21973. var lastParticle = this.particles.pop();
  21974. if (lastParticle !== particle) {
  21975. lastParticle.copyTo(particle);
  21976. this._stockParticles.push(lastParticle);
  21977. }
  21978. };
  21979. ParticleSystem.prototype.getCapacity = function () {
  21980. return this._capacity;
  21981. };
  21982. ParticleSystem.prototype.isAlive = function () {
  21983. return this._alive;
  21984. };
  21985. ParticleSystem.prototype.isStarted = function () {
  21986. return this._started;
  21987. };
  21988. ParticleSystem.prototype.start = function () {
  21989. this._started = true;
  21990. this._stopped = false;
  21991. this._actualFrame = 0;
  21992. };
  21993. ParticleSystem.prototype.stop = function () {
  21994. this._stopped = true;
  21995. };
  21996. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21997. var offset = index * 11;
  21998. this._vertices[offset] = particle.position.x;
  21999. this._vertices[offset + 1] = particle.position.y;
  22000. this._vertices[offset + 2] = particle.position.z;
  22001. this._vertices[offset + 3] = particle.color.r;
  22002. this._vertices[offset + 4] = particle.color.g;
  22003. this._vertices[offset + 5] = particle.color.b;
  22004. this._vertices[offset + 6] = particle.color.a;
  22005. this._vertices[offset + 7] = particle.angle;
  22006. this._vertices[offset + 8] = particle.size;
  22007. this._vertices[offset + 9] = offsetX;
  22008. this._vertices[offset + 10] = offsetY;
  22009. };
  22010. ParticleSystem.prototype._update = function (newParticles) {
  22011. // Update current
  22012. this._alive = this.particles.length > 0;
  22013. this.updateFunction(this.particles);
  22014. // Add new ones
  22015. var worldMatrix;
  22016. if (this.emitter.position) {
  22017. worldMatrix = this.emitter.getWorldMatrix();
  22018. }
  22019. else {
  22020. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22021. }
  22022. var particle;
  22023. for (var index = 0; index < newParticles; index++) {
  22024. if (this.particles.length === this._capacity) {
  22025. break;
  22026. }
  22027. if (this._stockParticles.length !== 0) {
  22028. particle = this._stockParticles.pop();
  22029. particle.age = 0;
  22030. }
  22031. else {
  22032. particle = new BABYLON.Particle();
  22033. }
  22034. this.particles.push(particle);
  22035. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22036. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22037. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22038. particle.size = randomNumber(this.minSize, this.maxSize);
  22039. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22040. this.startPositionFunction(worldMatrix, particle.position, particle);
  22041. var step = randomNumber(0, 1.0);
  22042. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22043. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22044. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22045. }
  22046. };
  22047. ParticleSystem.prototype._getEffect = function () {
  22048. if (this._customEffect) {
  22049. return this._customEffect;
  22050. }
  22051. ;
  22052. var defines = [];
  22053. if (this._scene.clipPlane) {
  22054. defines.push("#define CLIPPLANE");
  22055. }
  22056. // Effect
  22057. var join = defines.join("\n");
  22058. if (this._cachedDefines !== join) {
  22059. this._cachedDefines = join;
  22060. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22061. }
  22062. return this._effect;
  22063. };
  22064. ParticleSystem.prototype.animate = function () {
  22065. if (!this._started)
  22066. return;
  22067. var effect = this._getEffect();
  22068. // Check
  22069. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22070. return;
  22071. if (this._currentRenderId === this._scene.getRenderId()) {
  22072. return;
  22073. }
  22074. this._currentRenderId = this._scene.getRenderId();
  22075. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22076. // determine the number of particles we need to create
  22077. var newParticles;
  22078. if (this.manualEmitCount > -1) {
  22079. newParticles = this.manualEmitCount;
  22080. this._newPartsExcess = 0;
  22081. this.manualEmitCount = 0;
  22082. }
  22083. else {
  22084. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22085. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22086. }
  22087. if (this._newPartsExcess > 1.0) {
  22088. newParticles += this._newPartsExcess >> 0;
  22089. this._newPartsExcess -= this._newPartsExcess >> 0;
  22090. }
  22091. this._alive = false;
  22092. if (!this._stopped) {
  22093. this._actualFrame += this._scaledUpdateSpeed;
  22094. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22095. this.stop();
  22096. }
  22097. else {
  22098. newParticles = 0;
  22099. }
  22100. this._update(newParticles);
  22101. // Stopped?
  22102. if (this._stopped) {
  22103. if (!this._alive) {
  22104. this._started = false;
  22105. if (this.disposeOnStop) {
  22106. this._scene._toBeDisposed.push(this);
  22107. }
  22108. }
  22109. }
  22110. // Update VBO
  22111. var offset = 0;
  22112. for (var index = 0; index < this.particles.length; index++) {
  22113. var particle = this.particles[index];
  22114. this._appendParticleVertex(offset++, particle, 0, 0);
  22115. this._appendParticleVertex(offset++, particle, 1, 0);
  22116. this._appendParticleVertex(offset++, particle, 1, 1);
  22117. this._appendParticleVertex(offset++, particle, 0, 1);
  22118. }
  22119. var engine = this._scene.getEngine();
  22120. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22121. };
  22122. ParticleSystem.prototype.render = function () {
  22123. var effect = this._getEffect();
  22124. // Check
  22125. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22126. return 0;
  22127. var engine = this._scene.getEngine();
  22128. // Render
  22129. engine.enableEffect(effect);
  22130. engine.setState(false);
  22131. var viewMatrix = this._scene.getViewMatrix();
  22132. effect.setTexture("diffuseSampler", this.particleTexture);
  22133. effect.setMatrix("view", viewMatrix);
  22134. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22135. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22136. if (this._scene.clipPlane) {
  22137. var clipPlane = this._scene.clipPlane;
  22138. var invView = viewMatrix.clone();
  22139. invView.invert();
  22140. effect.setMatrix("invView", invView);
  22141. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22142. }
  22143. // VBOs
  22144. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22145. // Draw order
  22146. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22147. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22148. }
  22149. else {
  22150. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22151. }
  22152. if (this.forceDepthWrite) {
  22153. engine.setDepthWrite(true);
  22154. }
  22155. engine.draw(true, 0, this.particles.length * 6);
  22156. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22157. return this.particles.length;
  22158. };
  22159. ParticleSystem.prototype.dispose = function () {
  22160. if (this._vertexBuffer) {
  22161. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22162. this._vertexBuffer = null;
  22163. }
  22164. if (this._indexBuffer) {
  22165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22166. this._indexBuffer = null;
  22167. }
  22168. if (this.particleTexture) {
  22169. this.particleTexture.dispose();
  22170. this.particleTexture = null;
  22171. }
  22172. // Remove from scene
  22173. var index = this._scene.particleSystems.indexOf(this);
  22174. this._scene.particleSystems.splice(index, 1);
  22175. // Callback
  22176. if (this.onDispose) {
  22177. this.onDispose();
  22178. }
  22179. };
  22180. // Clone
  22181. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22182. var result = new ParticleSystem(name, this._capacity, this._scene);
  22183. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22184. if (newEmitter === undefined) {
  22185. newEmitter = this.emitter;
  22186. }
  22187. result.emitter = newEmitter;
  22188. if (this.particleTexture) {
  22189. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22190. }
  22191. result.start();
  22192. return result;
  22193. };
  22194. ParticleSystem.prototype.serialize = function () {
  22195. var serializationObject = {};
  22196. serializationObject.name = this.name;
  22197. serializationObject.id = this.id;
  22198. // Emitter
  22199. if (this.emitter.position) {
  22200. serializationObject.emitterId = this.emitter.id;
  22201. }
  22202. else {
  22203. serializationObject.emitter = this.emitter.asArray();
  22204. }
  22205. serializationObject.capacity = this.getCapacity();
  22206. if (this.particleTexture) {
  22207. serializationObject.textureName = this.particleTexture.name;
  22208. }
  22209. // Animations
  22210. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22211. // Particle system
  22212. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22213. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22214. serializationObject.minSize = this.minSize;
  22215. serializationObject.maxSize = this.maxSize;
  22216. serializationObject.minEmitPower = this.minEmitPower;
  22217. serializationObject.maxEmitPower = this.maxEmitPower;
  22218. serializationObject.minLifeTime = this.minLifeTime;
  22219. serializationObject.maxLifeTime = this.maxLifeTime;
  22220. serializationObject.emitRate = this.emitRate;
  22221. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22222. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22223. serializationObject.gravity = this.gravity.asArray();
  22224. serializationObject.direction1 = this.direction1.asArray();
  22225. serializationObject.direction2 = this.direction2.asArray();
  22226. serializationObject.color1 = this.color1.asArray();
  22227. serializationObject.color2 = this.color2.asArray();
  22228. serializationObject.colorDead = this.colorDead.asArray();
  22229. serializationObject.updateSpeed = this.updateSpeed;
  22230. serializationObject.targetStopDuration = this.targetStopDuration;
  22231. serializationObject.textureMask = this.textureMask.asArray();
  22232. serializationObject.blendMode = this.blendMode;
  22233. return serializationObject;
  22234. };
  22235. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22236. var name = parsedParticleSystem.name;
  22237. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22238. if (parsedParticleSystem.id) {
  22239. particleSystem.id = parsedParticleSystem.id;
  22240. }
  22241. // Texture
  22242. if (parsedParticleSystem.textureName) {
  22243. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22244. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22245. }
  22246. // Emitter
  22247. if (parsedParticleSystem.emitterId) {
  22248. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22249. }
  22250. else {
  22251. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22252. }
  22253. // Animations
  22254. if (parsedParticleSystem.animations) {
  22255. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22256. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22257. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22258. }
  22259. }
  22260. // Particle system
  22261. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22262. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22263. particleSystem.minSize = parsedParticleSystem.minSize;
  22264. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22265. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22266. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22267. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22268. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22269. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22270. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22271. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22272. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22273. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22274. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22275. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22276. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22277. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22278. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22279. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22280. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22281. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22282. particleSystem.start();
  22283. return particleSystem;
  22284. };
  22285. // Statics
  22286. ParticleSystem.BLENDMODE_ONEONE = 0;
  22287. ParticleSystem.BLENDMODE_STANDARD = 1;
  22288. return ParticleSystem;
  22289. })();
  22290. BABYLON.ParticleSystem = ParticleSystem;
  22291. })(BABYLON || (BABYLON = {}));
  22292. var BABYLON;
  22293. (function (BABYLON) {
  22294. var AnimationRange = (function () {
  22295. function AnimationRange(name, from, to) {
  22296. this.name = name;
  22297. this.from = from;
  22298. this.to = to;
  22299. }
  22300. return AnimationRange;
  22301. })();
  22302. BABYLON.AnimationRange = AnimationRange;
  22303. /**
  22304. * Composed of a frame, and an action function
  22305. */
  22306. var AnimationEvent = (function () {
  22307. function AnimationEvent(frame, action, onlyOnce) {
  22308. this.frame = frame;
  22309. this.action = action;
  22310. this.onlyOnce = onlyOnce;
  22311. this.isDone = false;
  22312. }
  22313. return AnimationEvent;
  22314. })();
  22315. BABYLON.AnimationEvent = AnimationEvent;
  22316. var Animation = (function () {
  22317. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22318. this.name = name;
  22319. this.targetProperty = targetProperty;
  22320. this.framePerSecond = framePerSecond;
  22321. this.dataType = dataType;
  22322. this.loopMode = loopMode;
  22323. this._offsetsCache = {};
  22324. this._highLimitsCache = {};
  22325. this._stopped = false;
  22326. // The set of event that will be linked to this animation
  22327. this._events = new Array();
  22328. this.allowMatricesInterpolation = false;
  22329. this._ranges = {};
  22330. this.targetPropertyPath = targetProperty.split(".");
  22331. this.dataType = dataType;
  22332. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22333. }
  22334. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22335. var dataType = undefined;
  22336. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22337. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22338. }
  22339. else if (from instanceof BABYLON.Quaternion) {
  22340. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22341. }
  22342. else if (from instanceof BABYLON.Vector3) {
  22343. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22344. }
  22345. else if (from instanceof BABYLON.Vector2) {
  22346. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22347. }
  22348. else if (from instanceof BABYLON.Color3) {
  22349. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22350. }
  22351. if (dataType == undefined) {
  22352. return null;
  22353. }
  22354. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22355. var keys = [];
  22356. keys.push({ frame: 0, value: from });
  22357. keys.push({ frame: totalFrame, value: to });
  22358. animation.setKeys(keys);
  22359. if (easingFunction !== undefined) {
  22360. animation.setEasingFunction(easingFunction);
  22361. }
  22362. return animation;
  22363. };
  22364. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22365. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22366. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22367. };
  22368. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22369. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22370. node.animations.push(animation);
  22371. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22372. };
  22373. // Methods
  22374. /**
  22375. * Add an event to this animation.
  22376. */
  22377. Animation.prototype.addEvent = function (event) {
  22378. this._events.push(event);
  22379. };
  22380. /**
  22381. * Remove all events found at the given frame
  22382. * @param frame
  22383. */
  22384. Animation.prototype.removeEvents = function (frame) {
  22385. for (var index = 0; index < this._events.length; index++) {
  22386. if (this._events[index].frame === frame) {
  22387. this._events.splice(index, 1);
  22388. index--;
  22389. }
  22390. }
  22391. };
  22392. Animation.prototype.createRange = function (name, from, to) {
  22393. // check name not already in use; could happen for bones after serialized
  22394. if (!this._ranges[name]) {
  22395. this._ranges[name] = new AnimationRange(name, from, to);
  22396. }
  22397. };
  22398. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22399. if (deleteFrames === void 0) { deleteFrames = true; }
  22400. if (this._ranges[name]) {
  22401. if (deleteFrames) {
  22402. var from = this._ranges[name].from;
  22403. var to = this._ranges[name].to;
  22404. // this loop MUST go high to low for multiple splices to work
  22405. for (var key = this._keys.length - 1; key >= 0; key--) {
  22406. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22407. this._keys.splice(key, 1);
  22408. }
  22409. }
  22410. }
  22411. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22412. }
  22413. };
  22414. Animation.prototype.getRange = function (name) {
  22415. return this._ranges[name];
  22416. };
  22417. Animation.prototype.reset = function () {
  22418. this._offsetsCache = {};
  22419. this._highLimitsCache = {};
  22420. this.currentFrame = 0;
  22421. };
  22422. Animation.prototype.isStopped = function () {
  22423. return this._stopped;
  22424. };
  22425. Animation.prototype.getKeys = function () {
  22426. return this._keys;
  22427. };
  22428. Animation.prototype.getHighestFrame = function () {
  22429. var ret = 0;
  22430. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22431. if (ret < this._keys[key].frame) {
  22432. ret = this._keys[key].frame;
  22433. }
  22434. }
  22435. return ret;
  22436. };
  22437. Animation.prototype.getEasingFunction = function () {
  22438. return this._easingFunction;
  22439. };
  22440. Animation.prototype.setEasingFunction = function (easingFunction) {
  22441. this._easingFunction = easingFunction;
  22442. };
  22443. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22444. return startValue + (endValue - startValue) * gradient;
  22445. };
  22446. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22447. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22448. };
  22449. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22450. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22451. };
  22452. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22453. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22454. };
  22455. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22456. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22457. };
  22458. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22459. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22460. };
  22461. Animation.prototype.clone = function () {
  22462. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22463. if (this._keys) {
  22464. clone.setKeys(this._keys);
  22465. }
  22466. return clone;
  22467. };
  22468. Animation.prototype.setKeys = function (values) {
  22469. this._keys = values.slice(0);
  22470. this._offsetsCache = {};
  22471. this._highLimitsCache = {};
  22472. };
  22473. Animation.prototype._getKeyValue = function (value) {
  22474. if (typeof value === "function") {
  22475. return value();
  22476. }
  22477. return value;
  22478. };
  22479. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22480. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22481. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22482. }
  22483. this.currentFrame = currentFrame;
  22484. // Try to get a hash to find the right key
  22485. 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));
  22486. if (this._keys[startKey].frame >= currentFrame) {
  22487. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22488. startKey--;
  22489. }
  22490. }
  22491. for (var key = startKey; key < this._keys.length; key++) {
  22492. if (this._keys[key + 1].frame >= currentFrame) {
  22493. var startValue = this._getKeyValue(this._keys[key].value);
  22494. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22495. // gradient : percent of currentFrame between the frame inf and the frame sup
  22496. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22497. // check for easingFunction and correction of gradient
  22498. if (this._easingFunction != null) {
  22499. gradient = this._easingFunction.ease(gradient);
  22500. }
  22501. switch (this.dataType) {
  22502. // Float
  22503. case Animation.ANIMATIONTYPE_FLOAT:
  22504. switch (loopMode) {
  22505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22507. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22508. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22509. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22510. }
  22511. break;
  22512. // Quaternion
  22513. case Animation.ANIMATIONTYPE_QUATERNION:
  22514. var quaternion = null;
  22515. switch (loopMode) {
  22516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22518. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22519. break;
  22520. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22521. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22522. break;
  22523. }
  22524. return quaternion;
  22525. // Vector3
  22526. case Animation.ANIMATIONTYPE_VECTOR3:
  22527. switch (loopMode) {
  22528. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22529. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22530. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22531. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22532. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22533. }
  22534. // Vector2
  22535. case Animation.ANIMATIONTYPE_VECTOR2:
  22536. switch (loopMode) {
  22537. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22538. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22539. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22541. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22542. }
  22543. // Color3
  22544. case Animation.ANIMATIONTYPE_COLOR3:
  22545. switch (loopMode) {
  22546. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22547. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22548. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22549. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22550. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22551. }
  22552. // Matrix
  22553. case Animation.ANIMATIONTYPE_MATRIX:
  22554. switch (loopMode) {
  22555. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22556. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22557. if (this.allowMatricesInterpolation) {
  22558. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22559. }
  22560. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22561. return startValue;
  22562. }
  22563. default:
  22564. break;
  22565. }
  22566. break;
  22567. }
  22568. }
  22569. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22570. };
  22571. Animation.prototype.setValue = function (currentValue) {
  22572. // Set value
  22573. if (this.targetPropertyPath.length > 1) {
  22574. var property = this._target[this.targetPropertyPath[0]];
  22575. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22576. property = property[this.targetPropertyPath[index]];
  22577. }
  22578. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22579. }
  22580. else {
  22581. this._target[this.targetPropertyPath[0]] = currentValue;
  22582. }
  22583. if (this._target.markAsDirty) {
  22584. this._target.markAsDirty(this.targetProperty);
  22585. }
  22586. };
  22587. Animation.prototype.goToFrame = function (frame) {
  22588. if (frame < this._keys[0].frame) {
  22589. frame = this._keys[0].frame;
  22590. }
  22591. else if (frame > this._keys[this._keys.length - 1].frame) {
  22592. frame = this._keys[this._keys.length - 1].frame;
  22593. }
  22594. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22595. this.setValue(currentValue);
  22596. };
  22597. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22598. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22599. this._stopped = true;
  22600. return false;
  22601. }
  22602. var returnValue = true;
  22603. // Adding a start key at frame 0 if missing
  22604. if (this._keys[0].frame !== 0) {
  22605. var newKey = { frame: 0, value: this._keys[0].value };
  22606. this._keys.splice(0, 0, newKey);
  22607. }
  22608. // Check limits
  22609. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22610. from = this._keys[0].frame;
  22611. }
  22612. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22613. to = this._keys[this._keys.length - 1].frame;
  22614. }
  22615. // Compute ratio
  22616. var range = to - from;
  22617. var offsetValue;
  22618. // ratio represents the frame delta between from and to
  22619. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22620. var highLimitValue = 0;
  22621. if (ratio > range && !loop) {
  22622. returnValue = false;
  22623. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22624. }
  22625. else {
  22626. // Get max value if required
  22627. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22628. var keyOffset = to.toString() + from.toString();
  22629. if (!this._offsetsCache[keyOffset]) {
  22630. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22631. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22632. switch (this.dataType) {
  22633. // Float
  22634. case Animation.ANIMATIONTYPE_FLOAT:
  22635. this._offsetsCache[keyOffset] = toValue - fromValue;
  22636. break;
  22637. // Quaternion
  22638. case Animation.ANIMATIONTYPE_QUATERNION:
  22639. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22640. break;
  22641. // Vector3
  22642. case Animation.ANIMATIONTYPE_VECTOR3:
  22643. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22644. // Vector2
  22645. case Animation.ANIMATIONTYPE_VECTOR2:
  22646. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22647. // Color3
  22648. case Animation.ANIMATIONTYPE_COLOR3:
  22649. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22650. default:
  22651. break;
  22652. }
  22653. this._highLimitsCache[keyOffset] = toValue;
  22654. }
  22655. highLimitValue = this._highLimitsCache[keyOffset];
  22656. offsetValue = this._offsetsCache[keyOffset];
  22657. }
  22658. }
  22659. if (offsetValue === undefined) {
  22660. switch (this.dataType) {
  22661. // Float
  22662. case Animation.ANIMATIONTYPE_FLOAT:
  22663. offsetValue = 0;
  22664. break;
  22665. // Quaternion
  22666. case Animation.ANIMATIONTYPE_QUATERNION:
  22667. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22668. break;
  22669. // Vector3
  22670. case Animation.ANIMATIONTYPE_VECTOR3:
  22671. offsetValue = BABYLON.Vector3.Zero();
  22672. break;
  22673. // Vector2
  22674. case Animation.ANIMATIONTYPE_VECTOR2:
  22675. offsetValue = BABYLON.Vector2.Zero();
  22676. break;
  22677. // Color3
  22678. case Animation.ANIMATIONTYPE_COLOR3:
  22679. offsetValue = BABYLON.Color3.Black();
  22680. }
  22681. }
  22682. // Compute value
  22683. var repeatCount = (ratio / range) >> 0;
  22684. var currentFrame = returnValue ? from + ratio % range : to;
  22685. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22686. // Set value
  22687. this.setValue(currentValue);
  22688. // Check events
  22689. for (var index = 0; index < this._events.length; index++) {
  22690. if (currentFrame >= this._events[index].frame) {
  22691. var event = this._events[index];
  22692. if (!event.isDone) {
  22693. // If event should be done only once, remove it.
  22694. if (event.onlyOnce) {
  22695. this._events.splice(index, 1);
  22696. index--;
  22697. }
  22698. event.isDone = true;
  22699. event.action();
  22700. } // Don't do anything if the event has already be done.
  22701. }
  22702. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22703. // reset event, the animation is looping
  22704. this._events[index].isDone = false;
  22705. }
  22706. }
  22707. if (!returnValue) {
  22708. this._stopped = true;
  22709. }
  22710. return returnValue;
  22711. };
  22712. Animation.prototype.serialize = function () {
  22713. var serializationObject = {};
  22714. serializationObject.name = this.name;
  22715. serializationObject.property = this.targetProperty;
  22716. serializationObject.framePerSecond = this.framePerSecond;
  22717. serializationObject.dataType = this.dataType;
  22718. serializationObject.loopBehavior = this.loopMode;
  22719. var dataType = this.dataType;
  22720. serializationObject.keys = [];
  22721. var keys = this.getKeys();
  22722. for (var index = 0; index < keys.length; index++) {
  22723. var animationKey = keys[index];
  22724. var key = {};
  22725. key.frame = animationKey.frame;
  22726. switch (dataType) {
  22727. case Animation.ANIMATIONTYPE_FLOAT:
  22728. key.values = [animationKey.value];
  22729. break;
  22730. case Animation.ANIMATIONTYPE_QUATERNION:
  22731. case Animation.ANIMATIONTYPE_MATRIX:
  22732. case Animation.ANIMATIONTYPE_VECTOR3:
  22733. case Animation.ANIMATIONTYPE_COLOR3:
  22734. key.values = animationKey.value.asArray();
  22735. break;
  22736. }
  22737. serializationObject.keys.push(key);
  22738. }
  22739. serializationObject.ranges = [];
  22740. for (var name in this._ranges) {
  22741. var range = {};
  22742. range.name = name;
  22743. range.from = this._ranges[name].from;
  22744. range.to = this._ranges[name].to;
  22745. serializationObject.ranges.push(range);
  22746. }
  22747. return serializationObject;
  22748. };
  22749. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22750. get: function () {
  22751. return Animation._ANIMATIONTYPE_FLOAT;
  22752. },
  22753. enumerable: true,
  22754. configurable: true
  22755. });
  22756. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22757. get: function () {
  22758. return Animation._ANIMATIONTYPE_VECTOR3;
  22759. },
  22760. enumerable: true,
  22761. configurable: true
  22762. });
  22763. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22764. get: function () {
  22765. return Animation._ANIMATIONTYPE_VECTOR2;
  22766. },
  22767. enumerable: true,
  22768. configurable: true
  22769. });
  22770. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22771. get: function () {
  22772. return Animation._ANIMATIONTYPE_QUATERNION;
  22773. },
  22774. enumerable: true,
  22775. configurable: true
  22776. });
  22777. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22778. get: function () {
  22779. return Animation._ANIMATIONTYPE_MATRIX;
  22780. },
  22781. enumerable: true,
  22782. configurable: true
  22783. });
  22784. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22785. get: function () {
  22786. return Animation._ANIMATIONTYPE_COLOR3;
  22787. },
  22788. enumerable: true,
  22789. configurable: true
  22790. });
  22791. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22792. get: function () {
  22793. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22794. },
  22795. enumerable: true,
  22796. configurable: true
  22797. });
  22798. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22799. get: function () {
  22800. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22801. },
  22802. enumerable: true,
  22803. configurable: true
  22804. });
  22805. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22806. get: function () {
  22807. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22808. },
  22809. enumerable: true,
  22810. configurable: true
  22811. });
  22812. Animation.Parse = function (parsedAnimation) {
  22813. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22814. var dataType = parsedAnimation.dataType;
  22815. var keys = [];
  22816. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22817. var key = parsedAnimation.keys[index];
  22818. var data;
  22819. switch (dataType) {
  22820. case Animation.ANIMATIONTYPE_FLOAT:
  22821. data = key.values[0];
  22822. break;
  22823. case Animation.ANIMATIONTYPE_QUATERNION:
  22824. data = BABYLON.Quaternion.FromArray(key.values);
  22825. break;
  22826. case Animation.ANIMATIONTYPE_MATRIX:
  22827. data = BABYLON.Matrix.FromArray(key.values);
  22828. break;
  22829. case Animation.ANIMATIONTYPE_COLOR3:
  22830. data = BABYLON.Color3.FromArray(key.values);
  22831. break;
  22832. case Animation.ANIMATIONTYPE_VECTOR3:
  22833. default:
  22834. data = BABYLON.Vector3.FromArray(key.values);
  22835. break;
  22836. }
  22837. keys.push({
  22838. frame: key.frame,
  22839. value: data
  22840. });
  22841. }
  22842. animation.setKeys(keys);
  22843. if (parsedAnimation.ranges) {
  22844. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22845. data = parsedAnimation.ranges[index];
  22846. animation.createRange(data.name, data.from, data.to);
  22847. }
  22848. }
  22849. return animation;
  22850. };
  22851. Animation.AppendSerializedAnimations = function (source, destination) {
  22852. if (source.animations) {
  22853. destination.animations = [];
  22854. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22855. var animation = source.animations[animationIndex];
  22856. destination.animations.push(animation.serialize());
  22857. }
  22858. }
  22859. };
  22860. // Statics
  22861. Animation._ANIMATIONTYPE_FLOAT = 0;
  22862. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22863. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22864. Animation._ANIMATIONTYPE_MATRIX = 3;
  22865. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22866. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22867. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22868. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22869. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22870. return Animation;
  22871. })();
  22872. BABYLON.Animation = Animation;
  22873. })(BABYLON || (BABYLON = {}));
  22874. var BABYLON;
  22875. (function (BABYLON) {
  22876. var Animatable = (function () {
  22877. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22878. if (fromFrame === void 0) { fromFrame = 0; }
  22879. if (toFrame === void 0) { toFrame = 100; }
  22880. if (loopAnimation === void 0) { loopAnimation = false; }
  22881. if (speedRatio === void 0) { speedRatio = 1.0; }
  22882. this.target = target;
  22883. this.fromFrame = fromFrame;
  22884. this.toFrame = toFrame;
  22885. this.loopAnimation = loopAnimation;
  22886. this.speedRatio = speedRatio;
  22887. this.onAnimationEnd = onAnimationEnd;
  22888. this._animations = new Array();
  22889. this._paused = false;
  22890. this.animationStarted = false;
  22891. if (animations) {
  22892. this.appendAnimations(target, animations);
  22893. }
  22894. this._scene = scene;
  22895. scene._activeAnimatables.push(this);
  22896. }
  22897. // Methods
  22898. Animatable.prototype.getAnimations = function () {
  22899. return this._animations;
  22900. };
  22901. Animatable.prototype.appendAnimations = function (target, animations) {
  22902. for (var index = 0; index < animations.length; index++) {
  22903. var animation = animations[index];
  22904. animation._target = target;
  22905. this._animations.push(animation);
  22906. }
  22907. };
  22908. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22909. var animations = this._animations;
  22910. for (var index = 0; index < animations.length; index++) {
  22911. if (animations[index].targetProperty === property) {
  22912. return animations[index];
  22913. }
  22914. }
  22915. return null;
  22916. };
  22917. Animatable.prototype.reset = function () {
  22918. var animations = this._animations;
  22919. for (var index = 0; index < animations.length; index++) {
  22920. animations[index].reset();
  22921. }
  22922. this._localDelayOffset = null;
  22923. this._pausedDelay = null;
  22924. };
  22925. Animatable.prototype.goToFrame = function (frame) {
  22926. var animations = this._animations;
  22927. for (var index = 0; index < animations.length; index++) {
  22928. animations[index].goToFrame(frame);
  22929. }
  22930. };
  22931. Animatable.prototype.pause = function () {
  22932. if (this._paused) {
  22933. return;
  22934. }
  22935. this._paused = true;
  22936. };
  22937. Animatable.prototype.restart = function () {
  22938. this._paused = false;
  22939. };
  22940. Animatable.prototype.stop = function () {
  22941. var index = this._scene._activeAnimatables.indexOf(this);
  22942. if (index > -1) {
  22943. this._scene._activeAnimatables.splice(index, 1);
  22944. if (this.onAnimationEnd) {
  22945. this.onAnimationEnd();
  22946. }
  22947. }
  22948. };
  22949. Animatable.prototype._animate = function (delay) {
  22950. if (this._paused) {
  22951. this.animationStarted = false;
  22952. if (!this._pausedDelay) {
  22953. this._pausedDelay = delay;
  22954. }
  22955. return true;
  22956. }
  22957. if (!this._localDelayOffset) {
  22958. this._localDelayOffset = delay;
  22959. }
  22960. else if (this._pausedDelay) {
  22961. this._localDelayOffset += delay - this._pausedDelay;
  22962. this._pausedDelay = null;
  22963. }
  22964. // Animating
  22965. var running = false;
  22966. var animations = this._animations;
  22967. var index;
  22968. for (index = 0; index < animations.length; index++) {
  22969. var animation = animations[index];
  22970. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22971. running = running || isRunning;
  22972. }
  22973. this.animationStarted = running;
  22974. if (!running) {
  22975. // Remove from active animatables
  22976. index = this._scene._activeAnimatables.indexOf(this);
  22977. this._scene._activeAnimatables.splice(index, 1);
  22978. }
  22979. if (!running && this.onAnimationEnd) {
  22980. this.onAnimationEnd();
  22981. this.onAnimationEnd = null;
  22982. }
  22983. return running;
  22984. };
  22985. return Animatable;
  22986. })();
  22987. BABYLON.Animatable = Animatable;
  22988. })(BABYLON || (BABYLON = {}));
  22989. var BABYLON;
  22990. (function (BABYLON) {
  22991. var EasingFunction = (function () {
  22992. function EasingFunction() {
  22993. // Properties
  22994. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22995. }
  22996. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22997. get: function () {
  22998. return EasingFunction._EASINGMODE_EASEIN;
  22999. },
  23000. enumerable: true,
  23001. configurable: true
  23002. });
  23003. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23004. get: function () {
  23005. return EasingFunction._EASINGMODE_EASEOUT;
  23006. },
  23007. enumerable: true,
  23008. configurable: true
  23009. });
  23010. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23011. get: function () {
  23012. return EasingFunction._EASINGMODE_EASEINOUT;
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23018. var n = Math.min(Math.max(easingMode, 0), 2);
  23019. this._easingMode = n;
  23020. };
  23021. EasingFunction.prototype.getEasingMode = function () {
  23022. return this._easingMode;
  23023. };
  23024. EasingFunction.prototype.easeInCore = function (gradient) {
  23025. throw new Error('You must implement this method');
  23026. };
  23027. EasingFunction.prototype.ease = function (gradient) {
  23028. switch (this._easingMode) {
  23029. case EasingFunction.EASINGMODE_EASEIN:
  23030. return this.easeInCore(gradient);
  23031. case EasingFunction.EASINGMODE_EASEOUT:
  23032. return (1 - this.easeInCore(1 - gradient));
  23033. }
  23034. if (gradient >= 0.5) {
  23035. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23036. }
  23037. return (this.easeInCore(gradient * 2) * 0.5);
  23038. };
  23039. //Statics
  23040. EasingFunction._EASINGMODE_EASEIN = 0;
  23041. EasingFunction._EASINGMODE_EASEOUT = 1;
  23042. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23043. return EasingFunction;
  23044. })();
  23045. BABYLON.EasingFunction = EasingFunction;
  23046. var CircleEase = (function (_super) {
  23047. __extends(CircleEase, _super);
  23048. function CircleEase() {
  23049. _super.apply(this, arguments);
  23050. }
  23051. CircleEase.prototype.easeInCore = function (gradient) {
  23052. gradient = Math.max(0, Math.min(1, gradient));
  23053. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23054. };
  23055. return CircleEase;
  23056. })(EasingFunction);
  23057. BABYLON.CircleEase = CircleEase;
  23058. var BackEase = (function (_super) {
  23059. __extends(BackEase, _super);
  23060. function BackEase(amplitude) {
  23061. if (amplitude === void 0) { amplitude = 1; }
  23062. _super.call(this);
  23063. this.amplitude = amplitude;
  23064. }
  23065. BackEase.prototype.easeInCore = function (gradient) {
  23066. var num = Math.max(0, this.amplitude);
  23067. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23068. };
  23069. return BackEase;
  23070. })(EasingFunction);
  23071. BABYLON.BackEase = BackEase;
  23072. var BounceEase = (function (_super) {
  23073. __extends(BounceEase, _super);
  23074. function BounceEase(bounces, bounciness) {
  23075. if (bounces === void 0) { bounces = 3; }
  23076. if (bounciness === void 0) { bounciness = 2; }
  23077. _super.call(this);
  23078. this.bounces = bounces;
  23079. this.bounciness = bounciness;
  23080. }
  23081. BounceEase.prototype.easeInCore = function (gradient) {
  23082. var y = Math.max(0.0, this.bounces);
  23083. var bounciness = this.bounciness;
  23084. if (bounciness <= 1.0) {
  23085. bounciness = 1.001;
  23086. }
  23087. var num9 = Math.pow(bounciness, y);
  23088. var num5 = 1.0 - bounciness;
  23089. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23090. var num15 = gradient * num4;
  23091. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23092. var num3 = Math.floor(num65);
  23093. var num13 = num3 + 1.0;
  23094. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23095. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23096. var num7 = (num8 + num12) * 0.5;
  23097. var num6 = gradient - num7;
  23098. var num2 = num7 - num8;
  23099. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23100. };
  23101. return BounceEase;
  23102. })(EasingFunction);
  23103. BABYLON.BounceEase = BounceEase;
  23104. var CubicEase = (function (_super) {
  23105. __extends(CubicEase, _super);
  23106. function CubicEase() {
  23107. _super.apply(this, arguments);
  23108. }
  23109. CubicEase.prototype.easeInCore = function (gradient) {
  23110. return (gradient * gradient * gradient);
  23111. };
  23112. return CubicEase;
  23113. })(EasingFunction);
  23114. BABYLON.CubicEase = CubicEase;
  23115. var ElasticEase = (function (_super) {
  23116. __extends(ElasticEase, _super);
  23117. function ElasticEase(oscillations, springiness) {
  23118. if (oscillations === void 0) { oscillations = 3; }
  23119. if (springiness === void 0) { springiness = 3; }
  23120. _super.call(this);
  23121. this.oscillations = oscillations;
  23122. this.springiness = springiness;
  23123. }
  23124. ElasticEase.prototype.easeInCore = function (gradient) {
  23125. var num2;
  23126. var num3 = Math.max(0.0, this.oscillations);
  23127. var num = Math.max(0.0, this.springiness);
  23128. if (num == 0) {
  23129. num2 = gradient;
  23130. }
  23131. else {
  23132. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23133. }
  23134. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23135. };
  23136. return ElasticEase;
  23137. })(EasingFunction);
  23138. BABYLON.ElasticEase = ElasticEase;
  23139. var ExponentialEase = (function (_super) {
  23140. __extends(ExponentialEase, _super);
  23141. function ExponentialEase(exponent) {
  23142. if (exponent === void 0) { exponent = 2; }
  23143. _super.call(this);
  23144. this.exponent = exponent;
  23145. }
  23146. ExponentialEase.prototype.easeInCore = function (gradient) {
  23147. if (this.exponent <= 0) {
  23148. return gradient;
  23149. }
  23150. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23151. };
  23152. return ExponentialEase;
  23153. })(EasingFunction);
  23154. BABYLON.ExponentialEase = ExponentialEase;
  23155. var PowerEase = (function (_super) {
  23156. __extends(PowerEase, _super);
  23157. function PowerEase(power) {
  23158. if (power === void 0) { power = 2; }
  23159. _super.call(this);
  23160. this.power = power;
  23161. }
  23162. PowerEase.prototype.easeInCore = function (gradient) {
  23163. var y = Math.max(0.0, this.power);
  23164. return Math.pow(gradient, y);
  23165. };
  23166. return PowerEase;
  23167. })(EasingFunction);
  23168. BABYLON.PowerEase = PowerEase;
  23169. var QuadraticEase = (function (_super) {
  23170. __extends(QuadraticEase, _super);
  23171. function QuadraticEase() {
  23172. _super.apply(this, arguments);
  23173. }
  23174. QuadraticEase.prototype.easeInCore = function (gradient) {
  23175. return (gradient * gradient);
  23176. };
  23177. return QuadraticEase;
  23178. })(EasingFunction);
  23179. BABYLON.QuadraticEase = QuadraticEase;
  23180. var QuarticEase = (function (_super) {
  23181. __extends(QuarticEase, _super);
  23182. function QuarticEase() {
  23183. _super.apply(this, arguments);
  23184. }
  23185. QuarticEase.prototype.easeInCore = function (gradient) {
  23186. return (gradient * gradient * gradient * gradient);
  23187. };
  23188. return QuarticEase;
  23189. })(EasingFunction);
  23190. BABYLON.QuarticEase = QuarticEase;
  23191. var QuinticEase = (function (_super) {
  23192. __extends(QuinticEase, _super);
  23193. function QuinticEase() {
  23194. _super.apply(this, arguments);
  23195. }
  23196. QuinticEase.prototype.easeInCore = function (gradient) {
  23197. return (gradient * gradient * gradient * gradient * gradient);
  23198. };
  23199. return QuinticEase;
  23200. })(EasingFunction);
  23201. BABYLON.QuinticEase = QuinticEase;
  23202. var SineEase = (function (_super) {
  23203. __extends(SineEase, _super);
  23204. function SineEase() {
  23205. _super.apply(this, arguments);
  23206. }
  23207. SineEase.prototype.easeInCore = function (gradient) {
  23208. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23209. };
  23210. return SineEase;
  23211. })(EasingFunction);
  23212. BABYLON.SineEase = SineEase;
  23213. var BezierCurveEase = (function (_super) {
  23214. __extends(BezierCurveEase, _super);
  23215. function BezierCurveEase(x1, y1, x2, y2) {
  23216. if (x1 === void 0) { x1 = 0; }
  23217. if (y1 === void 0) { y1 = 0; }
  23218. if (x2 === void 0) { x2 = 1; }
  23219. if (y2 === void 0) { y2 = 1; }
  23220. _super.call(this);
  23221. this.x1 = x1;
  23222. this.y1 = y1;
  23223. this.x2 = x2;
  23224. this.y2 = y2;
  23225. }
  23226. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23227. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23228. };
  23229. return BezierCurveEase;
  23230. })(EasingFunction);
  23231. BABYLON.BezierCurveEase = BezierCurveEase;
  23232. })(BABYLON || (BABYLON = {}));
  23233. var BABYLON;
  23234. (function (BABYLON) {
  23235. var Bone = (function (_super) {
  23236. __extends(Bone, _super);
  23237. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23238. _super.call(this, name, skeleton.getScene());
  23239. this.name = name;
  23240. this.children = new Array();
  23241. this.animations = new Array();
  23242. this._worldTransform = new BABYLON.Matrix();
  23243. this._absoluteTransform = new BABYLON.Matrix();
  23244. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23245. this._skeleton = skeleton;
  23246. this._matrix = matrix;
  23247. this._baseMatrix = matrix;
  23248. this._restPose = restPose ? restPose : matrix.clone();
  23249. skeleton.bones.push(this);
  23250. if (parentBone) {
  23251. this._parent = parentBone;
  23252. parentBone.children.push(this);
  23253. }
  23254. else {
  23255. this._parent = null;
  23256. }
  23257. this._updateDifferenceMatrix();
  23258. }
  23259. // Members
  23260. Bone.prototype.getParent = function () {
  23261. return this._parent;
  23262. };
  23263. Bone.prototype.getLocalMatrix = function () {
  23264. return this._matrix;
  23265. };
  23266. Bone.prototype.getBaseMatrix = function () {
  23267. return this._baseMatrix;
  23268. };
  23269. Bone.prototype.getRestPose = function () {
  23270. return this._restPose;
  23271. };
  23272. Bone.prototype.returnToRest = function () {
  23273. this.updateMatrix(this._restPose.clone());
  23274. };
  23275. Bone.prototype.getWorldMatrix = function () {
  23276. return this._worldTransform;
  23277. };
  23278. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23279. return this._invertedAbsoluteTransform;
  23280. };
  23281. Bone.prototype.getAbsoluteTransform = function () {
  23282. return this._absoluteTransform;
  23283. };
  23284. // Methods
  23285. Bone.prototype.updateMatrix = function (matrix) {
  23286. this._baseMatrix = matrix.clone();
  23287. this._matrix = matrix.clone();
  23288. this._skeleton._markAsDirty();
  23289. this._updateDifferenceMatrix();
  23290. };
  23291. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23292. if (!rootMatrix) {
  23293. rootMatrix = this._baseMatrix;
  23294. }
  23295. if (this._parent) {
  23296. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23297. }
  23298. else {
  23299. this._absoluteTransform.copyFrom(rootMatrix);
  23300. }
  23301. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23302. for (var index = 0; index < this.children.length; index++) {
  23303. this.children[index]._updateDifferenceMatrix();
  23304. }
  23305. };
  23306. Bone.prototype.markAsDirty = function () {
  23307. this._currentRenderId++;
  23308. this._skeleton._markAsDirty();
  23309. };
  23310. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23311. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23312. // all animation may be coming from a library skeleton, so may need to create animation
  23313. if (this.animations.length === 0) {
  23314. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23315. }
  23316. // get animation info / verify there is such a range from the source bone
  23317. var sourceRange = source.animations[0].getRange(rangeName);
  23318. if (!sourceRange) {
  23319. return false;
  23320. }
  23321. var from = sourceRange.from;
  23322. var to = sourceRange.to;
  23323. var sourceKeys = source.animations[0].getKeys();
  23324. // rescaling prep
  23325. var sourceBoneLength = source.length;
  23326. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23327. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23328. var destKeys = this.animations[0].getKeys();
  23329. // loop vars declaration / initialization
  23330. var orig;
  23331. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23332. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23333. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23334. var mat;
  23335. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23336. orig = sourceKeys[key];
  23337. if (orig.frame >= from && orig.frame <= to) {
  23338. if (scalingReqd) {
  23339. orig.value.decompose(origScale, origRotation, origTranslation);
  23340. origTranslation.scaleInPlace(ratio);
  23341. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23342. }
  23343. else {
  23344. mat = orig.value;
  23345. }
  23346. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23347. }
  23348. }
  23349. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23350. return true;
  23351. };
  23352. return Bone;
  23353. })(BABYLON.Node);
  23354. BABYLON.Bone = Bone;
  23355. })(BABYLON || (BABYLON = {}));
  23356. var BABYLON;
  23357. (function (BABYLON) {
  23358. var Skeleton = (function () {
  23359. function Skeleton(name, id, scene) {
  23360. this.name = name;
  23361. this.id = id;
  23362. this.bones = new Array();
  23363. this.needInitialSkinMatrix = false;
  23364. this._isDirty = true;
  23365. this._meshesWithPoseMatrix = new Array();
  23366. this._identity = BABYLON.Matrix.Identity();
  23367. this._ranges = {};
  23368. this.bones = [];
  23369. this._scene = scene;
  23370. scene.skeletons.push(this);
  23371. this.prepare();
  23372. //make sure it will recalculate the matrix next time prepare is called.
  23373. this._isDirty = true;
  23374. }
  23375. // Members
  23376. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23377. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23378. return mesh._bonesTransformMatrices;
  23379. }
  23380. return this._transformMatrices;
  23381. };
  23382. Skeleton.prototype.getScene = function () {
  23383. return this._scene;
  23384. };
  23385. // Methods
  23386. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23387. // check name not already in use
  23388. if (!this._ranges[name]) {
  23389. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23390. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23391. if (this.bones[i].animations[0]) {
  23392. this.bones[i].animations[0].createRange(name, from, to);
  23393. }
  23394. }
  23395. }
  23396. };
  23397. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23398. if (deleteFrames === void 0) { deleteFrames = true; }
  23399. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23400. if (this.bones[i].animations[0]) {
  23401. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23402. }
  23403. }
  23404. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23405. };
  23406. Skeleton.prototype.getAnimationRange = function (name) {
  23407. return this._ranges[name];
  23408. };
  23409. /**
  23410. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23411. */
  23412. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23413. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23414. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23415. return false;
  23416. }
  23417. var ret = true;
  23418. var frameOffset = this._getHighestAnimationFrame() + 1;
  23419. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23420. var boneDict = {};
  23421. var sourceBones = source.bones;
  23422. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23423. boneDict[sourceBones[i].name] = sourceBones[i];
  23424. }
  23425. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23426. var boneName = this.bones[i].name;
  23427. var sourceBone = boneDict[boneName];
  23428. if (sourceBone) {
  23429. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23430. }
  23431. else {
  23432. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23433. ret = false;
  23434. }
  23435. }
  23436. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23437. var range = source.getAnimationRange(name);
  23438. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23439. return ret;
  23440. };
  23441. Skeleton.prototype.returnToRest = function () {
  23442. for (var index = 0; index < this.bones.length; index++) {
  23443. this.bones[index].returnToRest();
  23444. }
  23445. };
  23446. Skeleton.prototype._getHighestAnimationFrame = function () {
  23447. var ret = 0;
  23448. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23449. if (this.bones[i].animations[0]) {
  23450. var highest = this.bones[i].animations[0].getHighestFrame();
  23451. if (ret < highest) {
  23452. ret = highest;
  23453. }
  23454. }
  23455. }
  23456. return ret;
  23457. };
  23458. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23459. var range = this.getAnimationRange(name);
  23460. if (!range) {
  23461. return null;
  23462. }
  23463. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23464. };
  23465. Skeleton.prototype._markAsDirty = function () {
  23466. this._isDirty = true;
  23467. };
  23468. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23469. this._meshesWithPoseMatrix.push(mesh);
  23470. };
  23471. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23472. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23473. if (index > -1) {
  23474. this._meshesWithPoseMatrix.splice(index, 1);
  23475. }
  23476. };
  23477. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23478. for (var index = 0; index < this.bones.length; index++) {
  23479. var bone = this.bones[index];
  23480. var parentBone = bone.getParent();
  23481. if (parentBone) {
  23482. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23483. }
  23484. else {
  23485. if (initialSkinMatrix) {
  23486. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23487. }
  23488. else {
  23489. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23490. }
  23491. }
  23492. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23493. }
  23494. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23495. };
  23496. Skeleton.prototype.prepare = function () {
  23497. if (!this._isDirty) {
  23498. return;
  23499. }
  23500. if (this.needInitialSkinMatrix) {
  23501. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23502. var mesh = this._meshesWithPoseMatrix[index];
  23503. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23504. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23505. }
  23506. var poseMatrix = mesh.getPoseMatrix();
  23507. // Prepare bones
  23508. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23509. var bone = this.bones[boneIndex];
  23510. if (!bone.getParent()) {
  23511. var matrix = bone.getBaseMatrix();
  23512. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23513. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23514. }
  23515. }
  23516. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23517. }
  23518. }
  23519. else {
  23520. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23521. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23522. }
  23523. this._computeTransformMatrices(this._transformMatrices, null);
  23524. }
  23525. this._isDirty = false;
  23526. this._scene._activeBones += this.bones.length;
  23527. };
  23528. Skeleton.prototype.getAnimatables = function () {
  23529. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23530. this._animatables = [];
  23531. for (var index = 0; index < this.bones.length; index++) {
  23532. this._animatables.push(this.bones[index]);
  23533. }
  23534. }
  23535. return this._animatables;
  23536. };
  23537. Skeleton.prototype.clone = function (name, id) {
  23538. var result = new Skeleton(name, id || name, this._scene);
  23539. for (var index = 0; index < this.bones.length; index++) {
  23540. var source = this.bones[index];
  23541. var parentBone = null;
  23542. if (source.getParent()) {
  23543. var parentIndex = this.bones.indexOf(source.getParent());
  23544. parentBone = result.bones[parentIndex];
  23545. }
  23546. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23547. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23548. }
  23549. return result;
  23550. };
  23551. Skeleton.prototype.dispose = function () {
  23552. this._meshesWithPoseMatrix = [];
  23553. // Animations
  23554. this.getScene().stopAnimation(this);
  23555. // Remove from scene
  23556. this.getScene().removeSkeleton(this);
  23557. };
  23558. Skeleton.prototype.serialize = function () {
  23559. var serializationObject = {};
  23560. serializationObject.name = this.name;
  23561. serializationObject.id = this.id;
  23562. serializationObject.bones = [];
  23563. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23564. for (var index = 0; index < this.bones.length; index++) {
  23565. var bone = this.bones[index];
  23566. var serializedBone = {
  23567. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23568. name: bone.name,
  23569. matrix: bone.getLocalMatrix().toArray(),
  23570. rest: bone.getRestPose().toArray()
  23571. };
  23572. serializationObject.bones.push(serializedBone);
  23573. if (bone.length) {
  23574. serializedBone.length = bone.length;
  23575. }
  23576. if (bone.animations && bone.animations.length > 0) {
  23577. serializedBone.animation = bone.animations[0].serialize();
  23578. }
  23579. serializationObject.ranges = [];
  23580. for (var name in this._ranges) {
  23581. var range = {};
  23582. range.name = name;
  23583. range.from = this._ranges[name].from;
  23584. range.to = this._ranges[name].to;
  23585. serializationObject.ranges.push(range);
  23586. }
  23587. }
  23588. return serializationObject;
  23589. };
  23590. Skeleton.Parse = function (parsedSkeleton, scene) {
  23591. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23592. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23593. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23594. var parsedBone = parsedSkeleton.bones[index];
  23595. var parentBone = null;
  23596. if (parsedBone.parentBoneIndex > -1) {
  23597. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23598. }
  23599. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23600. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23601. if (parsedBone.length) {
  23602. bone.length = parsedBone.length;
  23603. }
  23604. if (parsedBone.animation) {
  23605. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23606. }
  23607. }
  23608. // placed after bones, so createAnimationRange can cascade down
  23609. if (parsedSkeleton.ranges) {
  23610. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23611. var data = parsedSkeleton.ranges[index];
  23612. skeleton.createAnimationRange(data.name, data.from, data.to);
  23613. }
  23614. }
  23615. return skeleton;
  23616. };
  23617. return Skeleton;
  23618. })();
  23619. BABYLON.Skeleton = Skeleton;
  23620. })(BABYLON || (BABYLON = {}));
  23621. var BABYLON;
  23622. (function (BABYLON) {
  23623. var PostProcess = (function () {
  23624. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23626. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23627. this.name = name;
  23628. this.width = -1;
  23629. this.height = -1;
  23630. this._reusable = false;
  23631. this._textures = new BABYLON.SmartArray(2);
  23632. this._currentRenderTextureInd = 0;
  23633. if (camera != null) {
  23634. this._camera = camera;
  23635. this._scene = camera.getScene();
  23636. camera.attachPostProcess(this);
  23637. this._engine = this._scene.getEngine();
  23638. }
  23639. else {
  23640. this._engine = engine;
  23641. }
  23642. this._renderRatio = ratio;
  23643. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23644. this._reusable = reusable || false;
  23645. this._textureType = textureType;
  23646. this._samplers = samplers || [];
  23647. this._samplers.push("textureSampler");
  23648. this._fragmentUrl = fragmentUrl;
  23649. this._parameters = parameters || [];
  23650. this.updateEffect(defines);
  23651. }
  23652. PostProcess.prototype.updateEffect = function (defines) {
  23653. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23654. };
  23655. PostProcess.prototype.isReusable = function () {
  23656. return this._reusable;
  23657. };
  23658. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23659. camera = camera || this._camera;
  23660. var scene = camera.getScene();
  23661. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23662. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23663. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23664. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23665. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23666. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23667. if (this._textures.length > 0) {
  23668. for (var i = 0; i < this._textures.length; i++) {
  23669. this._engine._releaseTexture(this._textures.data[i]);
  23670. }
  23671. this._textures.reset();
  23672. }
  23673. this.width = desiredWidth;
  23674. this.height = desiredHeight;
  23675. 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 }));
  23676. if (this._reusable) {
  23677. 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 }));
  23678. }
  23679. if (this.onSizeChanged) {
  23680. this.onSizeChanged();
  23681. }
  23682. }
  23683. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23684. if (this.onActivate) {
  23685. this.onActivate(camera);
  23686. }
  23687. // Clear
  23688. if (this.clearColor) {
  23689. this._engine.clear(this.clearColor, true, true);
  23690. }
  23691. else {
  23692. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23693. }
  23694. if (this._reusable) {
  23695. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23696. }
  23697. };
  23698. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23699. get: function () {
  23700. return this._effect.isSupported;
  23701. },
  23702. enumerable: true,
  23703. configurable: true
  23704. });
  23705. PostProcess.prototype.apply = function () {
  23706. // Check
  23707. if (!this._effect.isReady())
  23708. return null;
  23709. // States
  23710. this._engine.enableEffect(this._effect);
  23711. this._engine.setState(false);
  23712. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23713. this._engine.setDepthBuffer(false);
  23714. this._engine.setDepthWrite(false);
  23715. // Texture
  23716. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23717. // Parameters
  23718. if (this.onApply) {
  23719. this.onApply(this._effect);
  23720. }
  23721. return this._effect;
  23722. };
  23723. PostProcess.prototype.dispose = function (camera) {
  23724. camera = camera || this._camera;
  23725. if (this._textures.length > 0) {
  23726. for (var i = 0; i < this._textures.length; i++) {
  23727. this._engine._releaseTexture(this._textures.data[i]);
  23728. }
  23729. this._textures.reset();
  23730. }
  23731. if (!camera) {
  23732. return;
  23733. }
  23734. camera.detachPostProcess(this);
  23735. var index = camera._postProcesses.indexOf(this);
  23736. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23737. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23738. }
  23739. };
  23740. return PostProcess;
  23741. })();
  23742. BABYLON.PostProcess = PostProcess;
  23743. })(BABYLON || (BABYLON = {}));
  23744. var BABYLON;
  23745. (function (BABYLON) {
  23746. var PostProcessManager = (function () {
  23747. function PostProcessManager(scene) {
  23748. this._vertexDeclaration = [2];
  23749. this._vertexStrideSize = 2 * 4;
  23750. this._scene = scene;
  23751. }
  23752. PostProcessManager.prototype._prepareBuffers = function () {
  23753. if (this._vertexBuffer) {
  23754. return;
  23755. }
  23756. // VBO
  23757. var vertices = [];
  23758. vertices.push(1, 1);
  23759. vertices.push(-1, 1);
  23760. vertices.push(-1, -1);
  23761. vertices.push(1, -1);
  23762. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23763. // Indices
  23764. var indices = [];
  23765. indices.push(0);
  23766. indices.push(1);
  23767. indices.push(2);
  23768. indices.push(0);
  23769. indices.push(2);
  23770. indices.push(3);
  23771. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23772. };
  23773. // Methods
  23774. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23775. var postProcesses = this._scene.activeCamera._postProcesses;
  23776. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23777. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23778. return false;
  23779. }
  23780. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23781. return true;
  23782. };
  23783. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23784. var engine = this._scene.getEngine();
  23785. for (var index = 0; index < postProcesses.length; index++) {
  23786. if (index < postProcesses.length - 1) {
  23787. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23788. }
  23789. else {
  23790. if (targetTexture) {
  23791. engine.bindFramebuffer(targetTexture);
  23792. }
  23793. else {
  23794. engine.restoreDefaultFramebuffer();
  23795. }
  23796. }
  23797. var pp = postProcesses[index];
  23798. var effect = pp.apply();
  23799. if (effect) {
  23800. if (pp.onBeforeRender) {
  23801. pp.onBeforeRender(effect);
  23802. }
  23803. // VBOs
  23804. this._prepareBuffers();
  23805. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23806. // Draw order
  23807. engine.draw(true, 0, 6);
  23808. if (pp.onAfterRender) {
  23809. pp.onAfterRender(effect);
  23810. }
  23811. }
  23812. }
  23813. // Restore depth buffer
  23814. engine.setDepthBuffer(true);
  23815. engine.setDepthWrite(true);
  23816. };
  23817. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23818. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23819. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23820. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23821. return;
  23822. }
  23823. var engine = this._scene.getEngine();
  23824. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23825. if (index < postProcessesTakenIndices.length - 1) {
  23826. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23827. }
  23828. else {
  23829. if (targetTexture) {
  23830. engine.bindFramebuffer(targetTexture, faceIndex);
  23831. }
  23832. else {
  23833. engine.restoreDefaultFramebuffer();
  23834. }
  23835. }
  23836. if (doNotPresent) {
  23837. break;
  23838. }
  23839. var pp = postProcesses[postProcessesTakenIndices[index]];
  23840. var effect = pp.apply();
  23841. if (effect) {
  23842. if (pp.onBeforeRender) {
  23843. pp.onBeforeRender(effect);
  23844. }
  23845. // VBOs
  23846. this._prepareBuffers();
  23847. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23848. // Draw order
  23849. engine.draw(true, 0, 6);
  23850. if (pp.onAfterRender) {
  23851. pp.onAfterRender(effect);
  23852. }
  23853. }
  23854. }
  23855. // Restore depth buffer
  23856. engine.setDepthBuffer(true);
  23857. engine.setDepthWrite(true);
  23858. };
  23859. PostProcessManager.prototype.dispose = function () {
  23860. if (this._vertexBuffer) {
  23861. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23862. this._vertexBuffer = null;
  23863. }
  23864. if (this._indexBuffer) {
  23865. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23866. this._indexBuffer = null;
  23867. }
  23868. };
  23869. return PostProcessManager;
  23870. })();
  23871. BABYLON.PostProcessManager = PostProcessManager;
  23872. })(BABYLON || (BABYLON = {}));
  23873. var BABYLON;
  23874. (function (BABYLON) {
  23875. var PassPostProcess = (function (_super) {
  23876. __extends(PassPostProcess, _super);
  23877. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23878. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23879. }
  23880. return PassPostProcess;
  23881. })(BABYLON.PostProcess);
  23882. BABYLON.PassPostProcess = PassPostProcess;
  23883. })(BABYLON || (BABYLON = {}));
  23884. var BABYLON;
  23885. (function (BABYLON) {
  23886. var PhysicsJoint = (function () {
  23887. function PhysicsJoint(type, jointData) {
  23888. this.type = type;
  23889. this.jointData = jointData;
  23890. jointData.nativeParams = jointData.nativeParams || {};
  23891. }
  23892. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  23893. get: function () {
  23894. return this._physicsJoint;
  23895. },
  23896. set: function (newJoint) {
  23897. if (this._physicsJoint) {
  23898. }
  23899. this._physicsJoint = newJoint;
  23900. },
  23901. enumerable: true,
  23902. configurable: true
  23903. });
  23904. //TODO check if the native joints are the same
  23905. //Joint Types
  23906. PhysicsJoint.DistanceJoint = 0;
  23907. PhysicsJoint.HingeJoint = 1;
  23908. PhysicsJoint.BallAndSocketJoint = 2;
  23909. PhysicsJoint.WheelJoint = 3;
  23910. PhysicsJoint.SliderJoint = 4;
  23911. //OIMO
  23912. PhysicsJoint.PrismaticJoint = 5;
  23913. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  23914. PhysicsJoint.UniversalJoint = 6;
  23915. PhysicsJoint.Hinge2Joint = 7;
  23916. //Cannon
  23917. //Similar to a Ball-Joint. Different in params
  23918. //TODO check!!
  23919. PhysicsJoint.PointToPointJoint = 8;
  23920. return PhysicsJoint;
  23921. })();
  23922. BABYLON.PhysicsJoint = PhysicsJoint;
  23923. })(BABYLON || (BABYLON = {}));
  23924. var BABYLON;
  23925. (function (BABYLON) {
  23926. var PhysicsImpostor = (function () {
  23927. function PhysicsImpostor(_mesh, type, _options) {
  23928. var _this = this;
  23929. if (_options === void 0) { _options = { mass: 0 }; }
  23930. this._mesh = _mesh;
  23931. this.type = type;
  23932. this._options = _options;
  23933. this._bodyUpdateRequired = false;
  23934. this._onBeforePhysicsStepCallbacks = new Array();
  23935. this._onAfterPhysicsStepCallbacks = new Array();
  23936. this._onPhysicsCollideCallbacks = [];
  23937. this._deltaPosition = BABYLON.Vector3.Zero();
  23938. this._deltaRotation = new BABYLON.Quaternion();
  23939. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  23940. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  23941. /**
  23942. * this function is executed by the physics engine.
  23943. */
  23944. this.beforeStep = function () {
  23945. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  23946. //conjugate deltaRotation
  23947. _this._tmpRotationWithDelta.copyFrom(_this._deltaRotation);
  23948. _this._tmpRotationWithDelta.multiplyInPlace(_this.mesh.rotationQuaternion);
  23949. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  23950. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  23951. func(_this);
  23952. });
  23953. };
  23954. /**
  23955. * this function is executed by the physics engine.
  23956. */
  23957. this.afterStep = function () {
  23958. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  23959. func(_this);
  23960. });
  23961. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  23962. _this.mesh.position.addInPlace(_this._deltaPosition);
  23963. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  23964. };
  23965. //event and body object due to cannon's event-based architecture.
  23966. this.onCollide = function (e) {
  23967. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  23968. if (otherImpostor) {
  23969. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  23970. return obj.otherImpostor === otherImpostor;
  23971. }).forEach(function (obj) {
  23972. obj.callback(_this, obj.otherImpostor);
  23973. });
  23974. }
  23975. };
  23976. //default options params
  23977. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  23978. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  23979. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  23980. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  23981. this._joints = [];
  23982. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  23983. if (!this._mesh.parent) {
  23984. this._init();
  23985. }
  23986. }
  23987. /**
  23988. * This function will completly initialize this impostor.
  23989. * It will create a new body - but only if this mesh has no parent.
  23990. * If it has, this impostor will not be used other than to define the impostor
  23991. * of the child mesh.
  23992. */
  23993. PhysicsImpostor.prototype._init = function () {
  23994. this._physicsEngine.removeImpostor(this);
  23995. this.physicsBody = null;
  23996. this._parent = this._parent || this._getPhysicsParent();
  23997. if (!this.parent) {
  23998. this._physicsEngine.addImpostor(this);
  23999. }
  24000. };
  24001. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24002. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24003. var parentMesh = this.mesh.parent;
  24004. return parentMesh.getPhysicsImpostor();
  24005. }
  24006. return;
  24007. };
  24008. /**
  24009. * Should a new body be generated.
  24010. */
  24011. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24012. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24013. };
  24014. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24015. this.forceUpdate();
  24016. };
  24017. /**
  24018. * Force a regeneration of this or the parent's impostor's body.
  24019. * Use under cautious - This will remove all joints already implemented.
  24020. */
  24021. PhysicsImpostor.prototype.forceUpdate = function () {
  24022. this._init();
  24023. if (this.parent) {
  24024. this.parent.forceUpdate();
  24025. }
  24026. };
  24027. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24028. get: function () {
  24029. return this._mesh;
  24030. },
  24031. enumerable: true,
  24032. configurable: true
  24033. });
  24034. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24035. /**
  24036. * Gets the body that holds this impostor. Either its own, or its parent.
  24037. */
  24038. get: function () {
  24039. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24040. },
  24041. /**
  24042. * Set the physics body. Used mainly by the physics engine/plugin
  24043. */
  24044. set: function (physicsBody) {
  24045. if (this._physicsBody) {
  24046. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24047. }
  24048. this._physicsBody = physicsBody;
  24049. this.resetUpdateFlags();
  24050. },
  24051. enumerable: true,
  24052. configurable: true
  24053. });
  24054. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24055. get: function () {
  24056. return this._parent;
  24057. },
  24058. enumerable: true,
  24059. configurable: true
  24060. });
  24061. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24062. this._bodyUpdateRequired = false;
  24063. };
  24064. /**
  24065. * Get a specific parametes from the options parameter.
  24066. */
  24067. PhysicsImpostor.prototype.getParam = function (paramName) {
  24068. return this._options[paramName];
  24069. };
  24070. /**
  24071. * Sets a specific parameter in the options given to the physics plugin
  24072. */
  24073. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24074. this._options[paramName] = value;
  24075. this._bodyUpdateRequired = true;
  24076. };
  24077. /**
  24078. * Set the body's velocity.
  24079. */
  24080. PhysicsImpostor.prototype.setVelocity = function (velocity) {
  24081. this._physicsEngine.getPhysicsPlugin().setVelocity(this, velocity);
  24082. };
  24083. /**
  24084. * Execute a function with the physics plugin native code.
  24085. * Provide a function the will have two variables - the world object and the physics body object.
  24086. */
  24087. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24088. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24089. };
  24090. /**
  24091. * Register a function that will be executed before the physics world is stepping forward.
  24092. */
  24093. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24094. this._onBeforePhysicsStepCallbacks.push(func);
  24095. };
  24096. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24097. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24098. if (index > -1) {
  24099. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24100. }
  24101. else {
  24102. BABYLON.Tools.Warn("Function to remove was not found");
  24103. }
  24104. };
  24105. /**
  24106. * Register a function that will be executed after the physics step
  24107. */
  24108. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24109. this._onAfterPhysicsStepCallbacks.push(func);
  24110. };
  24111. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24112. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24113. if (index > -1) {
  24114. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24115. }
  24116. else {
  24117. BABYLON.Tools.Warn("Function to remove was not found");
  24118. }
  24119. };
  24120. /**
  24121. * register a function that will be executed when this impostor collides against a different body.
  24122. */
  24123. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24124. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostor: collideAgainst });
  24125. };
  24126. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24127. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostor: collideAgainst });
  24128. if (index > -1) {
  24129. this._onPhysicsCollideCallbacks.splice(index, 1);
  24130. }
  24131. else {
  24132. BABYLON.Tools.Warn("Function to remove was not found");
  24133. }
  24134. };
  24135. /**
  24136. * Apply a force
  24137. */
  24138. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24139. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24140. };
  24141. /**
  24142. * Apply an impulse
  24143. */
  24144. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24145. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24146. };
  24147. /**
  24148. * A help function to create a joint.
  24149. */
  24150. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24151. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24152. this.addJoint(otherImpostor, joint);
  24153. };
  24154. /**
  24155. * Add a joint to this impostor with a different impostor.
  24156. */
  24157. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24158. this._joints.push({
  24159. otherImpostor: otherImpostor,
  24160. joint: joint
  24161. });
  24162. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24163. };
  24164. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24165. if (disposeChildren === void 0) { disposeChildren = true; }
  24166. this.physicsBody = null;
  24167. if (this.parent) {
  24168. this.parent.forceUpdate();
  24169. }
  24170. else {
  24171. this.mesh.getChildMeshes().forEach(function (mesh) {
  24172. if (mesh.physicsImpostor) {
  24173. if (disposeChildren) {
  24174. mesh.physicsImpostor.dispose();
  24175. mesh.physicsImpostor = null;
  24176. }
  24177. }
  24178. });
  24179. }
  24180. };
  24181. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24182. this._deltaPosition.copyFrom(position);
  24183. };
  24184. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24185. this._deltaRotation.copyFrom(rotation);
  24186. };
  24187. //Impostor types
  24188. PhysicsImpostor.NoImpostor = 0;
  24189. PhysicsImpostor.SphereImpostor = 1;
  24190. PhysicsImpostor.BoxImpostor = 2;
  24191. PhysicsImpostor.PlaneImpostor = 3;
  24192. PhysicsImpostor.MeshImpostor = 4;
  24193. PhysicsImpostor.CapsuleImpostor = 5;
  24194. PhysicsImpostor.ConeImpostor = 6;
  24195. PhysicsImpostor.CylinderImpostor = 7;
  24196. PhysicsImpostor.ConvexHullImpostor = 8;
  24197. PhysicsImpostor.HeightmapImpostor = 9;
  24198. return PhysicsImpostor;
  24199. })();
  24200. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24201. })(BABYLON || (BABYLON = {}));
  24202. var BABYLON;
  24203. (function (BABYLON) {
  24204. var PhysicsEngine = (function () {
  24205. function PhysicsEngine(gravity, _physicsPlugin) {
  24206. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24207. this._physicsPlugin = _physicsPlugin;
  24208. //new methods and parameters
  24209. this._impostors = [];
  24210. this._joints = [];
  24211. if (!this._physicsPlugin.isSupported()) {
  24212. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24213. + "Please make sure it is included.");
  24214. }
  24215. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24216. this.setGravity(gravity);
  24217. }
  24218. PhysicsEngine.prototype.setGravity = function (gravity) {
  24219. this.gravity = gravity;
  24220. this._physicsPlugin.setGravity(this.gravity);
  24221. };
  24222. PhysicsEngine.prototype.dispose = function () {
  24223. this._impostors.forEach(function (impostor) {
  24224. impostor.dispose();
  24225. });
  24226. this._physicsPlugin.dispose();
  24227. };
  24228. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24229. return this._physicsPlugin.name;
  24230. };
  24231. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24232. this._impostors.push(impostor);
  24233. //if no parent, generate the body
  24234. if (!impostor.parent) {
  24235. this._physicsPlugin.generatePhysicsBody(impostor);
  24236. }
  24237. };
  24238. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24239. var index = this._impostors.indexOf(impostor);
  24240. if (index > -1) {
  24241. var removed = this._impostors.splice(index, 1);
  24242. //Is it needed?
  24243. if (removed.length) {
  24244. //this will also remove it from the world.
  24245. removed[0].physicsBody = null;
  24246. }
  24247. }
  24248. };
  24249. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24250. var impostorJoint = {
  24251. mainImpostor: mainImpostor,
  24252. connectedImpostor: connectedImpostor,
  24253. joint: joint
  24254. };
  24255. this._joints.push(impostorJoint);
  24256. this._physicsPlugin.generateJoint(impostorJoint);
  24257. };
  24258. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24259. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24260. return (impostorJoint.connectedImpostor === connectedImpostor
  24261. && impostorJoint.joint === joint
  24262. && impostorJoint.mainImpostor === mainImpostor);
  24263. });
  24264. if (matchingJoints.length) {
  24265. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24266. }
  24267. };
  24268. /**
  24269. * Called by the scene. no need to call it.
  24270. */
  24271. PhysicsEngine.prototype._step = function (delta) {
  24272. var _this = this;
  24273. //check if any mesh has no body / requires an update
  24274. this._impostors.forEach(function (impostor) {
  24275. if (impostor.isBodyInitRequired()) {
  24276. _this._physicsPlugin.generatePhysicsBody(impostor);
  24277. }
  24278. });
  24279. if (delta > 0.1) {
  24280. delta = 0.1;
  24281. }
  24282. else if (delta <= 0) {
  24283. delta = 1.0 / 60.0;
  24284. }
  24285. this._physicsPlugin.executeStep(delta, this._impostors);
  24286. };
  24287. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24288. return this._physicsPlugin;
  24289. };
  24290. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24291. for (var i = 0; i < this._impostors.length; ++i) {
  24292. if (this._impostors[i].physicsBody === body) {
  24293. return this._impostors[i];
  24294. }
  24295. }
  24296. };
  24297. // Statics, Legacy support.
  24298. /**
  24299. * @Deprecated
  24300. *
  24301. */
  24302. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24303. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24304. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24305. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24306. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24307. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24308. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24309. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24310. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24311. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24312. PhysicsEngine.Epsilon = 0.001;
  24313. return PhysicsEngine;
  24314. })();
  24315. BABYLON.PhysicsEngine = PhysicsEngine;
  24316. })(BABYLON || (BABYLON = {}));
  24317. var BABYLON;
  24318. (function (BABYLON) {
  24319. var VertexData = (function () {
  24320. function VertexData() {
  24321. }
  24322. VertexData.prototype.set = function (data, kind) {
  24323. switch (kind) {
  24324. case BABYLON.VertexBuffer.PositionKind:
  24325. this.positions = data;
  24326. break;
  24327. case BABYLON.VertexBuffer.NormalKind:
  24328. this.normals = data;
  24329. break;
  24330. case BABYLON.VertexBuffer.UVKind:
  24331. this.uvs = data;
  24332. break;
  24333. case BABYLON.VertexBuffer.UV2Kind:
  24334. this.uvs2 = data;
  24335. break;
  24336. case BABYLON.VertexBuffer.UV3Kind:
  24337. this.uvs3 = data;
  24338. break;
  24339. case BABYLON.VertexBuffer.UV4Kind:
  24340. this.uvs4 = data;
  24341. break;
  24342. case BABYLON.VertexBuffer.UV5Kind:
  24343. this.uvs5 = data;
  24344. break;
  24345. case BABYLON.VertexBuffer.UV6Kind:
  24346. this.uvs6 = data;
  24347. break;
  24348. case BABYLON.VertexBuffer.ColorKind:
  24349. this.colors = data;
  24350. break;
  24351. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24352. this.matricesIndices = data;
  24353. break;
  24354. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24355. this.matricesWeights = data;
  24356. break;
  24357. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24358. this.matricesIndicesExtra = data;
  24359. break;
  24360. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24361. this.matricesWeightsExtra = data;
  24362. break;
  24363. }
  24364. };
  24365. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24366. this._applyTo(mesh, updatable);
  24367. };
  24368. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24369. this._applyTo(geometry, updatable);
  24370. };
  24371. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24372. this._update(mesh);
  24373. };
  24374. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24375. this._update(geometry);
  24376. };
  24377. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24378. if (this.positions) {
  24379. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24380. }
  24381. if (this.normals) {
  24382. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24383. }
  24384. if (this.uvs) {
  24385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24386. }
  24387. if (this.uvs2) {
  24388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24389. }
  24390. if (this.uvs3) {
  24391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24392. }
  24393. if (this.uvs4) {
  24394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24395. }
  24396. if (this.uvs5) {
  24397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24398. }
  24399. if (this.uvs6) {
  24400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24401. }
  24402. if (this.colors) {
  24403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24404. }
  24405. if (this.matricesIndices) {
  24406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24407. }
  24408. if (this.matricesWeights) {
  24409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24410. }
  24411. if (this.matricesIndicesExtra) {
  24412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24413. }
  24414. if (this.matricesWeightsExtra) {
  24415. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24416. }
  24417. if (this.indices) {
  24418. meshOrGeometry.setIndices(this.indices);
  24419. }
  24420. };
  24421. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24422. if (this.positions) {
  24423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24424. }
  24425. if (this.normals) {
  24426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24427. }
  24428. if (this.uvs) {
  24429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24430. }
  24431. if (this.uvs2) {
  24432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24433. }
  24434. if (this.uvs3) {
  24435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24436. }
  24437. if (this.uvs4) {
  24438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24439. }
  24440. if (this.uvs5) {
  24441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24442. }
  24443. if (this.uvs6) {
  24444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24445. }
  24446. if (this.colors) {
  24447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24448. }
  24449. if (this.matricesIndices) {
  24450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24451. }
  24452. if (this.matricesWeights) {
  24453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24454. }
  24455. if (this.matricesIndicesExtra) {
  24456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24457. }
  24458. if (this.matricesWeightsExtra) {
  24459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24460. }
  24461. if (this.indices) {
  24462. meshOrGeometry.setIndices(this.indices);
  24463. }
  24464. };
  24465. VertexData.prototype.transform = function (matrix) {
  24466. var transformed = BABYLON.Vector3.Zero();
  24467. var index;
  24468. if (this.positions) {
  24469. var position = BABYLON.Vector3.Zero();
  24470. for (index = 0; index < this.positions.length; index += 3) {
  24471. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24472. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24473. this.positions[index] = transformed.x;
  24474. this.positions[index + 1] = transformed.y;
  24475. this.positions[index + 2] = transformed.z;
  24476. }
  24477. }
  24478. if (this.normals) {
  24479. var normal = BABYLON.Vector3.Zero();
  24480. for (index = 0; index < this.normals.length; index += 3) {
  24481. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24482. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24483. this.normals[index] = transformed.x;
  24484. this.normals[index + 1] = transformed.y;
  24485. this.normals[index + 2] = transformed.z;
  24486. }
  24487. }
  24488. };
  24489. VertexData.prototype.merge = function (other) {
  24490. if (other.indices) {
  24491. if (!this.indices) {
  24492. this.indices = [];
  24493. }
  24494. var offset = this.positions ? this.positions.length / 3 : 0;
  24495. for (var index = 0; index < other.indices.length; index++) {
  24496. //TODO check type - if Int32Array!
  24497. this.indices.push(other.indices[index] + offset);
  24498. }
  24499. }
  24500. this.positions = this._mergeElement(this.positions, other.positions);
  24501. this.normals = this._mergeElement(this.normals, other.normals);
  24502. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24503. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24504. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24505. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24506. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24507. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24508. this.colors = this._mergeElement(this.colors, other.colors);
  24509. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24510. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24511. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24512. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24513. };
  24514. VertexData.prototype._mergeElement = function (source, other) {
  24515. if (!other)
  24516. return source;
  24517. if (!source)
  24518. return other;
  24519. var len = other.length + source.length;
  24520. var isSrcTypedArray = source instanceof Float32Array;
  24521. var isOthTypedArray = other instanceof Float32Array;
  24522. // use non-loop method when the source is Float32Array
  24523. if (isSrcTypedArray) {
  24524. var ret32 = new Float32Array(len);
  24525. ret32.set(source);
  24526. ret32.set(other, source.length);
  24527. return ret32;
  24528. }
  24529. else if (!isOthTypedArray) {
  24530. return source.concat(other);
  24531. }
  24532. else {
  24533. var ret = source.slice(0); // copy source to a separate array
  24534. for (var i = 0, len = other.length; i < len; i++) {
  24535. ret.push(other[i]);
  24536. }
  24537. return ret;
  24538. }
  24539. };
  24540. VertexData.prototype.serialize = function () {
  24541. var serializationObject = this.serialize();
  24542. if (this.positions) {
  24543. serializationObject.positions = this.positions;
  24544. }
  24545. if (this.normals) {
  24546. serializationObject.normals = this.normals;
  24547. }
  24548. if (this.uvs) {
  24549. serializationObject.uvs = this.uvs;
  24550. }
  24551. if (this.uvs2) {
  24552. serializationObject.uvs2 = this.uvs2;
  24553. }
  24554. if (this.uvs3) {
  24555. serializationObject.uvs3 = this.uvs3;
  24556. }
  24557. if (this.uvs4) {
  24558. serializationObject.uvs4 = this.uvs4;
  24559. }
  24560. if (this.uvs5) {
  24561. serializationObject.uvs5 = this.uvs5;
  24562. }
  24563. if (this.uvs6) {
  24564. serializationObject.uvs6 = this.uvs6;
  24565. }
  24566. if (this.colors) {
  24567. serializationObject.colors = this.colors;
  24568. }
  24569. if (this.matricesIndices) {
  24570. serializationObject.matricesIndices = this.matricesIndices;
  24571. serializationObject.matricesIndices._isExpanded = true;
  24572. }
  24573. if (this.matricesWeights) {
  24574. serializationObject.matricesWeights = this.matricesWeights;
  24575. }
  24576. if (this.matricesIndicesExtra) {
  24577. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24578. serializationObject.matricesIndicesExtra._isExpanded = true;
  24579. }
  24580. if (this.matricesWeightsExtra) {
  24581. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24582. }
  24583. serializationObject.indices = this.indices;
  24584. return serializationObject;
  24585. };
  24586. // Statics
  24587. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24588. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24589. };
  24590. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24591. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24592. };
  24593. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24594. var result = new VertexData();
  24595. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24596. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24597. }
  24598. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24599. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24600. }
  24601. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24602. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24603. }
  24604. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24605. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24606. }
  24607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24608. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24609. }
  24610. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24611. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24612. }
  24613. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24614. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24615. }
  24616. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24617. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24618. }
  24619. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24620. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24621. }
  24622. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24623. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24624. }
  24625. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24626. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24627. }
  24628. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24629. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24630. }
  24631. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24632. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24633. }
  24634. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24635. return result;
  24636. };
  24637. VertexData.CreateRibbon = function (options) {
  24638. var pathArray = options.pathArray;
  24639. var closeArray = options.closeArray || false;
  24640. var closePath = options.closePath || false;
  24641. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24642. var offset = options.offset || defaultOffset;
  24643. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24644. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24645. var positions = [];
  24646. var indices = [];
  24647. var normals = [];
  24648. var uvs = [];
  24649. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24650. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24651. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24652. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24653. var minlg; // minimal length among all paths from pathArray
  24654. var lg = []; // array of path lengths : nb of vertex per path
  24655. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24656. var p; // path iterator
  24657. var i; // point iterator
  24658. var j; // point iterator
  24659. // if single path in pathArray
  24660. if (pathArray.length < 2) {
  24661. var ar1 = [];
  24662. var ar2 = [];
  24663. for (i = 0; i < pathArray[0].length - offset; i++) {
  24664. ar1.push(pathArray[0][i]);
  24665. ar2.push(pathArray[0][i + offset]);
  24666. }
  24667. pathArray = [ar1, ar2];
  24668. }
  24669. // positions and horizontal distances (u)
  24670. var idc = 0;
  24671. var closePathCorr = (closePath) ? 1 : 0;
  24672. var path;
  24673. var l;
  24674. minlg = pathArray[0].length;
  24675. var vectlg;
  24676. var dist;
  24677. for (p = 0; p < pathArray.length; p++) {
  24678. uTotalDistance[p] = 0;
  24679. us[p] = [0];
  24680. path = pathArray[p];
  24681. l = path.length;
  24682. minlg = (minlg < l) ? minlg : l;
  24683. j = 0;
  24684. while (j < l) {
  24685. positions.push(path[j].x, path[j].y, path[j].z);
  24686. if (j > 0) {
  24687. vectlg = path[j].subtract(path[j - 1]).length();
  24688. dist = vectlg + uTotalDistance[p];
  24689. us[p].push(dist);
  24690. uTotalDistance[p] = dist;
  24691. }
  24692. j++;
  24693. }
  24694. if (closePath) {
  24695. j--;
  24696. positions.push(path[0].x, path[0].y, path[0].z);
  24697. vectlg = path[j].subtract(path[0]).length();
  24698. dist = vectlg + uTotalDistance[p];
  24699. us[p].push(dist);
  24700. uTotalDistance[p] = dist;
  24701. }
  24702. lg[p] = l + closePathCorr;
  24703. idx[p] = idc;
  24704. idc += (l + closePathCorr);
  24705. }
  24706. // vertical distances (v)
  24707. var path1;
  24708. var path2;
  24709. var vertex1;
  24710. var vertex2;
  24711. for (i = 0; i < minlg + closePathCorr; i++) {
  24712. vTotalDistance[i] = 0;
  24713. vs[i] = [0];
  24714. for (p = 0; p < pathArray.length - 1; p++) {
  24715. path1 = pathArray[p];
  24716. path2 = pathArray[p + 1];
  24717. if (i === minlg) {
  24718. vertex1 = path1[0];
  24719. vertex2 = path2[0];
  24720. }
  24721. else {
  24722. vertex1 = path1[i];
  24723. vertex2 = path2[i];
  24724. }
  24725. vectlg = vertex2.subtract(vertex1).length();
  24726. dist = vectlg + vTotalDistance[i];
  24727. vs[i].push(dist);
  24728. vTotalDistance[i] = dist;
  24729. }
  24730. if (closeArray) {
  24731. path1 = pathArray[p];
  24732. path2 = pathArray[0];
  24733. if (i === minlg) {
  24734. vertex2 = path2[0];
  24735. }
  24736. vectlg = vertex2.subtract(vertex1).length();
  24737. dist = vectlg + vTotalDistance[i];
  24738. vTotalDistance[i] = dist;
  24739. }
  24740. }
  24741. // uvs
  24742. var u;
  24743. var v;
  24744. for (p = 0; p < pathArray.length; p++) {
  24745. for (i = 0; i < minlg + closePathCorr; i++) {
  24746. u = us[p][i] / uTotalDistance[p];
  24747. v = vs[i][p] / vTotalDistance[i];
  24748. uvs.push(u, v);
  24749. }
  24750. }
  24751. // indices
  24752. p = 0; // path index
  24753. var pi = 0; // positions array index
  24754. var l1 = lg[p] - 1; // path1 length
  24755. var l2 = lg[p + 1] - 1; // path2 length
  24756. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24757. var shft = idx[1] - idx[0]; // shift
  24758. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24759. while (pi <= min && p < path1nb) {
  24760. // 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
  24761. indices.push(pi, pi + shft, pi + 1);
  24762. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24763. pi += 1;
  24764. if (pi === min) {
  24765. p++;
  24766. if (p === lg.length - 1) {
  24767. shft = idx[0] - idx[p];
  24768. l1 = lg[p] - 1;
  24769. l2 = lg[0] - 1;
  24770. }
  24771. else {
  24772. shft = idx[p + 1] - idx[p];
  24773. l1 = lg[p] - 1;
  24774. l2 = lg[p + 1] - 1;
  24775. }
  24776. pi = idx[p];
  24777. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24778. }
  24779. }
  24780. // normals
  24781. VertexData.ComputeNormals(positions, indices, normals);
  24782. if (closePath) {
  24783. var indexFirst = 0;
  24784. var indexLast = 0;
  24785. for (p = 0; p < pathArray.length; p++) {
  24786. indexFirst = idx[p] * 3;
  24787. if (p + 1 < pathArray.length) {
  24788. indexLast = (idx[p + 1] - 1) * 3;
  24789. }
  24790. else {
  24791. indexLast = normals.length - 3;
  24792. }
  24793. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24794. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24795. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24796. normals[indexLast] = normals[indexFirst];
  24797. normals[indexLast + 1] = normals[indexFirst + 1];
  24798. normals[indexLast + 2] = normals[indexFirst + 2];
  24799. }
  24800. }
  24801. // sides
  24802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24803. // Result
  24804. var vertexData = new VertexData();
  24805. vertexData.indices = indices;
  24806. vertexData.positions = positions;
  24807. vertexData.normals = normals;
  24808. vertexData.uvs = uvs;
  24809. if (closePath) {
  24810. vertexData._idx = idx;
  24811. }
  24812. return vertexData;
  24813. };
  24814. VertexData.CreateBox = function (options) {
  24815. var normalsSource = [
  24816. new BABYLON.Vector3(0, 0, 1),
  24817. new BABYLON.Vector3(0, 0, -1),
  24818. new BABYLON.Vector3(1, 0, 0),
  24819. new BABYLON.Vector3(-1, 0, 0),
  24820. new BABYLON.Vector3(0, 1, 0),
  24821. new BABYLON.Vector3(0, -1, 0)
  24822. ];
  24823. var indices = [];
  24824. var positions = [];
  24825. var normals = [];
  24826. var uvs = [];
  24827. var width = options.width || options.size || 1;
  24828. var height = options.height || options.size || 1;
  24829. var depth = options.depth || options.size || 1;
  24830. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24831. var faceUV = options.faceUV || new Array(6);
  24832. var faceColors = options.faceColors;
  24833. var colors = [];
  24834. // default face colors and UV if undefined
  24835. for (var f = 0; f < 6; f++) {
  24836. if (faceUV[f] === undefined) {
  24837. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24838. }
  24839. if (faceColors && faceColors[f] === undefined) {
  24840. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24841. }
  24842. }
  24843. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24844. // Create each face in turn.
  24845. for (var index = 0; index < normalsSource.length; index++) {
  24846. var normal = normalsSource[index];
  24847. // Get two vectors perpendicular to the face normal and to each other.
  24848. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24849. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24850. // Six indices (two triangles) per face.
  24851. var verticesLength = positions.length / 3;
  24852. indices.push(verticesLength);
  24853. indices.push(verticesLength + 1);
  24854. indices.push(verticesLength + 2);
  24855. indices.push(verticesLength);
  24856. indices.push(verticesLength + 2);
  24857. indices.push(verticesLength + 3);
  24858. // Four vertices per face.
  24859. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24860. positions.push(vertex.x, vertex.y, vertex.z);
  24861. normals.push(normal.x, normal.y, normal.z);
  24862. uvs.push(faceUV[index].z, faceUV[index].w);
  24863. if (faceColors) {
  24864. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24865. }
  24866. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24867. positions.push(vertex.x, vertex.y, vertex.z);
  24868. normals.push(normal.x, normal.y, normal.z);
  24869. uvs.push(faceUV[index].x, faceUV[index].w);
  24870. if (faceColors) {
  24871. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24872. }
  24873. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24874. positions.push(vertex.x, vertex.y, vertex.z);
  24875. normals.push(normal.x, normal.y, normal.z);
  24876. uvs.push(faceUV[index].x, faceUV[index].y);
  24877. if (faceColors) {
  24878. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24879. }
  24880. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24881. positions.push(vertex.x, vertex.y, vertex.z);
  24882. normals.push(normal.x, normal.y, normal.z);
  24883. uvs.push(faceUV[index].z, faceUV[index].y);
  24884. if (faceColors) {
  24885. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24886. }
  24887. }
  24888. // sides
  24889. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24890. // Result
  24891. var vertexData = new VertexData();
  24892. vertexData.indices = indices;
  24893. vertexData.positions = positions;
  24894. vertexData.normals = normals;
  24895. vertexData.uvs = uvs;
  24896. if (faceColors) {
  24897. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24898. vertexData.colors = totalColors;
  24899. }
  24900. return vertexData;
  24901. };
  24902. VertexData.CreateSphere = function (options) {
  24903. var segments = options.segments || 32;
  24904. var diameterX = options.diameterX || options.diameter || 1;
  24905. var diameterY = options.diameterY || options.diameter || 1;
  24906. var diameterZ = options.diameterZ || options.diameter || 1;
  24907. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24908. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24909. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24910. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24911. var totalZRotationSteps = 2 + segments;
  24912. var totalYRotationSteps = 2 * totalZRotationSteps;
  24913. var indices = [];
  24914. var positions = [];
  24915. var normals = [];
  24916. var uvs = [];
  24917. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24918. var normalizedZ = zRotationStep / totalZRotationSteps;
  24919. var angleZ = normalizedZ * Math.PI * slice;
  24920. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24921. var normalizedY = yRotationStep / totalYRotationSteps;
  24922. var angleY = normalizedY * Math.PI * 2 * arc;
  24923. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24924. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24925. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24926. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24927. var vertex = complete.multiply(radius);
  24928. var normal = complete.divide(radius).normalize();
  24929. positions.push(vertex.x, vertex.y, vertex.z);
  24930. normals.push(normal.x, normal.y, normal.z);
  24931. uvs.push(normalizedY, normalizedZ);
  24932. }
  24933. if (zRotationStep > 0) {
  24934. var verticesCount = positions.length / 3;
  24935. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24936. indices.push((firstIndex));
  24937. indices.push((firstIndex + 1));
  24938. indices.push(firstIndex + totalYRotationSteps + 1);
  24939. indices.push((firstIndex + totalYRotationSteps + 1));
  24940. indices.push((firstIndex + 1));
  24941. indices.push((firstIndex + totalYRotationSteps + 2));
  24942. }
  24943. }
  24944. }
  24945. // Sides
  24946. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24947. // Result
  24948. var vertexData = new VertexData();
  24949. vertexData.indices = indices;
  24950. vertexData.positions = positions;
  24951. vertexData.normals = normals;
  24952. vertexData.uvs = uvs;
  24953. return vertexData;
  24954. };
  24955. // Cylinder and cone
  24956. VertexData.CreateCylinder = function (options) {
  24957. var height = options.height || 2;
  24958. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24959. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24960. var tessellation = options.tessellation || 24;
  24961. var subdivisions = options.subdivisions || 1;
  24962. var hasRings = options.hasRings;
  24963. var enclose = options.enclose;
  24964. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24965. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24966. var faceUV = options.faceUV || new Array(3);
  24967. var faceColors = options.faceColors;
  24968. // default face colors and UV if undefined
  24969. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24970. var ringNb = (hasRings) ? subdivisions : 1;
  24971. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24972. var f;
  24973. for (f = 0; f < surfaceNb; f++) {
  24974. if (faceColors && faceColors[f] === undefined) {
  24975. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24976. }
  24977. }
  24978. for (f = 0; f < surfaceNb; f++) {
  24979. if (faceUV && faceUV[f] === undefined) {
  24980. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24981. }
  24982. }
  24983. var indices = [];
  24984. var positions = [];
  24985. var normals = [];
  24986. var uvs = [];
  24987. var colors = [];
  24988. var angle_step = Math.PI * 2 * arc / tessellation;
  24989. var angle;
  24990. var h;
  24991. var radius;
  24992. var tan = (diameterBottom - diameterTop) / 2 / height;
  24993. var ringVertex = BABYLON.Vector3.Zero();
  24994. var ringNormal = BABYLON.Vector3.Zero();
  24995. var ringFirstVertex = BABYLON.Vector3.Zero();
  24996. var ringFirstNormal = BABYLON.Vector3.Zero();
  24997. var quadNormal = BABYLON.Vector3.Zero();
  24998. var Y = BABYLON.Axis.Y;
  24999. // positions, normals, uvs
  25000. var i;
  25001. var j;
  25002. var r;
  25003. var ringIdx = 1;
  25004. var s = 1; // surface index
  25005. var cs = 0;
  25006. var v = 0;
  25007. for (i = 0; i <= subdivisions; i++) {
  25008. h = i / subdivisions;
  25009. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25010. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25011. for (r = 0; r < ringIdx; r++) {
  25012. if (hasRings) {
  25013. s += r;
  25014. }
  25015. if (enclose) {
  25016. s += 2 * r;
  25017. }
  25018. for (j = 0; j <= tessellation; j++) {
  25019. angle = j * angle_step;
  25020. // position
  25021. ringVertex.x = Math.cos(-angle) * radius;
  25022. ringVertex.y = -height / 2 + h * height;
  25023. ringVertex.z = Math.sin(-angle) * radius;
  25024. // normal
  25025. if (diameterTop === 0 && i === subdivisions) {
  25026. // if no top cap, reuse former normals
  25027. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25028. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25029. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25030. }
  25031. else {
  25032. ringNormal.x = ringVertex.x;
  25033. ringNormal.z = ringVertex.z;
  25034. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25035. ringNormal.normalize();
  25036. }
  25037. // keep first ring vertex values for enclose
  25038. if (j === 0) {
  25039. ringFirstVertex.copyFrom(ringVertex);
  25040. ringFirstNormal.copyFrom(ringNormal);
  25041. }
  25042. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25043. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25044. if (hasRings) {
  25045. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25046. }
  25047. else {
  25048. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25049. }
  25050. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25051. if (faceColors) {
  25052. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25053. }
  25054. }
  25055. // if enclose, add four vertices and their dedicated normals
  25056. if (arc !== 1 && enclose) {
  25057. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25058. positions.push(0, ringVertex.y, 0);
  25059. positions.push(0, ringVertex.y, 0);
  25060. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25061. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25062. quadNormal.normalize();
  25063. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25064. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25065. quadNormal.normalize();
  25066. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25067. if (hasRings) {
  25068. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25069. }
  25070. else {
  25071. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25072. }
  25073. uvs.push(faceUV[s + 1].x, v);
  25074. uvs.push(faceUV[s + 1].z, v);
  25075. if (hasRings) {
  25076. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25077. }
  25078. else {
  25079. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25080. }
  25081. uvs.push(faceUV[s + 2].x, v);
  25082. uvs.push(faceUV[s + 2].z, v);
  25083. if (faceColors) {
  25084. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25085. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25086. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25087. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25088. }
  25089. }
  25090. if (cs !== s) {
  25091. cs = s;
  25092. }
  25093. }
  25094. }
  25095. // indices
  25096. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25097. var s;
  25098. i = 0;
  25099. for (s = 0; s < subdivisions; s++) {
  25100. for (j = 0; j < tessellation; j++) {
  25101. var i0 = i * (e + 1) + j;
  25102. var i1 = (i + 1) * (e + 1) + j;
  25103. var i2 = i * (e + 1) + (j + 1);
  25104. var i3 = (i + 1) * (e + 1) + (j + 1);
  25105. indices.push(i0, i1, i2);
  25106. indices.push(i3, i2, i1);
  25107. }
  25108. if (arc !== 1 && enclose) {
  25109. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25110. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25111. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25112. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25113. }
  25114. i = (hasRings) ? (i + 2) : (i + 1);
  25115. }
  25116. // Caps
  25117. var createCylinderCap = function (isTop) {
  25118. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25119. if (radius === 0) {
  25120. return;
  25121. }
  25122. // Cap positions, normals & uvs
  25123. var angle;
  25124. var circleVector;
  25125. var i;
  25126. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25127. var c;
  25128. if (faceColors) {
  25129. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25130. }
  25131. // cap center
  25132. var vbase = positions.length / 3;
  25133. var offset = isTop ? height / 2 : -height / 2;
  25134. var center = new BABYLON.Vector3(0, offset, 0);
  25135. positions.push(center.x, center.y, center.z);
  25136. normals.push(0, isTop ? 1 : -1, 0);
  25137. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25138. if (faceColors) {
  25139. colors.push(c.r, c.g, c.b, c.a);
  25140. }
  25141. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25142. for (i = 0; i <= tessellation; i++) {
  25143. angle = Math.PI * 2 * i * arc / tessellation;
  25144. var cos = Math.cos(-angle);
  25145. var sin = Math.sin(-angle);
  25146. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25147. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25148. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25149. normals.push(0, isTop ? 1 : -1, 0);
  25150. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25151. if (faceColors) {
  25152. colors.push(c.r, c.g, c.b, c.a);
  25153. }
  25154. }
  25155. // Cap indices
  25156. for (i = 0; i < tessellation; i++) {
  25157. if (!isTop) {
  25158. indices.push(vbase);
  25159. indices.push(vbase + (i + 1));
  25160. indices.push(vbase + (i + 2));
  25161. }
  25162. else {
  25163. indices.push(vbase);
  25164. indices.push(vbase + (i + 2));
  25165. indices.push(vbase + (i + 1));
  25166. }
  25167. }
  25168. };
  25169. // add caps to geometry
  25170. createCylinderCap(false);
  25171. createCylinderCap(true);
  25172. // Sides
  25173. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25174. var vertexData = new VertexData();
  25175. vertexData.indices = indices;
  25176. vertexData.positions = positions;
  25177. vertexData.normals = normals;
  25178. vertexData.uvs = uvs;
  25179. if (faceColors) {
  25180. vertexData.colors = colors;
  25181. }
  25182. return vertexData;
  25183. };
  25184. VertexData.CreateTorus = function (options) {
  25185. var indices = [];
  25186. var positions = [];
  25187. var normals = [];
  25188. var uvs = [];
  25189. var diameter = options.diameter || 1;
  25190. var thickness = options.thickness || 0.5;
  25191. var tessellation = options.tessellation || 16;
  25192. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25193. var stride = tessellation + 1;
  25194. for (var i = 0; i <= tessellation; i++) {
  25195. var u = i / tessellation;
  25196. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25197. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25198. for (var j = 0; j <= tessellation; j++) {
  25199. var v = 1 - j / tessellation;
  25200. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25201. var dx = Math.cos(innerAngle);
  25202. var dy = Math.sin(innerAngle);
  25203. // Create a vertex.
  25204. var normal = new BABYLON.Vector3(dx, dy, 0);
  25205. var position = normal.scale(thickness / 2);
  25206. var textureCoordinate = new BABYLON.Vector2(u, v);
  25207. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25208. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25209. positions.push(position.x, position.y, position.z);
  25210. normals.push(normal.x, normal.y, normal.z);
  25211. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25212. // And create indices for two triangles.
  25213. var nextI = (i + 1) % stride;
  25214. var nextJ = (j + 1) % stride;
  25215. indices.push(i * stride + j);
  25216. indices.push(i * stride + nextJ);
  25217. indices.push(nextI * stride + j);
  25218. indices.push(i * stride + nextJ);
  25219. indices.push(nextI * stride + nextJ);
  25220. indices.push(nextI * stride + j);
  25221. }
  25222. }
  25223. // Sides
  25224. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25225. // Result
  25226. var vertexData = new VertexData();
  25227. vertexData.indices = indices;
  25228. vertexData.positions = positions;
  25229. vertexData.normals = normals;
  25230. vertexData.uvs = uvs;
  25231. return vertexData;
  25232. };
  25233. VertexData.CreateLineSystem = function (options) {
  25234. var indices = [];
  25235. var positions = [];
  25236. var lines = options.lines;
  25237. var idx = 0;
  25238. for (var l = 0; l < lines.length; l++) {
  25239. var points = lines[l];
  25240. for (var index = 0; index < points.length; index++) {
  25241. positions.push(points[index].x, points[index].y, points[index].z);
  25242. if (index > 0) {
  25243. indices.push(idx - 1);
  25244. indices.push(idx);
  25245. }
  25246. idx++;
  25247. }
  25248. }
  25249. var vertexData = new VertexData();
  25250. vertexData.indices = indices;
  25251. vertexData.positions = positions;
  25252. return vertexData;
  25253. };
  25254. VertexData.CreateDashedLines = function (options) {
  25255. var dashSize = options.dashSize || 3;
  25256. var gapSize = options.gapSize || 1;
  25257. var dashNb = options.dashNb || 200;
  25258. var points = options.points;
  25259. var positions = new Array();
  25260. var indices = new Array();
  25261. var curvect = BABYLON.Vector3.Zero();
  25262. var lg = 0;
  25263. var nb = 0;
  25264. var shft = 0;
  25265. var dashshft = 0;
  25266. var curshft = 0;
  25267. var idx = 0;
  25268. var i = 0;
  25269. for (i = 0; i < points.length - 1; i++) {
  25270. points[i + 1].subtractToRef(points[i], curvect);
  25271. lg += curvect.length();
  25272. }
  25273. shft = lg / dashNb;
  25274. dashshft = dashSize * shft / (dashSize + gapSize);
  25275. for (i = 0; i < points.length - 1; i++) {
  25276. points[i + 1].subtractToRef(points[i], curvect);
  25277. nb = Math.floor(curvect.length() / shft);
  25278. curvect.normalize();
  25279. for (var j = 0; j < nb; j++) {
  25280. curshft = shft * j;
  25281. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25282. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25283. indices.push(idx, idx + 1);
  25284. idx += 2;
  25285. }
  25286. }
  25287. // Result
  25288. var vertexData = new VertexData();
  25289. vertexData.positions = positions;
  25290. vertexData.indices = indices;
  25291. return vertexData;
  25292. };
  25293. VertexData.CreateGround = function (options) {
  25294. var indices = [];
  25295. var positions = [];
  25296. var normals = [];
  25297. var uvs = [];
  25298. var row, col;
  25299. var width = options.width || 1;
  25300. var height = options.height || 1;
  25301. var subdivisions = options.subdivisions || 1;
  25302. for (row = 0; row <= subdivisions; row++) {
  25303. for (col = 0; col <= subdivisions; col++) {
  25304. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25305. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25306. positions.push(position.x, position.y, position.z);
  25307. normals.push(normal.x, normal.y, normal.z);
  25308. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25309. }
  25310. }
  25311. for (row = 0; row < subdivisions; row++) {
  25312. for (col = 0; col < subdivisions; col++) {
  25313. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25314. indices.push(col + 1 + row * (subdivisions + 1));
  25315. indices.push(col + row * (subdivisions + 1));
  25316. indices.push(col + (row + 1) * (subdivisions + 1));
  25317. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25318. indices.push(col + row * (subdivisions + 1));
  25319. }
  25320. }
  25321. // Result
  25322. var vertexData = new VertexData();
  25323. vertexData.indices = indices;
  25324. vertexData.positions = positions;
  25325. vertexData.normals = normals;
  25326. vertexData.uvs = uvs;
  25327. return vertexData;
  25328. };
  25329. VertexData.CreateTiledGround = function (options) {
  25330. var xmin = options.xmin;
  25331. var zmin = options.zmin;
  25332. var xmax = options.xmax;
  25333. var zmax = options.zmax;
  25334. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25335. var precision = options.precision || { w: 1, h: 1 };
  25336. var indices = [];
  25337. var positions = [];
  25338. var normals = [];
  25339. var uvs = [];
  25340. var row, col, tileRow, tileCol;
  25341. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25342. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25343. precision.w = (precision.w < 1) ? 1 : precision.w;
  25344. precision.h = (precision.h < 1) ? 1 : precision.h;
  25345. var tileSize = {
  25346. 'w': (xmax - xmin) / subdivisions.w,
  25347. 'h': (zmax - zmin) / subdivisions.h
  25348. };
  25349. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25350. // Indices
  25351. var base = positions.length / 3;
  25352. var rowLength = precision.w + 1;
  25353. for (row = 0; row < precision.h; row++) {
  25354. for (col = 0; col < precision.w; col++) {
  25355. var square = [
  25356. base + col + row * rowLength,
  25357. base + (col + 1) + row * rowLength,
  25358. base + (col + 1) + (row + 1) * rowLength,
  25359. base + col + (row + 1) * rowLength
  25360. ];
  25361. indices.push(square[1]);
  25362. indices.push(square[2]);
  25363. indices.push(square[3]);
  25364. indices.push(square[0]);
  25365. indices.push(square[1]);
  25366. indices.push(square[3]);
  25367. }
  25368. }
  25369. // Position, normals and uvs
  25370. var position = BABYLON.Vector3.Zero();
  25371. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25372. for (row = 0; row <= precision.h; row++) {
  25373. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25374. for (col = 0; col <= precision.w; col++) {
  25375. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25376. position.y = 0;
  25377. positions.push(position.x, position.y, position.z);
  25378. normals.push(normal.x, normal.y, normal.z);
  25379. uvs.push(col / precision.w, row / precision.h);
  25380. }
  25381. }
  25382. }
  25383. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25384. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25385. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25386. }
  25387. }
  25388. // Result
  25389. var vertexData = new VertexData();
  25390. vertexData.indices = indices;
  25391. vertexData.positions = positions;
  25392. vertexData.normals = normals;
  25393. vertexData.uvs = uvs;
  25394. return vertexData;
  25395. };
  25396. VertexData.CreateGroundFromHeightMap = function (options) {
  25397. var indices = [];
  25398. var positions = [];
  25399. var normals = [];
  25400. var uvs = [];
  25401. var row, col;
  25402. // Vertices
  25403. for (row = 0; row <= options.subdivisions; row++) {
  25404. for (col = 0; col <= options.subdivisions; col++) {
  25405. 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));
  25406. // Compute height
  25407. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25408. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25409. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25410. var r = options.buffer[pos] / 255.0;
  25411. var g = options.buffer[pos + 1] / 255.0;
  25412. var b = options.buffer[pos + 2] / 255.0;
  25413. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25414. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25415. // Add vertex
  25416. positions.push(position.x, position.y, position.z);
  25417. normals.push(0, 0, 0);
  25418. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25419. }
  25420. }
  25421. // Indices
  25422. for (row = 0; row < options.subdivisions; row++) {
  25423. for (col = 0; col < options.subdivisions; col++) {
  25424. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25425. indices.push(col + 1 + row * (options.subdivisions + 1));
  25426. indices.push(col + row * (options.subdivisions + 1));
  25427. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25428. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25429. indices.push(col + row * (options.subdivisions + 1));
  25430. }
  25431. }
  25432. // Normals
  25433. VertexData.ComputeNormals(positions, indices, normals);
  25434. // Result
  25435. var vertexData = new VertexData();
  25436. vertexData.indices = indices;
  25437. vertexData.positions = positions;
  25438. vertexData.normals = normals;
  25439. vertexData.uvs = uvs;
  25440. return vertexData;
  25441. };
  25442. VertexData.CreatePlane = function (options) {
  25443. var indices = [];
  25444. var positions = [];
  25445. var normals = [];
  25446. var uvs = [];
  25447. var width = options.width || options.size || 1;
  25448. var height = options.height || options.size || 1;
  25449. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25450. // Vertices
  25451. var halfWidth = width / 2.0;
  25452. var halfHeight = height / 2.0;
  25453. positions.push(-halfWidth, -halfHeight, 0);
  25454. normals.push(0, 0, -1.0);
  25455. uvs.push(0.0, 0.0);
  25456. positions.push(halfWidth, -halfHeight, 0);
  25457. normals.push(0, 0, -1.0);
  25458. uvs.push(1.0, 0.0);
  25459. positions.push(halfWidth, halfHeight, 0);
  25460. normals.push(0, 0, -1.0);
  25461. uvs.push(1.0, 1.0);
  25462. positions.push(-halfWidth, halfHeight, 0);
  25463. normals.push(0, 0, -1.0);
  25464. uvs.push(0.0, 1.0);
  25465. // Indices
  25466. indices.push(0);
  25467. indices.push(1);
  25468. indices.push(2);
  25469. indices.push(0);
  25470. indices.push(2);
  25471. indices.push(3);
  25472. // Sides
  25473. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25474. // Result
  25475. var vertexData = new VertexData();
  25476. vertexData.indices = indices;
  25477. vertexData.positions = positions;
  25478. vertexData.normals = normals;
  25479. vertexData.uvs = uvs;
  25480. return vertexData;
  25481. };
  25482. VertexData.CreateDisc = function (options) {
  25483. var positions = [];
  25484. var indices = [];
  25485. var normals = [];
  25486. var uvs = [];
  25487. var radius = options.radius || 0.5;
  25488. var tessellation = options.tessellation || 64;
  25489. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25491. // positions and uvs
  25492. positions.push(0, 0, 0); // disc center first
  25493. uvs.push(0.5, 0.5);
  25494. var theta = Math.PI * 2 * arc;
  25495. var step = theta / tessellation;
  25496. for (var a = 0; a < theta; a += step) {
  25497. var x = Math.cos(a);
  25498. var y = Math.sin(a);
  25499. var u = (x + 1) / 2;
  25500. var v = (1 - y) / 2;
  25501. positions.push(radius * x, radius * y, 0);
  25502. uvs.push(u, v);
  25503. }
  25504. if (arc === 1) {
  25505. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25506. uvs.push(uvs[2], uvs[3]);
  25507. }
  25508. //indices
  25509. var vertexNb = positions.length / 3;
  25510. for (var i = 1; i < vertexNb - 1; i++) {
  25511. indices.push(i + 1, 0, i);
  25512. }
  25513. // result
  25514. VertexData.ComputeNormals(positions, indices, normals);
  25515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25516. var vertexData = new VertexData();
  25517. vertexData.indices = indices;
  25518. vertexData.positions = positions;
  25519. vertexData.normals = normals;
  25520. vertexData.uvs = uvs;
  25521. return vertexData;
  25522. };
  25523. VertexData.CreateIcoSphere = function (options) {
  25524. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25525. var radius = options.radius || 1;
  25526. var flat = (options.flat === undefined) ? true : options.flat;
  25527. var subdivisions = options.subdivisions || 4;
  25528. var radiusX = options.radiusX || radius;
  25529. var radiusY = options.radiusY || radius;
  25530. var radiusZ = options.radiusZ || radius;
  25531. var t = (1 + Math.sqrt(5)) / 2;
  25532. // 12 vertex x,y,z
  25533. var ico_vertices = [
  25534. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25535. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25536. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25537. ];
  25538. // index of 3 vertex makes a face of icopshere
  25539. var ico_indices = [
  25540. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25541. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25542. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25543. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25544. ];
  25545. // vertex for uv have aliased position, not for UV
  25546. var vertices_unalias_id = [
  25547. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25548. // vertex alias
  25549. 0,
  25550. 2,
  25551. 3,
  25552. 3,
  25553. 3,
  25554. 4,
  25555. 7,
  25556. 8,
  25557. 9,
  25558. 9,
  25559. 10,
  25560. 11 // 23: B + 12
  25561. ];
  25562. // uv as integer step (not pixels !)
  25563. var ico_vertexuv = [
  25564. 5, 1, 3, 1, 6, 4, 0, 0,
  25565. 5, 3, 4, 2, 2, 2, 4, 0,
  25566. 2, 0, 1, 1, 6, 0, 6, 2,
  25567. // vertex alias (for same vertex on different faces)
  25568. 0, 4,
  25569. 3, 3,
  25570. 4, 4,
  25571. 3, 1,
  25572. 4, 2,
  25573. 4, 4,
  25574. 0, 2,
  25575. 1, 1,
  25576. 2, 2,
  25577. 3, 3,
  25578. 1, 3,
  25579. 2, 4 // 23: B + 12
  25580. ];
  25581. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25582. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25583. // First island of uv mapping
  25584. // v = 4h 3+ 2
  25585. // v = 3h 9+ 4
  25586. // v = 2h 9+ 5 B
  25587. // v = 1h 9 1 0
  25588. // v = 0h 3 8 7 A
  25589. // u = 0 1 2 3 4 5 6 *a
  25590. // Second island of uv mapping
  25591. // v = 4h 0+ B+ 4+
  25592. // v = 3h A+ 2+
  25593. // v = 2h 7+ 6 3+
  25594. // v = 1h 8+ 3+
  25595. // v = 0h
  25596. // u = 0 1 2 3 4 5 6 *a
  25597. // Face layout on texture UV mapping
  25598. // ============
  25599. // \ 4 /\ 16 / ======
  25600. // \ / \ / /\ 11 /
  25601. // \/ 7 \/ / \ /
  25602. // ======= / 10 \/
  25603. // /\ 17 /\ =======
  25604. // / \ / \ \ 15 /\
  25605. // / 8 \/ 12 \ \ / \
  25606. // ============ \/ 6 \
  25607. // \ 18 /\ ============
  25608. // \ / \ \ 5 /\ 0 /
  25609. // \/ 13 \ \ / \ /
  25610. // ======= \/ 1 \/
  25611. // =============
  25612. // /\ 19 /\ 2 /\
  25613. // / \ / \ / \
  25614. // / 14 \/ 9 \/ 3 \
  25615. // ===================
  25616. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25617. var ustep = 138 / 1024;
  25618. var vstep = 239 / 1024;
  25619. var uoffset = 60 / 1024;
  25620. var voffset = 26 / 1024;
  25621. // Second island should have margin, not to touch the first island
  25622. // avoid any borderline artefact in pixel rounding
  25623. var island_u_offset = -40 / 1024;
  25624. var island_v_offset = +20 / 1024;
  25625. // face is either island 0 or 1 :
  25626. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25627. var island = [
  25628. 0, 0, 0, 0, 1,
  25629. 0, 0, 1, 1, 0,
  25630. 0, 0, 1, 1, 0,
  25631. 0, 1, 1, 1, 0 // 15 - 19
  25632. ];
  25633. var indices = [];
  25634. var positions = [];
  25635. var normals = [];
  25636. var uvs = [];
  25637. var current_indice = 0;
  25638. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25639. var face_vertex_pos = new Array(3);
  25640. var face_vertex_uv = new Array(3);
  25641. var v012;
  25642. for (v012 = 0; v012 < 3; v012++) {
  25643. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25644. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25645. }
  25646. // create all with normals
  25647. for (var face = 0; face < 20; face++) {
  25648. // 3 vertex per face
  25649. for (v012 = 0; v012 < 3; v012++) {
  25650. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25651. var v_id = ico_indices[3 * face + v012];
  25652. // vertex have 3D position (x,y,z)
  25653. 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]);
  25654. // Normalize to get normal, then scale to radius
  25655. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25656. // uv Coordinates from vertex ID
  25657. 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);
  25658. }
  25659. // Subdivide the face (interpolate pos, norm, uv)
  25660. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25661. // - norm is linear interpolation of vertex corner normal
  25662. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25663. // - uv is linear interpolation
  25664. //
  25665. // Topology is as below for sub-divide by 2
  25666. // vertex shown as v0,v1,v2
  25667. // interp index is i1 to progress in range [v0,v1[
  25668. // interp index is i2 to progress in range [v0,v2[
  25669. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25670. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25671. //
  25672. //
  25673. // i2 v2
  25674. // ^ ^
  25675. // / / \
  25676. // / / \
  25677. // / / \
  25678. // / / (0,1) \
  25679. // / #---------\
  25680. // / / \ (0,0)'/ \
  25681. // / / \ / \
  25682. // / / \ / \
  25683. // / / (0,0) \ / (1,0) \
  25684. // / #---------#---------\
  25685. // v0 v1
  25686. //
  25687. // --------------------> i1
  25688. //
  25689. // interp of (i1,i2):
  25690. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25691. // along i1 : lerp(x0,x1, i1/(S-i2))
  25692. //
  25693. // centroid of triangle is needed to get help normal computation
  25694. // (c1,c2) are used for centroid location
  25695. var interp_vertex = function (i1, i2, c1, c2) {
  25696. // vertex is interpolated from
  25697. // - face_vertex_pos[0..2]
  25698. // - face_vertex_uv[0..2]
  25699. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25700. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25701. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25702. pos_interp.normalize();
  25703. var vertex_normal;
  25704. if (flat) {
  25705. // in flat mode, recalculate normal as face centroid normal
  25706. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25707. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25708. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25709. }
  25710. else {
  25711. // in smooth mode, recalculate normal from each single vertex position
  25712. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25713. }
  25714. // Vertex normal need correction due to X,Y,Z radius scaling
  25715. vertex_normal.x /= radiusX;
  25716. vertex_normal.y /= radiusY;
  25717. vertex_normal.z /= radiusZ;
  25718. vertex_normal.normalize();
  25719. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25720. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25721. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25722. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25723. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25724. uvs.push(uv_interp.x, uv_interp.y);
  25725. // push each vertex has member of a face
  25726. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25727. indices.push(current_indice);
  25728. current_indice++;
  25729. };
  25730. for (var i2 = 0; i2 < subdivisions; i2++) {
  25731. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25732. // face : (i1,i2) for /\ :
  25733. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25734. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25735. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25736. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25737. if (i1 + i2 + 1 < subdivisions) {
  25738. // face : (i1,i2)' for \/ :
  25739. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25740. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25741. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25742. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25743. }
  25744. }
  25745. }
  25746. }
  25747. // Sides
  25748. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25749. // Result
  25750. var vertexData = new VertexData();
  25751. vertexData.indices = indices;
  25752. vertexData.positions = positions;
  25753. vertexData.normals = normals;
  25754. vertexData.uvs = uvs;
  25755. return vertexData;
  25756. };
  25757. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25758. VertexData.CreatePolyhedron = function (options) {
  25759. // provided polyhedron types :
  25760. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25761. // 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)
  25762. var polyhedra = [];
  25763. 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]] };
  25764. 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]] };
  25765. polyhedra[2] = {
  25766. 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]],
  25767. 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]]
  25768. };
  25769. polyhedra[3] = {
  25770. 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]],
  25771. 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]]
  25772. };
  25773. polyhedra[4] = {
  25774. 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]],
  25775. 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]]
  25776. };
  25777. 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]] };
  25778. 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]] };
  25779. 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]] };
  25780. 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]] };
  25781. 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]] };
  25782. 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]] };
  25783. 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]] };
  25784. 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]] };
  25785. 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]] };
  25786. polyhedra[14] = {
  25787. 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]],
  25788. 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]]
  25789. };
  25790. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25791. var size = options.size;
  25792. var sizeX = options.sizeX || size || 1;
  25793. var sizeY = options.sizeY || size || 1;
  25794. var sizeZ = options.sizeZ || size || 1;
  25795. var data = options.custom || polyhedra[type];
  25796. var nbfaces = data.face.length;
  25797. var faceUV = options.faceUV || new Array(nbfaces);
  25798. var faceColors = options.faceColors;
  25799. var flat = (options.flat === undefined) ? true : options.flat;
  25800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25801. var positions = [];
  25802. var indices = [];
  25803. var normals = [];
  25804. var uvs = [];
  25805. var colors = [];
  25806. var index = 0;
  25807. var faceIdx = 0; // face cursor in the array "indexes"
  25808. var indexes = [];
  25809. var i = 0;
  25810. var f = 0;
  25811. var u, v, ang, x, y, tmp;
  25812. // default face colors and UV if undefined
  25813. if (flat) {
  25814. for (f = 0; f < nbfaces; f++) {
  25815. if (faceColors && faceColors[f] === undefined) {
  25816. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25817. }
  25818. if (faceUV && faceUV[f] === undefined) {
  25819. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25820. }
  25821. }
  25822. }
  25823. if (!flat) {
  25824. for (i = 0; i < data.vertex.length; i++) {
  25825. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25826. uvs.push(0, 0);
  25827. }
  25828. for (f = 0; f < nbfaces; f++) {
  25829. for (i = 0; i < data.face[f].length - 2; i++) {
  25830. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25831. }
  25832. }
  25833. }
  25834. else {
  25835. for (f = 0; f < nbfaces; f++) {
  25836. var fl = data.face[f].length; // number of vertices of the current face
  25837. ang = 2 * Math.PI / fl;
  25838. x = 0.5 * Math.tan(ang / 2);
  25839. y = 0.5;
  25840. // positions, uvs, colors
  25841. for (i = 0; i < fl; i++) {
  25842. // positions
  25843. 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);
  25844. indexes.push(index);
  25845. index++;
  25846. // uvs
  25847. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25848. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25849. uvs.push(u, v);
  25850. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25851. y = x * Math.sin(ang) + y * Math.cos(ang);
  25852. x = tmp;
  25853. // colors
  25854. if (faceColors) {
  25855. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25856. }
  25857. }
  25858. // indices from indexes
  25859. for (i = 0; i < fl - 2; i++) {
  25860. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25861. }
  25862. faceIdx += fl;
  25863. }
  25864. }
  25865. VertexData.ComputeNormals(positions, indices, normals);
  25866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25867. var vertexData = new VertexData();
  25868. vertexData.positions = positions;
  25869. vertexData.indices = indices;
  25870. vertexData.normals = normals;
  25871. vertexData.uvs = uvs;
  25872. if (faceColors && flat) {
  25873. vertexData.colors = colors;
  25874. }
  25875. return vertexData;
  25876. };
  25877. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25878. VertexData.CreateTorusKnot = function (options) {
  25879. var indices = [];
  25880. var positions = [];
  25881. var normals = [];
  25882. var uvs = [];
  25883. var radius = options.radius || 2;
  25884. var tube = options.tube || 0.5;
  25885. var radialSegments = options.radialSegments || 32;
  25886. var tubularSegments = options.tubularSegments || 32;
  25887. var p = options.p || 2;
  25888. var q = options.q || 3;
  25889. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25890. // Helper
  25891. var getPos = function (angle) {
  25892. var cu = Math.cos(angle);
  25893. var su = Math.sin(angle);
  25894. var quOverP = q / p * angle;
  25895. var cs = Math.cos(quOverP);
  25896. var tx = radius * (2 + cs) * 0.5 * cu;
  25897. var ty = radius * (2 + cs) * su * 0.5;
  25898. var tz = radius * Math.sin(quOverP) * 0.5;
  25899. return new BABYLON.Vector3(tx, ty, tz);
  25900. };
  25901. // Vertices
  25902. var i;
  25903. var j;
  25904. for (i = 0; i <= radialSegments; i++) {
  25905. var modI = i % radialSegments;
  25906. var u = modI / radialSegments * 2 * p * Math.PI;
  25907. var p1 = getPos(u);
  25908. var p2 = getPos(u + 0.01);
  25909. var tang = p2.subtract(p1);
  25910. var n = p2.add(p1);
  25911. var bitan = BABYLON.Vector3.Cross(tang, n);
  25912. n = BABYLON.Vector3.Cross(bitan, tang);
  25913. bitan.normalize();
  25914. n.normalize();
  25915. for (j = 0; j < tubularSegments; j++) {
  25916. var modJ = j % tubularSegments;
  25917. var v = modJ / tubularSegments * 2 * Math.PI;
  25918. var cx = -tube * Math.cos(v);
  25919. var cy = tube * Math.sin(v);
  25920. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25921. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25922. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25923. uvs.push(i / radialSegments);
  25924. uvs.push(j / tubularSegments);
  25925. }
  25926. }
  25927. for (i = 0; i < radialSegments; i++) {
  25928. for (j = 0; j < tubularSegments; j++) {
  25929. var jNext = (j + 1) % tubularSegments;
  25930. var a = i * tubularSegments + j;
  25931. var b = (i + 1) * tubularSegments + j;
  25932. var c = (i + 1) * tubularSegments + jNext;
  25933. var d = i * tubularSegments + jNext;
  25934. indices.push(d);
  25935. indices.push(b);
  25936. indices.push(a);
  25937. indices.push(d);
  25938. indices.push(c);
  25939. indices.push(b);
  25940. }
  25941. }
  25942. // Normals
  25943. VertexData.ComputeNormals(positions, indices, normals);
  25944. // Sides
  25945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25946. // Result
  25947. var vertexData = new VertexData();
  25948. vertexData.indices = indices;
  25949. vertexData.positions = positions;
  25950. vertexData.normals = normals;
  25951. vertexData.uvs = uvs;
  25952. return vertexData;
  25953. };
  25954. // Tools
  25955. /**
  25956. * @param {any} - positions (number[] or Float32Array)
  25957. * @param {any} - indices (number[] or Uint16Array)
  25958. * @param {any} - normals (number[] or Float32Array)
  25959. */
  25960. VertexData.ComputeNormals = function (positions, indices, normals) {
  25961. var index = 0;
  25962. var p1p2x = 0.0;
  25963. var p1p2y = 0.0;
  25964. var p1p2z = 0.0;
  25965. var p3p2x = 0.0;
  25966. var p3p2y = 0.0;
  25967. var p3p2z = 0.0;
  25968. var faceNormalx = 0.0;
  25969. var faceNormaly = 0.0;
  25970. var faceNormalz = 0.0;
  25971. var length = 0.0;
  25972. var i1 = 0;
  25973. var i2 = 0;
  25974. var i3 = 0;
  25975. for (index = 0; index < positions.length; index++) {
  25976. normals[index] = 0.0;
  25977. }
  25978. // indice triplet = 1 face
  25979. var nbFaces = indices.length / 3;
  25980. for (index = 0; index < nbFaces; index++) {
  25981. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25982. i2 = indices[index * 3 + 1];
  25983. i3 = indices[index * 3 + 2];
  25984. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25985. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25986. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25987. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25988. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25989. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25990. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25991. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25992. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25993. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25994. length = (length === 0) ? 1.0 : length;
  25995. faceNormalx /= length; // normalize this normal
  25996. faceNormaly /= length;
  25997. faceNormalz /= length;
  25998. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25999. normals[i1 * 3 + 1] += faceNormaly;
  26000. normals[i1 * 3 + 2] += faceNormalz;
  26001. normals[i2 * 3] += faceNormalx;
  26002. normals[i2 * 3 + 1] += faceNormaly;
  26003. normals[i2 * 3 + 2] += faceNormalz;
  26004. normals[i3 * 3] += faceNormalx;
  26005. normals[i3 * 3 + 1] += faceNormaly;
  26006. normals[i3 * 3 + 2] += faceNormalz;
  26007. }
  26008. // last normalization of each normal
  26009. for (index = 0; index < normals.length / 3; index++) {
  26010. faceNormalx = normals[index * 3];
  26011. faceNormaly = normals[index * 3 + 1];
  26012. faceNormalz = normals[index * 3 + 2];
  26013. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26014. length = (length === 0) ? 1.0 : length;
  26015. faceNormalx /= length;
  26016. faceNormaly /= length;
  26017. faceNormalz /= length;
  26018. normals[index * 3] = faceNormalx;
  26019. normals[index * 3 + 1] = faceNormaly;
  26020. normals[index * 3 + 2] = faceNormalz;
  26021. }
  26022. };
  26023. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26024. var li = indices.length;
  26025. var ln = normals.length;
  26026. var i;
  26027. var n;
  26028. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26029. switch (sideOrientation) {
  26030. case BABYLON.Mesh.FRONTSIDE:
  26031. // nothing changed
  26032. break;
  26033. case BABYLON.Mesh.BACKSIDE:
  26034. var tmp;
  26035. // indices
  26036. for (i = 0; i < li; i += 3) {
  26037. tmp = indices[i];
  26038. indices[i] = indices[i + 2];
  26039. indices[i + 2] = tmp;
  26040. }
  26041. // normals
  26042. for (n = 0; n < ln; n++) {
  26043. normals[n] = -normals[n];
  26044. }
  26045. break;
  26046. case BABYLON.Mesh.DOUBLESIDE:
  26047. // positions
  26048. var lp = positions.length;
  26049. var l = lp / 3;
  26050. for (var p = 0; p < lp; p++) {
  26051. positions[lp + p] = positions[p];
  26052. }
  26053. // indices
  26054. for (i = 0; i < li; i += 3) {
  26055. indices[i + li] = indices[i + 2] + l;
  26056. indices[i + 1 + li] = indices[i + 1] + l;
  26057. indices[i + 2 + li] = indices[i] + l;
  26058. }
  26059. // normals
  26060. for (n = 0; n < ln; n++) {
  26061. normals[ln + n] = -normals[n];
  26062. }
  26063. // uvs
  26064. var lu = uvs.length;
  26065. for (var u = 0; u < lu; u++) {
  26066. uvs[u + lu] = uvs[u];
  26067. }
  26068. break;
  26069. }
  26070. };
  26071. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26072. var vertexData = new VertexData();
  26073. // positions
  26074. var positions = parsedVertexData.positions;
  26075. if (positions) {
  26076. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26077. }
  26078. // normals
  26079. var normals = parsedVertexData.normals;
  26080. if (normals) {
  26081. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26082. }
  26083. // uvs
  26084. var uvs = parsedVertexData.uvs;
  26085. if (uvs) {
  26086. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26087. }
  26088. // uv2s
  26089. var uv2s = parsedVertexData.uv2s;
  26090. if (uv2s) {
  26091. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26092. }
  26093. // uv3s
  26094. var uv3s = parsedVertexData.uv3s;
  26095. if (uv3s) {
  26096. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26097. }
  26098. // uv4s
  26099. var uv4s = parsedVertexData.uv4s;
  26100. if (uv4s) {
  26101. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26102. }
  26103. // uv5s
  26104. var uv5s = parsedVertexData.uv5s;
  26105. if (uv5s) {
  26106. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26107. }
  26108. // uv6s
  26109. var uv6s = parsedVertexData.uv6s;
  26110. if (uv6s) {
  26111. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26112. }
  26113. // colors
  26114. var colors = parsedVertexData.colors;
  26115. if (colors) {
  26116. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26117. }
  26118. // matricesIndices
  26119. var matricesIndices = parsedVertexData.matricesIndices;
  26120. if (matricesIndices) {
  26121. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26122. }
  26123. // matricesWeights
  26124. var matricesWeights = parsedVertexData.matricesWeights;
  26125. if (matricesWeights) {
  26126. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26127. }
  26128. // indices
  26129. var indices = parsedVertexData.indices;
  26130. if (indices) {
  26131. vertexData.indices = indices;
  26132. }
  26133. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26134. };
  26135. return VertexData;
  26136. })();
  26137. BABYLON.VertexData = VertexData;
  26138. })(BABYLON || (BABYLON = {}));
  26139. var BABYLON;
  26140. (function (BABYLON) {
  26141. var Tags = (function () {
  26142. function Tags() {
  26143. }
  26144. Tags.EnableFor = function (obj) {
  26145. obj._tags = obj._tags || {};
  26146. obj.hasTags = function () {
  26147. return Tags.HasTags(obj);
  26148. };
  26149. obj.addTags = function (tagsString) {
  26150. return Tags.AddTagsTo(obj, tagsString);
  26151. };
  26152. obj.removeTags = function (tagsString) {
  26153. return Tags.RemoveTagsFrom(obj, tagsString);
  26154. };
  26155. obj.matchesTagsQuery = function (tagsQuery) {
  26156. return Tags.MatchesQuery(obj, tagsQuery);
  26157. };
  26158. };
  26159. Tags.DisableFor = function (obj) {
  26160. delete obj._tags;
  26161. delete obj.hasTags;
  26162. delete obj.addTags;
  26163. delete obj.removeTags;
  26164. delete obj.matchesTagsQuery;
  26165. };
  26166. Tags.HasTags = function (obj) {
  26167. if (!obj._tags) {
  26168. return false;
  26169. }
  26170. return !BABYLON.Tools.IsEmpty(obj._tags);
  26171. };
  26172. Tags.GetTags = function (obj, asString) {
  26173. if (asString === void 0) { asString = true; }
  26174. if (!obj._tags) {
  26175. return null;
  26176. }
  26177. if (asString) {
  26178. var tagsArray = [];
  26179. for (var tag in obj._tags) {
  26180. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26181. tagsArray.push(tag);
  26182. }
  26183. }
  26184. return tagsArray.join(" ");
  26185. }
  26186. else {
  26187. return obj._tags;
  26188. }
  26189. };
  26190. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26191. // a tag cannot start with '||', '&&', and '!'
  26192. // it cannot contain whitespaces
  26193. Tags.AddTagsTo = function (obj, tagsString) {
  26194. if (!tagsString) {
  26195. return;
  26196. }
  26197. if (typeof tagsString !== "string") {
  26198. return;
  26199. }
  26200. var tags = tagsString.split(" ");
  26201. for (var t in tags) {
  26202. Tags._AddTagTo(obj, tags[t]);
  26203. }
  26204. };
  26205. Tags._AddTagTo = function (obj, tag) {
  26206. tag = tag.trim();
  26207. if (tag === "" || tag === "true" || tag === "false") {
  26208. return;
  26209. }
  26210. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26211. return;
  26212. }
  26213. Tags.EnableFor(obj);
  26214. obj._tags[tag] = true;
  26215. };
  26216. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26217. if (!Tags.HasTags(obj)) {
  26218. return;
  26219. }
  26220. var tags = tagsString.split(" ");
  26221. for (var t in tags) {
  26222. Tags._RemoveTagFrom(obj, tags[t]);
  26223. }
  26224. };
  26225. Tags._RemoveTagFrom = function (obj, tag) {
  26226. delete obj._tags[tag];
  26227. };
  26228. Tags.MatchesQuery = function (obj, tagsQuery) {
  26229. if (tagsQuery === undefined) {
  26230. return true;
  26231. }
  26232. if (tagsQuery === "") {
  26233. return Tags.HasTags(obj);
  26234. }
  26235. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26236. };
  26237. return Tags;
  26238. })();
  26239. BABYLON.Tags = Tags;
  26240. })(BABYLON || (BABYLON = {}));
  26241. var BABYLON;
  26242. (function (BABYLON) {
  26243. var Internals;
  26244. (function (Internals) {
  26245. var AndOrNotEvaluator = (function () {
  26246. function AndOrNotEvaluator() {
  26247. }
  26248. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26249. if (!query.match(/\([^\(\)]*\)/g)) {
  26250. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26251. }
  26252. else {
  26253. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26254. // remove parenthesis
  26255. r = r.slice(1, r.length - 1);
  26256. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26257. });
  26258. }
  26259. if (query === "true") {
  26260. return true;
  26261. }
  26262. if (query === "false") {
  26263. return false;
  26264. }
  26265. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26266. };
  26267. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26268. evaluateCallback = evaluateCallback || (function (r) {
  26269. return r === "true" ? true : false;
  26270. });
  26271. var result;
  26272. var or = parenthesisContent.split("||");
  26273. for (var i in or) {
  26274. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26275. var and = ori.split("&&");
  26276. if (and.length > 1) {
  26277. for (var j = 0; j < and.length; ++j) {
  26278. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26279. if (andj !== "true" && andj !== "false") {
  26280. if (andj[0] === "!") {
  26281. result = !evaluateCallback(andj.substring(1));
  26282. }
  26283. else {
  26284. result = evaluateCallback(andj);
  26285. }
  26286. }
  26287. else {
  26288. result = andj === "true" ? true : false;
  26289. }
  26290. if (!result) {
  26291. ori = "false";
  26292. break;
  26293. }
  26294. }
  26295. }
  26296. if (result || ori === "true") {
  26297. result = true;
  26298. break;
  26299. }
  26300. // result equals false (or undefined)
  26301. if (ori !== "true" && ori !== "false") {
  26302. if (ori[0] === "!") {
  26303. result = !evaluateCallback(ori.substring(1));
  26304. }
  26305. else {
  26306. result = evaluateCallback(ori);
  26307. }
  26308. }
  26309. else {
  26310. result = ori === "true" ? true : false;
  26311. }
  26312. }
  26313. // the whole parenthesis scope is replaced by 'true' or 'false'
  26314. return result ? "true" : "false";
  26315. };
  26316. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26317. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26318. // remove whitespaces
  26319. r = r.replace(/[\s]/g, function () { return ""; });
  26320. return r.length % 2 ? "!" : "";
  26321. });
  26322. booleanString = booleanString.trim();
  26323. if (booleanString === "!true") {
  26324. booleanString = "false";
  26325. }
  26326. else if (booleanString === "!false") {
  26327. booleanString = "true";
  26328. }
  26329. return booleanString;
  26330. };
  26331. return AndOrNotEvaluator;
  26332. })();
  26333. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26334. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26335. })(BABYLON || (BABYLON = {}));
  26336. var BABYLON;
  26337. (function (BABYLON) {
  26338. var PostProcessRenderPass = (function () {
  26339. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26340. this._enabled = true;
  26341. this._refCount = 0;
  26342. this._name = name;
  26343. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26344. this.setRenderList(renderList);
  26345. this._renderTexture.onBeforeRender = beforeRender;
  26346. this._renderTexture.onAfterRender = afterRender;
  26347. this._scene = scene;
  26348. this._renderList = renderList;
  26349. }
  26350. // private
  26351. PostProcessRenderPass.prototype._incRefCount = function () {
  26352. if (this._refCount === 0) {
  26353. this._scene.customRenderTargets.push(this._renderTexture);
  26354. }
  26355. return ++this._refCount;
  26356. };
  26357. PostProcessRenderPass.prototype._decRefCount = function () {
  26358. this._refCount--;
  26359. if (this._refCount <= 0) {
  26360. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26361. }
  26362. return this._refCount;
  26363. };
  26364. PostProcessRenderPass.prototype._update = function () {
  26365. this.setRenderList(this._renderList);
  26366. };
  26367. // public
  26368. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26369. this._renderTexture.renderList = renderList;
  26370. };
  26371. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26372. return this._renderTexture;
  26373. };
  26374. return PostProcessRenderPass;
  26375. })();
  26376. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26377. })(BABYLON || (BABYLON = {}));
  26378. var BABYLON;
  26379. (function (BABYLON) {
  26380. var PostProcessRenderEffect = (function () {
  26381. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26382. this._engine = engine;
  26383. this._name = name;
  26384. this._singleInstance = singleInstance || true;
  26385. this._getPostProcess = getPostProcess;
  26386. this._cameras = [];
  26387. this._indicesForCamera = [];
  26388. this._postProcesses = {};
  26389. this._renderPasses = {};
  26390. this._renderEffectAsPasses = {};
  26391. }
  26392. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26393. get: function () {
  26394. for (var index in this._postProcesses) {
  26395. if (!this._postProcesses[index].isSupported) {
  26396. return false;
  26397. }
  26398. }
  26399. return true;
  26400. },
  26401. enumerable: true,
  26402. configurable: true
  26403. });
  26404. PostProcessRenderEffect.prototype._update = function () {
  26405. for (var renderPassName in this._renderPasses) {
  26406. this._renderPasses[renderPassName]._update();
  26407. }
  26408. };
  26409. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26410. this._renderPasses[renderPass._name] = renderPass;
  26411. this._linkParameters();
  26412. };
  26413. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26414. delete this._renderPasses[renderPass._name];
  26415. this._linkParameters();
  26416. };
  26417. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26418. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26419. this._linkParameters();
  26420. };
  26421. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26422. for (var renderPassName in this._renderPasses) {
  26423. if (renderPassName === passName) {
  26424. return this._renderPasses[passName];
  26425. }
  26426. }
  26427. };
  26428. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26429. this._renderPasses = {};
  26430. this._linkParameters();
  26431. };
  26432. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26433. var cameraKey;
  26434. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26435. for (var i = 0; i < _cam.length; i++) {
  26436. var camera = _cam[i];
  26437. var cameraName = camera.name;
  26438. if (this._singleInstance) {
  26439. cameraKey = 0;
  26440. }
  26441. else {
  26442. cameraKey = cameraName;
  26443. }
  26444. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26445. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26446. if (!this._indicesForCamera[cameraName]) {
  26447. this._indicesForCamera[cameraName] = [];
  26448. }
  26449. this._indicesForCamera[cameraName].push(index);
  26450. if (this._cameras.indexOf(camera) === -1) {
  26451. this._cameras[cameraName] = camera;
  26452. }
  26453. for (var passName in this._renderPasses) {
  26454. this._renderPasses[passName]._incRefCount();
  26455. }
  26456. }
  26457. this._linkParameters();
  26458. };
  26459. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26460. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26461. for (var i = 0; i < _cam.length; i++) {
  26462. var camera = _cam[i];
  26463. var cameraName = camera.name;
  26464. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26465. var index = this._cameras.indexOf(cameraName);
  26466. this._indicesForCamera.splice(index, 1);
  26467. this._cameras.splice(index, 1);
  26468. for (var passName in this._renderPasses) {
  26469. this._renderPasses[passName]._decRefCount();
  26470. }
  26471. }
  26472. };
  26473. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26474. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26475. for (var i = 0; i < _cam.length; i++) {
  26476. var camera = _cam[i];
  26477. var cameraName = camera.name;
  26478. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26479. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26480. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26481. }
  26482. }
  26483. for (var passName in this._renderPasses) {
  26484. this._renderPasses[passName]._incRefCount();
  26485. }
  26486. }
  26487. };
  26488. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26489. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26490. for (var i = 0; i < _cam.length; i++) {
  26491. var camera = _cam[i];
  26492. var cameraName = camera.Name;
  26493. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26494. for (var passName in this._renderPasses) {
  26495. this._renderPasses[passName]._decRefCount();
  26496. }
  26497. }
  26498. };
  26499. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26500. if (this._singleInstance) {
  26501. return this._postProcesses[0];
  26502. }
  26503. else {
  26504. return this._postProcesses[camera.name];
  26505. }
  26506. };
  26507. PostProcessRenderEffect.prototype._linkParameters = function () {
  26508. var _this = this;
  26509. for (var index in this._postProcesses) {
  26510. if (this.applyParameters) {
  26511. this.applyParameters(this._postProcesses[index]);
  26512. }
  26513. this._postProcesses[index].onBeforeRender = function (effect) {
  26514. _this._linkTextures(effect);
  26515. };
  26516. }
  26517. };
  26518. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26519. for (var renderPassName in this._renderPasses) {
  26520. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26521. }
  26522. for (var renderEffectName in this._renderEffectAsPasses) {
  26523. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26524. }
  26525. };
  26526. return PostProcessRenderEffect;
  26527. })();
  26528. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26529. })(BABYLON || (BABYLON = {}));
  26530. var BABYLON;
  26531. (function (BABYLON) {
  26532. var PostProcessRenderPipeline = (function () {
  26533. function PostProcessRenderPipeline(engine, name) {
  26534. this._engine = engine;
  26535. this._name = name;
  26536. this._renderEffects = {};
  26537. this._renderEffectsForIsolatedPass = {};
  26538. this._cameras = [];
  26539. }
  26540. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26541. get: function () {
  26542. for (var renderEffectName in this._renderEffects) {
  26543. if (!this._renderEffects[renderEffectName].isSupported) {
  26544. return false;
  26545. }
  26546. }
  26547. return true;
  26548. },
  26549. enumerable: true,
  26550. configurable: true
  26551. });
  26552. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26553. this._renderEffects[renderEffect._name] = renderEffect;
  26554. };
  26555. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26556. var renderEffects = this._renderEffects[renderEffectName];
  26557. if (!renderEffects) {
  26558. return;
  26559. }
  26560. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26561. };
  26562. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26563. var renderEffects = this._renderEffects[renderEffectName];
  26564. if (!renderEffects) {
  26565. return;
  26566. }
  26567. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26568. };
  26569. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26570. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26571. var indicesToDelete = [];
  26572. var i;
  26573. for (i = 0; i < _cam.length; i++) {
  26574. var camera = _cam[i];
  26575. var cameraName = camera.name;
  26576. if (this._cameras.indexOf(camera) === -1) {
  26577. this._cameras[cameraName] = camera;
  26578. }
  26579. else if (unique) {
  26580. indicesToDelete.push(i);
  26581. }
  26582. }
  26583. for (i = 0; i < indicesToDelete.length; i++) {
  26584. cameras.splice(indicesToDelete[i], 1);
  26585. }
  26586. for (var renderEffectName in this._renderEffects) {
  26587. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26588. }
  26589. };
  26590. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26591. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26592. for (var renderEffectName in this._renderEffects) {
  26593. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26594. }
  26595. for (var i = 0; i < _cam.length; i++) {
  26596. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26597. }
  26598. };
  26599. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26600. var _this = this;
  26601. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26602. var pass = null;
  26603. var renderEffectName;
  26604. for (renderEffectName in this._renderEffects) {
  26605. pass = this._renderEffects[renderEffectName].getPass(passName);
  26606. if (pass != null) {
  26607. break;
  26608. }
  26609. }
  26610. if (pass === null) {
  26611. return;
  26612. }
  26613. for (renderEffectName in this._renderEffects) {
  26614. this._renderEffects[renderEffectName]._disable(_cam);
  26615. }
  26616. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26617. for (var i = 0; i < _cam.length; i++) {
  26618. var camera = _cam[i];
  26619. var cameraName = camera.name;
  26620. 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); });
  26621. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26622. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26623. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26624. }
  26625. };
  26626. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26627. var _this = this;
  26628. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26629. for (var i = 0; i < _cam.length; i++) {
  26630. var camera = _cam[i];
  26631. var cameraName = camera.name;
  26632. 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); });
  26633. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26634. }
  26635. for (var renderEffectName in this._renderEffects) {
  26636. this._renderEffects[renderEffectName]._enable(_cam);
  26637. }
  26638. };
  26639. PostProcessRenderPipeline.prototype._update = function () {
  26640. for (var renderEffectName in this._renderEffects) {
  26641. this._renderEffects[renderEffectName]._update();
  26642. }
  26643. for (var i = 0; i < this._cameras.length; i++) {
  26644. var cameraName = this._cameras[i].name;
  26645. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26646. this._renderEffectsForIsolatedPass[cameraName]._update();
  26647. }
  26648. }
  26649. };
  26650. PostProcessRenderPipeline.prototype.dispose = function () {
  26651. // Must be implemented by children
  26652. };
  26653. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26654. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26655. return PostProcessRenderPipeline;
  26656. })();
  26657. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26658. })(BABYLON || (BABYLON = {}));
  26659. var BABYLON;
  26660. (function (BABYLON) {
  26661. var PostProcessRenderPipelineManager = (function () {
  26662. function PostProcessRenderPipelineManager() {
  26663. this._renderPipelines = {};
  26664. }
  26665. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26666. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26667. };
  26668. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26669. var renderPipeline = this._renderPipelines[renderPipelineName];
  26670. if (!renderPipeline) {
  26671. return;
  26672. }
  26673. renderPipeline._attachCameras(cameras, unique);
  26674. };
  26675. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26676. var renderPipeline = this._renderPipelines[renderPipelineName];
  26677. if (!renderPipeline) {
  26678. return;
  26679. }
  26680. renderPipeline._detachCameras(cameras);
  26681. };
  26682. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26683. var renderPipeline = this._renderPipelines[renderPipelineName];
  26684. if (!renderPipeline) {
  26685. return;
  26686. }
  26687. renderPipeline._enableEffect(renderEffectName, cameras);
  26688. };
  26689. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26690. var renderPipeline = this._renderPipelines[renderPipelineName];
  26691. if (!renderPipeline) {
  26692. return;
  26693. }
  26694. renderPipeline._disableEffect(renderEffectName, cameras);
  26695. };
  26696. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26697. var renderPipeline = this._renderPipelines[renderPipelineName];
  26698. if (!renderPipeline) {
  26699. return;
  26700. }
  26701. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26702. };
  26703. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26704. var renderPipeline = this._renderPipelines[renderPipelineName];
  26705. if (!renderPipeline) {
  26706. return;
  26707. }
  26708. renderPipeline._disableDisplayOnlyPass(cameras);
  26709. };
  26710. PostProcessRenderPipelineManager.prototype.update = function () {
  26711. for (var renderPipelineName in this._renderPipelines) {
  26712. var pipeline = this._renderPipelines[renderPipelineName];
  26713. if (!pipeline.isSupported) {
  26714. pipeline.dispose();
  26715. delete this._renderPipelines[renderPipelineName];
  26716. }
  26717. else {
  26718. pipeline._update();
  26719. }
  26720. }
  26721. };
  26722. return PostProcessRenderPipelineManager;
  26723. })();
  26724. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26725. })(BABYLON || (BABYLON = {}));
  26726. var BABYLON;
  26727. (function (BABYLON) {
  26728. var BoundingBoxRenderer = (function () {
  26729. function BoundingBoxRenderer(scene) {
  26730. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26731. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26732. this.showBackLines = true;
  26733. this.renderList = new BABYLON.SmartArray(32);
  26734. this._scene = scene;
  26735. }
  26736. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26737. if (this._colorShader) {
  26738. return;
  26739. }
  26740. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26741. attributes: ["position"],
  26742. uniforms: ["worldViewProjection", "color"]
  26743. });
  26744. var engine = this._scene.getEngine();
  26745. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26746. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26747. 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]);
  26748. };
  26749. BoundingBoxRenderer.prototype.reset = function () {
  26750. this.renderList.reset();
  26751. };
  26752. BoundingBoxRenderer.prototype.render = function () {
  26753. if (this.renderList.length === 0) {
  26754. return;
  26755. }
  26756. this._prepareRessources();
  26757. if (!this._colorShader.isReady()) {
  26758. return;
  26759. }
  26760. var engine = this._scene.getEngine();
  26761. engine.setDepthWrite(false);
  26762. this._colorShader._preBind();
  26763. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26764. var boundingBox = this.renderList.data[boundingBoxIndex];
  26765. var min = boundingBox.minimum;
  26766. var max = boundingBox.maximum;
  26767. var diff = max.subtract(min);
  26768. var median = min.add(diff.scale(0.5));
  26769. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26770. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26771. .multiply(boundingBox.getWorldMatrix());
  26772. // VBOs
  26773. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26774. if (this.showBackLines) {
  26775. // Back
  26776. engine.setDepthFunctionToGreaterOrEqual();
  26777. this._scene.resetCachedMaterial();
  26778. this._colorShader.setColor4("color", this.backColor.toColor4());
  26779. this._colorShader.bind(worldMatrix);
  26780. // Draw order
  26781. engine.draw(false, 0, 24);
  26782. }
  26783. // Front
  26784. engine.setDepthFunctionToLess();
  26785. this._scene.resetCachedMaterial();
  26786. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26787. this._colorShader.bind(worldMatrix);
  26788. // Draw order
  26789. engine.draw(false, 0, 24);
  26790. }
  26791. this._colorShader.unbind();
  26792. engine.setDepthFunctionToLessOrEqual();
  26793. engine.setDepthWrite(true);
  26794. };
  26795. BoundingBoxRenderer.prototype.dispose = function () {
  26796. if (!this._colorShader) {
  26797. return;
  26798. }
  26799. this._colorShader.dispose();
  26800. this._vb.dispose();
  26801. this._scene.getEngine()._releaseBuffer(this._ib);
  26802. };
  26803. return BoundingBoxRenderer;
  26804. })();
  26805. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26806. })(BABYLON || (BABYLON = {}));
  26807. var BABYLON;
  26808. (function (BABYLON) {
  26809. var Condition = (function () {
  26810. function Condition(actionManager) {
  26811. this._actionManager = actionManager;
  26812. }
  26813. Condition.prototype.isValid = function () {
  26814. return true;
  26815. };
  26816. Condition.prototype._getProperty = function (propertyPath) {
  26817. return this._actionManager._getProperty(propertyPath);
  26818. };
  26819. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26820. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26821. };
  26822. return Condition;
  26823. })();
  26824. BABYLON.Condition = Condition;
  26825. var ValueCondition = (function (_super) {
  26826. __extends(ValueCondition, _super);
  26827. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26828. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26829. _super.call(this, actionManager);
  26830. this.propertyPath = propertyPath;
  26831. this.value = value;
  26832. this.operator = operator;
  26833. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26834. this._property = this._getProperty(this.propertyPath);
  26835. }
  26836. Object.defineProperty(ValueCondition, "IsEqual", {
  26837. get: function () {
  26838. return ValueCondition._IsEqual;
  26839. },
  26840. enumerable: true,
  26841. configurable: true
  26842. });
  26843. Object.defineProperty(ValueCondition, "IsDifferent", {
  26844. get: function () {
  26845. return ValueCondition._IsDifferent;
  26846. },
  26847. enumerable: true,
  26848. configurable: true
  26849. });
  26850. Object.defineProperty(ValueCondition, "IsGreater", {
  26851. get: function () {
  26852. return ValueCondition._IsGreater;
  26853. },
  26854. enumerable: true,
  26855. configurable: true
  26856. });
  26857. Object.defineProperty(ValueCondition, "IsLesser", {
  26858. get: function () {
  26859. return ValueCondition._IsLesser;
  26860. },
  26861. enumerable: true,
  26862. configurable: true
  26863. });
  26864. // Methods
  26865. ValueCondition.prototype.isValid = function () {
  26866. switch (this.operator) {
  26867. case ValueCondition.IsGreater:
  26868. return this._target[this._property] > this.value;
  26869. case ValueCondition.IsLesser:
  26870. return this._target[this._property] < this.value;
  26871. case ValueCondition.IsEqual:
  26872. case ValueCondition.IsDifferent:
  26873. var check;
  26874. if (this.value.equals) {
  26875. check = this.value.equals(this._target[this._property]);
  26876. }
  26877. else {
  26878. check = this.value === this._target[this._property];
  26879. }
  26880. return this.operator === ValueCondition.IsEqual ? check : !check;
  26881. }
  26882. return false;
  26883. };
  26884. // Statics
  26885. ValueCondition._IsEqual = 0;
  26886. ValueCondition._IsDifferent = 1;
  26887. ValueCondition._IsGreater = 2;
  26888. ValueCondition._IsLesser = 3;
  26889. return ValueCondition;
  26890. })(Condition);
  26891. BABYLON.ValueCondition = ValueCondition;
  26892. var PredicateCondition = (function (_super) {
  26893. __extends(PredicateCondition, _super);
  26894. function PredicateCondition(actionManager, predicate) {
  26895. _super.call(this, actionManager);
  26896. this.predicate = predicate;
  26897. }
  26898. PredicateCondition.prototype.isValid = function () {
  26899. return this.predicate();
  26900. };
  26901. return PredicateCondition;
  26902. })(Condition);
  26903. BABYLON.PredicateCondition = PredicateCondition;
  26904. var StateCondition = (function (_super) {
  26905. __extends(StateCondition, _super);
  26906. function StateCondition(actionManager, target, value) {
  26907. _super.call(this, actionManager);
  26908. this.value = value;
  26909. this._target = target;
  26910. }
  26911. // Methods
  26912. StateCondition.prototype.isValid = function () {
  26913. return this._target.state === this.value;
  26914. };
  26915. return StateCondition;
  26916. })(Condition);
  26917. BABYLON.StateCondition = StateCondition;
  26918. })(BABYLON || (BABYLON = {}));
  26919. var BABYLON;
  26920. (function (BABYLON) {
  26921. var Action = (function () {
  26922. function Action(triggerOptions, condition) {
  26923. this.triggerOptions = triggerOptions;
  26924. if (triggerOptions.parameter) {
  26925. this.trigger = triggerOptions.trigger;
  26926. this._triggerParameter = triggerOptions.parameter;
  26927. }
  26928. else {
  26929. this.trigger = triggerOptions;
  26930. }
  26931. this._nextActiveAction = this;
  26932. this._condition = condition;
  26933. }
  26934. // Methods
  26935. Action.prototype._prepare = function () {
  26936. };
  26937. Action.prototype.getTriggerParameter = function () {
  26938. return this._triggerParameter;
  26939. };
  26940. Action.prototype._executeCurrent = function (evt) {
  26941. if (this._nextActiveAction._condition) {
  26942. var condition = this._nextActiveAction._condition;
  26943. var currentRenderId = this._actionManager.getScene().getRenderId();
  26944. // We cache the current evaluation for the current frame
  26945. if (condition._evaluationId === currentRenderId) {
  26946. if (!condition._currentResult) {
  26947. return;
  26948. }
  26949. }
  26950. else {
  26951. condition._evaluationId = currentRenderId;
  26952. if (!condition.isValid()) {
  26953. condition._currentResult = false;
  26954. return;
  26955. }
  26956. condition._currentResult = true;
  26957. }
  26958. }
  26959. this._nextActiveAction.execute(evt);
  26960. this.skipToNextActiveAction();
  26961. };
  26962. Action.prototype.execute = function (evt) {
  26963. };
  26964. Action.prototype.skipToNextActiveAction = function () {
  26965. if (this._nextActiveAction._child) {
  26966. if (!this._nextActiveAction._child._actionManager) {
  26967. this._nextActiveAction._child._actionManager = this._actionManager;
  26968. }
  26969. this._nextActiveAction = this._nextActiveAction._child;
  26970. }
  26971. else {
  26972. this._nextActiveAction = this;
  26973. }
  26974. };
  26975. Action.prototype.then = function (action) {
  26976. this._child = action;
  26977. action._actionManager = this._actionManager;
  26978. action._prepare();
  26979. return action;
  26980. };
  26981. Action.prototype._getProperty = function (propertyPath) {
  26982. return this._actionManager._getProperty(propertyPath);
  26983. };
  26984. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26985. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26986. };
  26987. return Action;
  26988. })();
  26989. BABYLON.Action = Action;
  26990. })(BABYLON || (BABYLON = {}));
  26991. var BABYLON;
  26992. (function (BABYLON) {
  26993. /**
  26994. * ActionEvent is the event beint sent when an action is triggered.
  26995. */
  26996. var ActionEvent = (function () {
  26997. /**
  26998. * @constructor
  26999. * @param source The mesh or sprite that triggered the action.
  27000. * @param pointerX The X mouse cursor position at the time of the event
  27001. * @param pointerY The Y mouse cursor position at the time of the event
  27002. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27003. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27004. */
  27005. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27006. this.source = source;
  27007. this.pointerX = pointerX;
  27008. this.pointerY = pointerY;
  27009. this.meshUnderPointer = meshUnderPointer;
  27010. this.sourceEvent = sourceEvent;
  27011. this.additionalData = additionalData;
  27012. }
  27013. /**
  27014. * Helper function to auto-create an ActionEvent from a source mesh.
  27015. * @param source The source mesh that triggered the event
  27016. * @param evt {Event} The original (browser) event
  27017. */
  27018. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27019. var scene = source.getScene();
  27020. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27021. };
  27022. /**
  27023. * Helper function to auto-create an ActionEvent from a source mesh.
  27024. * @param source The source sprite that triggered the event
  27025. * @param scene Scene associated with the sprite
  27026. * @param evt {Event} The original (browser) event
  27027. */
  27028. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27029. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27030. };
  27031. /**
  27032. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27033. * @param scene the scene where the event occurred
  27034. * @param evt {Event} The original (browser) event
  27035. */
  27036. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27037. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27038. };
  27039. return ActionEvent;
  27040. })();
  27041. BABYLON.ActionEvent = ActionEvent;
  27042. /**
  27043. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27044. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27045. */
  27046. var ActionManager = (function () {
  27047. function ActionManager(scene) {
  27048. // Members
  27049. this.actions = new Array();
  27050. this._scene = scene;
  27051. scene._actionManagers.push(this);
  27052. }
  27053. Object.defineProperty(ActionManager, "NothingTrigger", {
  27054. get: function () {
  27055. return ActionManager._NothingTrigger;
  27056. },
  27057. enumerable: true,
  27058. configurable: true
  27059. });
  27060. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27061. get: function () {
  27062. return ActionManager._OnPickTrigger;
  27063. },
  27064. enumerable: true,
  27065. configurable: true
  27066. });
  27067. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27068. get: function () {
  27069. return ActionManager._OnLeftPickTrigger;
  27070. },
  27071. enumerable: true,
  27072. configurable: true
  27073. });
  27074. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27075. get: function () {
  27076. return ActionManager._OnRightPickTrigger;
  27077. },
  27078. enumerable: true,
  27079. configurable: true
  27080. });
  27081. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27082. get: function () {
  27083. return ActionManager._OnCenterPickTrigger;
  27084. },
  27085. enumerable: true,
  27086. configurable: true
  27087. });
  27088. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27089. get: function () {
  27090. return ActionManager._OnPickDownTrigger;
  27091. },
  27092. enumerable: true,
  27093. configurable: true
  27094. });
  27095. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27096. get: function () {
  27097. return ActionManager._OnPickUpTrigger;
  27098. },
  27099. enumerable: true,
  27100. configurable: true
  27101. });
  27102. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27103. /// This trigger will only be raised if you also declared a OnPickDown
  27104. get: function () {
  27105. return ActionManager._OnPickOutTrigger;
  27106. },
  27107. enumerable: true,
  27108. configurable: true
  27109. });
  27110. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27111. get: function () {
  27112. return ActionManager._OnLongPressTrigger;
  27113. },
  27114. enumerable: true,
  27115. configurable: true
  27116. });
  27117. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27118. get: function () {
  27119. return ActionManager._OnPointerOverTrigger;
  27120. },
  27121. enumerable: true,
  27122. configurable: true
  27123. });
  27124. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27125. get: function () {
  27126. return ActionManager._OnPointerOutTrigger;
  27127. },
  27128. enumerable: true,
  27129. configurable: true
  27130. });
  27131. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27132. get: function () {
  27133. return ActionManager._OnEveryFrameTrigger;
  27134. },
  27135. enumerable: true,
  27136. configurable: true
  27137. });
  27138. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27139. get: function () {
  27140. return ActionManager._OnIntersectionEnterTrigger;
  27141. },
  27142. enumerable: true,
  27143. configurable: true
  27144. });
  27145. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27146. get: function () {
  27147. return ActionManager._OnIntersectionExitTrigger;
  27148. },
  27149. enumerable: true,
  27150. configurable: true
  27151. });
  27152. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27153. get: function () {
  27154. return ActionManager._OnKeyDownTrigger;
  27155. },
  27156. enumerable: true,
  27157. configurable: true
  27158. });
  27159. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27160. get: function () {
  27161. return ActionManager._OnKeyUpTrigger;
  27162. },
  27163. enumerable: true,
  27164. configurable: true
  27165. });
  27166. // Methods
  27167. ActionManager.prototype.dispose = function () {
  27168. var index = this._scene._actionManagers.indexOf(this);
  27169. if (index > -1) {
  27170. this._scene._actionManagers.splice(index, 1);
  27171. }
  27172. };
  27173. ActionManager.prototype.getScene = function () {
  27174. return this._scene;
  27175. };
  27176. /**
  27177. * Does this action manager handles actions of any of the given triggers
  27178. * @param {number[]} triggers - the triggers to be tested
  27179. * @return {boolean} whether one (or more) of the triggers is handeled
  27180. */
  27181. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27182. for (var index = 0; index < this.actions.length; index++) {
  27183. var action = this.actions[index];
  27184. if (triggers.indexOf(action.trigger) > -1) {
  27185. return true;
  27186. }
  27187. }
  27188. return false;
  27189. };
  27190. /**
  27191. * Does this action manager handles actions of a given trigger
  27192. * @param {number} trigger - the trigger to be tested
  27193. * @return {boolean} whether the trigger is handeled
  27194. */
  27195. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27196. for (var index = 0; index < this.actions.length; index++) {
  27197. var action = this.actions[index];
  27198. if (action.trigger === trigger) {
  27199. return true;
  27200. }
  27201. }
  27202. return false;
  27203. };
  27204. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27205. /**
  27206. * Does this action manager has pointer triggers
  27207. * @return {boolean} whether or not it has pointer triggers
  27208. */
  27209. get: function () {
  27210. for (var index = 0; index < this.actions.length; index++) {
  27211. var action = this.actions[index];
  27212. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27213. return true;
  27214. }
  27215. }
  27216. return false;
  27217. },
  27218. enumerable: true,
  27219. configurable: true
  27220. });
  27221. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27222. /**
  27223. * Does this action manager has pick triggers
  27224. * @return {boolean} whether or not it has pick triggers
  27225. */
  27226. get: function () {
  27227. for (var index = 0; index < this.actions.length; index++) {
  27228. var action = this.actions[index];
  27229. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27230. return true;
  27231. }
  27232. }
  27233. return false;
  27234. },
  27235. enumerable: true,
  27236. configurable: true
  27237. });
  27238. /**
  27239. * Registers an action to this action manager
  27240. * @param {BABYLON.Action} action - the action to be registered
  27241. * @return {BABYLON.Action} the action amended (prepared) after registration
  27242. */
  27243. ActionManager.prototype.registerAction = function (action) {
  27244. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27245. if (this.getScene().actionManager !== this) {
  27246. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27247. return null;
  27248. }
  27249. }
  27250. this.actions.push(action);
  27251. action._actionManager = this;
  27252. action._prepare();
  27253. return action;
  27254. };
  27255. /**
  27256. * Process a specific trigger
  27257. * @param {number} trigger - the trigger to process
  27258. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27259. */
  27260. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27261. for (var index = 0; index < this.actions.length; index++) {
  27262. var action = this.actions[index];
  27263. if (action.trigger === trigger) {
  27264. if (trigger === ActionManager.OnKeyUpTrigger
  27265. || trigger === ActionManager.OnKeyDownTrigger) {
  27266. var parameter = action.getTriggerParameter();
  27267. if (parameter) {
  27268. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27269. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27270. if (actualkey !== parameter.toLowerCase()) {
  27271. continue;
  27272. }
  27273. }
  27274. }
  27275. action._executeCurrent(evt);
  27276. }
  27277. }
  27278. };
  27279. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27280. var properties = propertyPath.split(".");
  27281. for (var index = 0; index < properties.length - 1; index++) {
  27282. target = target[properties[index]];
  27283. }
  27284. return target;
  27285. };
  27286. ActionManager.prototype._getProperty = function (propertyPath) {
  27287. var properties = propertyPath.split(".");
  27288. return properties[properties.length - 1];
  27289. };
  27290. ActionManager.Parse = function (parsedActions, object, scene) {
  27291. var actionManager = new BABYLON.ActionManager(scene);
  27292. if (object === null)
  27293. scene.actionManager = actionManager;
  27294. else
  27295. object.actionManager = actionManager;
  27296. // instanciate a new object
  27297. var instanciate = function (name, params) {
  27298. var newInstance = Object.create(BABYLON[name].prototype);
  27299. newInstance.constructor.apply(newInstance, params);
  27300. return newInstance;
  27301. };
  27302. var parseParameter = function (name, value, target, propertyPath) {
  27303. if (propertyPath === null) {
  27304. // String, boolean or float
  27305. var floatValue = parseFloat(value);
  27306. if (value === "true" || value === "false")
  27307. return value === "true";
  27308. else
  27309. return isNaN(floatValue) ? value : floatValue;
  27310. }
  27311. var effectiveTarget = propertyPath.split(".");
  27312. var values = value.split(",");
  27313. // Get effective Target
  27314. for (var i = 0; i < effectiveTarget.length; i++) {
  27315. target = target[effectiveTarget[i]];
  27316. }
  27317. // Return appropriate value with its type
  27318. if (typeof (target) === "boolean")
  27319. return values[0] === "true";
  27320. if (typeof (target) === "string")
  27321. return values[0];
  27322. // Parameters with multiple values such as Vector3 etc.
  27323. var split = new Array();
  27324. for (var i = 0; i < values.length; i++)
  27325. split.push(parseFloat(values[i]));
  27326. if (target instanceof BABYLON.Vector3)
  27327. return BABYLON.Vector3.FromArray(split);
  27328. if (target instanceof BABYLON.Vector4)
  27329. return BABYLON.Vector4.FromArray(split);
  27330. if (target instanceof BABYLON.Color3)
  27331. return BABYLON.Color3.FromArray(split);
  27332. if (target instanceof BABYLON.Color4)
  27333. return BABYLON.Color4.FromArray(split);
  27334. return parseFloat(values[0]);
  27335. };
  27336. // traverse graph per trigger
  27337. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27338. if (combineArray === void 0) { combineArray = null; }
  27339. if (parsedAction.detached)
  27340. return;
  27341. var parameters = new Array();
  27342. var target = null;
  27343. var propertyPath = null;
  27344. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27345. // Parameters
  27346. if (parsedAction.type === 2)
  27347. parameters.push(actionManager);
  27348. else
  27349. parameters.push(trigger);
  27350. if (combine) {
  27351. var actions = new Array();
  27352. for (var j = 0; j < parsedAction.combine.length; j++) {
  27353. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27354. }
  27355. parameters.push(actions);
  27356. }
  27357. else {
  27358. for (var i = 0; i < parsedAction.properties.length; i++) {
  27359. var value = parsedAction.properties[i].value;
  27360. var name = parsedAction.properties[i].name;
  27361. var targetType = parsedAction.properties[i].targetType;
  27362. if (name === "target")
  27363. if (targetType !== null && targetType === "SceneProperties")
  27364. value = target = scene;
  27365. else
  27366. value = target = scene.getNodeByName(value);
  27367. else if (name === "parent")
  27368. value = scene.getNodeByName(value);
  27369. else if (name === "sound")
  27370. value = scene.getSoundByName(value);
  27371. else if (name !== "propertyPath") {
  27372. if (parsedAction.type === 2 && name === "operator")
  27373. value = BABYLON.ValueCondition[value];
  27374. else
  27375. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27376. }
  27377. else {
  27378. propertyPath = value;
  27379. }
  27380. parameters.push(value);
  27381. }
  27382. }
  27383. if (combineArray === null) {
  27384. parameters.push(condition);
  27385. }
  27386. else {
  27387. parameters.push(null);
  27388. }
  27389. // If interpolate value action
  27390. if (parsedAction.name === "InterpolateValueAction") {
  27391. var param = parameters[parameters.length - 2];
  27392. parameters[parameters.length - 1] = param;
  27393. parameters[parameters.length - 2] = condition;
  27394. }
  27395. // Action or condition(s) and not CombineAction
  27396. var newAction = instanciate(parsedAction.name, parameters);
  27397. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27398. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27399. if (action)
  27400. action.then(nothing);
  27401. else
  27402. actionManager.registerAction(nothing);
  27403. action = nothing;
  27404. }
  27405. if (combineArray === null) {
  27406. if (newAction instanceof BABYLON.Condition) {
  27407. condition = newAction;
  27408. newAction = action;
  27409. }
  27410. else {
  27411. condition = null;
  27412. if (action)
  27413. action.then(newAction);
  27414. else
  27415. actionManager.registerAction(newAction);
  27416. }
  27417. }
  27418. else {
  27419. combineArray.push(newAction);
  27420. }
  27421. for (var i = 0; i < parsedAction.children.length; i++)
  27422. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27423. };
  27424. // triggers
  27425. for (var i = 0; i < parsedActions.children.length; i++) {
  27426. var triggerParams;
  27427. var trigger = parsedActions.children[i];
  27428. if (trigger.properties.length > 0) {
  27429. var param = trigger.properties[0].value;
  27430. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27431. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27432. }
  27433. else
  27434. triggerParams = BABYLON.ActionManager[trigger.name];
  27435. for (var j = 0; j < trigger.children.length; j++) {
  27436. if (!trigger.detached)
  27437. traverse(trigger.children[j], triggerParams, null, null);
  27438. }
  27439. }
  27440. };
  27441. // Statics
  27442. ActionManager._NothingTrigger = 0;
  27443. ActionManager._OnPickTrigger = 1;
  27444. ActionManager._OnLeftPickTrigger = 2;
  27445. ActionManager._OnRightPickTrigger = 3;
  27446. ActionManager._OnCenterPickTrigger = 4;
  27447. ActionManager._OnPickDownTrigger = 5;
  27448. ActionManager._OnPickUpTrigger = 6;
  27449. ActionManager._OnLongPressTrigger = 7;
  27450. ActionManager._OnPointerOverTrigger = 8;
  27451. ActionManager._OnPointerOutTrigger = 9;
  27452. ActionManager._OnEveryFrameTrigger = 10;
  27453. ActionManager._OnIntersectionEnterTrigger = 11;
  27454. ActionManager._OnIntersectionExitTrigger = 12;
  27455. ActionManager._OnKeyDownTrigger = 13;
  27456. ActionManager._OnKeyUpTrigger = 14;
  27457. ActionManager._OnPickOutTrigger = 15;
  27458. ActionManager.DragMovementThreshold = 10; // in pixels
  27459. ActionManager.LongPressDelay = 500; // in milliseconds
  27460. return ActionManager;
  27461. })();
  27462. BABYLON.ActionManager = ActionManager;
  27463. })(BABYLON || (BABYLON = {}));
  27464. var BABYLON;
  27465. (function (BABYLON) {
  27466. var InterpolateValueAction = (function (_super) {
  27467. __extends(InterpolateValueAction, _super);
  27468. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27469. if (duration === void 0) { duration = 1000; }
  27470. _super.call(this, triggerOptions, condition);
  27471. this.propertyPath = propertyPath;
  27472. this.value = value;
  27473. this.duration = duration;
  27474. this.stopOtherAnimations = stopOtherAnimations;
  27475. this.onInterpolationDone = onInterpolationDone;
  27476. this._target = target;
  27477. }
  27478. InterpolateValueAction.prototype._prepare = function () {
  27479. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27480. this._property = this._getProperty(this.propertyPath);
  27481. };
  27482. InterpolateValueAction.prototype.execute = function () {
  27483. var scene = this._actionManager.getScene();
  27484. var keys = [
  27485. {
  27486. frame: 0,
  27487. value: this._target[this._property]
  27488. }, {
  27489. frame: 100,
  27490. value: this.value
  27491. }
  27492. ];
  27493. var dataType;
  27494. if (typeof this.value === "number") {
  27495. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27496. }
  27497. else if (this.value instanceof BABYLON.Color3) {
  27498. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27499. }
  27500. else if (this.value instanceof BABYLON.Vector3) {
  27501. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27502. }
  27503. else if (this.value instanceof BABYLON.Matrix) {
  27504. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27505. }
  27506. else if (this.value instanceof BABYLON.Quaternion) {
  27507. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27508. }
  27509. else {
  27510. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27511. return;
  27512. }
  27513. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27514. animation.setKeys(keys);
  27515. if (this.stopOtherAnimations) {
  27516. scene.stopAnimation(this._target);
  27517. }
  27518. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27519. };
  27520. return InterpolateValueAction;
  27521. })(BABYLON.Action);
  27522. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27523. })(BABYLON || (BABYLON = {}));
  27524. var BABYLON;
  27525. (function (BABYLON) {
  27526. var SwitchBooleanAction = (function (_super) {
  27527. __extends(SwitchBooleanAction, _super);
  27528. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27529. _super.call(this, triggerOptions, condition);
  27530. this.propertyPath = propertyPath;
  27531. this._target = target;
  27532. }
  27533. SwitchBooleanAction.prototype._prepare = function () {
  27534. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27535. this._property = this._getProperty(this.propertyPath);
  27536. };
  27537. SwitchBooleanAction.prototype.execute = function () {
  27538. this._target[this._property] = !this._target[this._property];
  27539. };
  27540. return SwitchBooleanAction;
  27541. })(BABYLON.Action);
  27542. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27543. var SetStateAction = (function (_super) {
  27544. __extends(SetStateAction, _super);
  27545. function SetStateAction(triggerOptions, target, value, condition) {
  27546. _super.call(this, triggerOptions, condition);
  27547. this.value = value;
  27548. this._target = target;
  27549. }
  27550. SetStateAction.prototype.execute = function () {
  27551. this._target.state = this.value;
  27552. };
  27553. return SetStateAction;
  27554. })(BABYLON.Action);
  27555. BABYLON.SetStateAction = SetStateAction;
  27556. var SetValueAction = (function (_super) {
  27557. __extends(SetValueAction, _super);
  27558. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27559. _super.call(this, triggerOptions, condition);
  27560. this.propertyPath = propertyPath;
  27561. this.value = value;
  27562. this._target = target;
  27563. }
  27564. SetValueAction.prototype._prepare = function () {
  27565. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27566. this._property = this._getProperty(this.propertyPath);
  27567. };
  27568. SetValueAction.prototype.execute = function () {
  27569. this._target[this._property] = this.value;
  27570. };
  27571. return SetValueAction;
  27572. })(BABYLON.Action);
  27573. BABYLON.SetValueAction = SetValueAction;
  27574. var IncrementValueAction = (function (_super) {
  27575. __extends(IncrementValueAction, _super);
  27576. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27577. _super.call(this, triggerOptions, condition);
  27578. this.propertyPath = propertyPath;
  27579. this.value = value;
  27580. this._target = target;
  27581. }
  27582. IncrementValueAction.prototype._prepare = function () {
  27583. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27584. this._property = this._getProperty(this.propertyPath);
  27585. if (typeof this._target[this._property] !== "number") {
  27586. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27587. }
  27588. };
  27589. IncrementValueAction.prototype.execute = function () {
  27590. this._target[this._property] += this.value;
  27591. };
  27592. return IncrementValueAction;
  27593. })(BABYLON.Action);
  27594. BABYLON.IncrementValueAction = IncrementValueAction;
  27595. var PlayAnimationAction = (function (_super) {
  27596. __extends(PlayAnimationAction, _super);
  27597. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27598. _super.call(this, triggerOptions, condition);
  27599. this.from = from;
  27600. this.to = to;
  27601. this.loop = loop;
  27602. this._target = target;
  27603. }
  27604. PlayAnimationAction.prototype._prepare = function () {
  27605. };
  27606. PlayAnimationAction.prototype.execute = function () {
  27607. var scene = this._actionManager.getScene();
  27608. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27609. };
  27610. return PlayAnimationAction;
  27611. })(BABYLON.Action);
  27612. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27613. var StopAnimationAction = (function (_super) {
  27614. __extends(StopAnimationAction, _super);
  27615. function StopAnimationAction(triggerOptions, target, condition) {
  27616. _super.call(this, triggerOptions, condition);
  27617. this._target = target;
  27618. }
  27619. StopAnimationAction.prototype._prepare = function () {
  27620. };
  27621. StopAnimationAction.prototype.execute = function () {
  27622. var scene = this._actionManager.getScene();
  27623. scene.stopAnimation(this._target);
  27624. };
  27625. return StopAnimationAction;
  27626. })(BABYLON.Action);
  27627. BABYLON.StopAnimationAction = StopAnimationAction;
  27628. var DoNothingAction = (function (_super) {
  27629. __extends(DoNothingAction, _super);
  27630. function DoNothingAction(triggerOptions, condition) {
  27631. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27632. _super.call(this, triggerOptions, condition);
  27633. }
  27634. DoNothingAction.prototype.execute = function () {
  27635. };
  27636. return DoNothingAction;
  27637. })(BABYLON.Action);
  27638. BABYLON.DoNothingAction = DoNothingAction;
  27639. var CombineAction = (function (_super) {
  27640. __extends(CombineAction, _super);
  27641. function CombineAction(triggerOptions, children, condition) {
  27642. _super.call(this, triggerOptions, condition);
  27643. this.children = children;
  27644. }
  27645. CombineAction.prototype._prepare = function () {
  27646. for (var index = 0; index < this.children.length; index++) {
  27647. this.children[index]._actionManager = this._actionManager;
  27648. this.children[index]._prepare();
  27649. }
  27650. };
  27651. CombineAction.prototype.execute = function (evt) {
  27652. for (var index = 0; index < this.children.length; index++) {
  27653. this.children[index].execute(evt);
  27654. }
  27655. };
  27656. return CombineAction;
  27657. })(BABYLON.Action);
  27658. BABYLON.CombineAction = CombineAction;
  27659. var ExecuteCodeAction = (function (_super) {
  27660. __extends(ExecuteCodeAction, _super);
  27661. function ExecuteCodeAction(triggerOptions, func, condition) {
  27662. _super.call(this, triggerOptions, condition);
  27663. this.func = func;
  27664. }
  27665. ExecuteCodeAction.prototype.execute = function (evt) {
  27666. this.func(evt);
  27667. };
  27668. return ExecuteCodeAction;
  27669. })(BABYLON.Action);
  27670. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27671. var SetParentAction = (function (_super) {
  27672. __extends(SetParentAction, _super);
  27673. function SetParentAction(triggerOptions, target, parent, condition) {
  27674. _super.call(this, triggerOptions, condition);
  27675. this._target = target;
  27676. this._parent = parent;
  27677. }
  27678. SetParentAction.prototype._prepare = function () {
  27679. };
  27680. SetParentAction.prototype.execute = function () {
  27681. if (this._target.parent === this._parent) {
  27682. return;
  27683. }
  27684. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27685. invertParentWorldMatrix.invert();
  27686. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27687. this._target.parent = this._parent;
  27688. };
  27689. return SetParentAction;
  27690. })(BABYLON.Action);
  27691. BABYLON.SetParentAction = SetParentAction;
  27692. var PlaySoundAction = (function (_super) {
  27693. __extends(PlaySoundAction, _super);
  27694. function PlaySoundAction(triggerOptions, sound, condition) {
  27695. _super.call(this, triggerOptions, condition);
  27696. this._sound = sound;
  27697. }
  27698. PlaySoundAction.prototype._prepare = function () {
  27699. };
  27700. PlaySoundAction.prototype.execute = function () {
  27701. if (this._sound !== undefined)
  27702. this._sound.play();
  27703. };
  27704. return PlaySoundAction;
  27705. })(BABYLON.Action);
  27706. BABYLON.PlaySoundAction = PlaySoundAction;
  27707. var StopSoundAction = (function (_super) {
  27708. __extends(StopSoundAction, _super);
  27709. function StopSoundAction(triggerOptions, sound, condition) {
  27710. _super.call(this, triggerOptions, condition);
  27711. this._sound = sound;
  27712. }
  27713. StopSoundAction.prototype._prepare = function () {
  27714. };
  27715. StopSoundAction.prototype.execute = function () {
  27716. if (this._sound !== undefined)
  27717. this._sound.stop();
  27718. };
  27719. return StopSoundAction;
  27720. })(BABYLON.Action);
  27721. BABYLON.StopSoundAction = StopSoundAction;
  27722. })(BABYLON || (BABYLON = {}));
  27723. var BABYLON;
  27724. (function (BABYLON) {
  27725. var Geometry = (function () {
  27726. function Geometry(id, scene, vertexData, updatable, mesh) {
  27727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27728. this._totalVertices = 0;
  27729. this._isDisposed = false;
  27730. this.id = id;
  27731. this._engine = scene.getEngine();
  27732. this._meshes = [];
  27733. this._scene = scene;
  27734. //Init vertex buffer cache
  27735. this._vertexBuffers = {};
  27736. this._indices = [];
  27737. // vertexData
  27738. if (vertexData) {
  27739. this.setAllVerticesData(vertexData, updatable);
  27740. }
  27741. else {
  27742. this._totalVertices = 0;
  27743. this._indices = [];
  27744. }
  27745. // applyToMesh
  27746. if (mesh) {
  27747. this.applyToMesh(mesh);
  27748. mesh.computeWorldMatrix(true);
  27749. }
  27750. }
  27751. Object.defineProperty(Geometry.prototype, "extend", {
  27752. get: function () {
  27753. return this._extend;
  27754. },
  27755. enumerable: true,
  27756. configurable: true
  27757. });
  27758. Geometry.prototype.getScene = function () {
  27759. return this._scene;
  27760. };
  27761. Geometry.prototype.getEngine = function () {
  27762. return this._engine;
  27763. };
  27764. Geometry.prototype.isReady = function () {
  27765. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27766. };
  27767. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27768. vertexData.applyToGeometry(this, updatable);
  27769. this.notifyUpdate();
  27770. };
  27771. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27772. if (this._vertexBuffers[kind]) {
  27773. this._vertexBuffers[kind].dispose();
  27774. }
  27775. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27776. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27777. stride = this._vertexBuffers[kind].getStrideSize();
  27778. this._totalVertices = data.length / stride;
  27779. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27780. var meshes = this._meshes;
  27781. var numOfMeshes = meshes.length;
  27782. for (var index = 0; index < numOfMeshes; index++) {
  27783. var mesh = meshes[index];
  27784. mesh._resetPointsArrayCache();
  27785. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27786. mesh._createGlobalSubMesh();
  27787. mesh.computeWorldMatrix(true);
  27788. }
  27789. }
  27790. this.notifyUpdate(kind);
  27791. };
  27792. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27793. var vertexBuffer = this.getVertexBuffer(kind);
  27794. if (!vertexBuffer) {
  27795. return;
  27796. }
  27797. vertexBuffer.updateDirectly(data, offset);
  27798. this.notifyUpdate(kind);
  27799. };
  27800. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27801. var vertexBuffer = this.getVertexBuffer(kind);
  27802. if (!vertexBuffer) {
  27803. return;
  27804. }
  27805. vertexBuffer.update(data);
  27806. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27807. var stride = vertexBuffer.getStrideSize();
  27808. this._totalVertices = data.length / stride;
  27809. if (updateExtends) {
  27810. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27811. }
  27812. var meshes = this._meshes;
  27813. var numOfMeshes = meshes.length;
  27814. for (var index = 0; index < numOfMeshes; index++) {
  27815. var mesh = meshes[index];
  27816. mesh._resetPointsArrayCache();
  27817. if (updateExtends) {
  27818. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27819. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27820. var subMesh = mesh.subMeshes[subIndex];
  27821. subMesh.refreshBoundingInfo();
  27822. }
  27823. }
  27824. }
  27825. }
  27826. this.notifyUpdate(kind);
  27827. };
  27828. Geometry.prototype.getTotalVertices = function () {
  27829. if (!this.isReady()) {
  27830. return 0;
  27831. }
  27832. return this._totalVertices;
  27833. };
  27834. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27835. var vertexBuffer = this.getVertexBuffer(kind);
  27836. if (!vertexBuffer) {
  27837. return null;
  27838. }
  27839. var orig = vertexBuffer.getData();
  27840. if (!copyWhenShared || this._meshes.length === 1) {
  27841. return orig;
  27842. }
  27843. else {
  27844. var len = orig.length;
  27845. var copy = [];
  27846. for (var i = 0; i < len; i++) {
  27847. copy.push(orig[i]);
  27848. }
  27849. return copy;
  27850. }
  27851. };
  27852. Geometry.prototype.getVertexBuffer = function (kind) {
  27853. if (!this.isReady()) {
  27854. return null;
  27855. }
  27856. return this._vertexBuffers[kind];
  27857. };
  27858. Geometry.prototype.getVertexBuffers = function () {
  27859. if (!this.isReady()) {
  27860. return null;
  27861. }
  27862. return this._vertexBuffers;
  27863. };
  27864. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27865. if (!this._vertexBuffers) {
  27866. if (this._delayInfo) {
  27867. return this._delayInfo.indexOf(kind) !== -1;
  27868. }
  27869. return false;
  27870. }
  27871. return this._vertexBuffers[kind] !== undefined;
  27872. };
  27873. Geometry.prototype.getVerticesDataKinds = function () {
  27874. var result = [];
  27875. var kind;
  27876. if (!this._vertexBuffers && this._delayInfo) {
  27877. for (kind in this._delayInfo) {
  27878. result.push(kind);
  27879. }
  27880. }
  27881. else {
  27882. for (kind in this._vertexBuffers) {
  27883. result.push(kind);
  27884. }
  27885. }
  27886. return result;
  27887. };
  27888. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27889. if (this._indexBuffer) {
  27890. this._engine._releaseBuffer(this._indexBuffer);
  27891. }
  27892. this._indices = indices;
  27893. if (this._meshes.length !== 0 && this._indices) {
  27894. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27895. }
  27896. if (totalVertices !== undefined) {
  27897. this._totalVertices = totalVertices;
  27898. }
  27899. var meshes = this._meshes;
  27900. var numOfMeshes = meshes.length;
  27901. for (var index = 0; index < numOfMeshes; index++) {
  27902. meshes[index]._createGlobalSubMesh();
  27903. }
  27904. this.notifyUpdate();
  27905. };
  27906. Geometry.prototype.getTotalIndices = function () {
  27907. if (!this.isReady()) {
  27908. return 0;
  27909. }
  27910. return this._indices.length;
  27911. };
  27912. Geometry.prototype.getIndices = function (copyWhenShared) {
  27913. if (!this.isReady()) {
  27914. return null;
  27915. }
  27916. var orig = this._indices;
  27917. if (!copyWhenShared || this._meshes.length === 1) {
  27918. return orig;
  27919. }
  27920. else {
  27921. var len = orig.length;
  27922. var copy = [];
  27923. for (var i = 0; i < len; i++) {
  27924. copy.push(orig[i]);
  27925. }
  27926. return copy;
  27927. }
  27928. };
  27929. Geometry.prototype.getIndexBuffer = function () {
  27930. if (!this.isReady()) {
  27931. return null;
  27932. }
  27933. return this._indexBuffer;
  27934. };
  27935. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27936. var meshes = this._meshes;
  27937. var index = meshes.indexOf(mesh);
  27938. if (index === -1) {
  27939. return;
  27940. }
  27941. for (var kind in this._vertexBuffers) {
  27942. this._vertexBuffers[kind].dispose();
  27943. }
  27944. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27945. this._indexBuffer = null;
  27946. }
  27947. meshes.splice(index, 1);
  27948. mesh._geometry = null;
  27949. if (meshes.length === 0 && shouldDispose) {
  27950. this.dispose();
  27951. }
  27952. };
  27953. Geometry.prototype.applyToMesh = function (mesh) {
  27954. if (mesh._geometry === this) {
  27955. return;
  27956. }
  27957. var previousGeometry = mesh._geometry;
  27958. if (previousGeometry) {
  27959. previousGeometry.releaseForMesh(mesh);
  27960. }
  27961. var meshes = this._meshes;
  27962. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27963. mesh._geometry = this;
  27964. this._scene.pushGeometry(this);
  27965. meshes.push(mesh);
  27966. if (this.isReady()) {
  27967. this._applyToMesh(mesh);
  27968. }
  27969. else {
  27970. mesh._boundingInfo = this._boundingInfo;
  27971. }
  27972. };
  27973. Geometry.prototype._applyToMesh = function (mesh) {
  27974. var numOfMeshes = this._meshes.length;
  27975. // vertexBuffers
  27976. for (var kind in this._vertexBuffers) {
  27977. if (numOfMeshes === 1) {
  27978. this._vertexBuffers[kind].create();
  27979. }
  27980. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27981. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27982. mesh._resetPointsArrayCache();
  27983. if (!this._extend) {
  27984. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27985. }
  27986. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27987. mesh._createGlobalSubMesh();
  27988. //bounding info was just created again, world matrix should be applied again.
  27989. mesh._updateBoundingInfo();
  27990. }
  27991. }
  27992. // indexBuffer
  27993. if (numOfMeshes === 1 && this._indices) {
  27994. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27995. }
  27996. if (this._indexBuffer) {
  27997. this._indexBuffer.references = numOfMeshes;
  27998. }
  27999. };
  28000. Geometry.prototype.notifyUpdate = function (kind) {
  28001. if (this.onGeometryUpdated) {
  28002. this.onGeometryUpdated(this, kind);
  28003. }
  28004. };
  28005. Geometry.prototype.load = function (scene, onLoaded) {
  28006. var _this = this;
  28007. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28008. return;
  28009. }
  28010. if (this.isReady()) {
  28011. if (onLoaded) {
  28012. onLoaded();
  28013. }
  28014. return;
  28015. }
  28016. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28017. scene._addPendingData(this);
  28018. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28019. _this._delayLoadingFunction(JSON.parse(data), _this);
  28020. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28021. _this._delayInfo = [];
  28022. scene._removePendingData(_this);
  28023. var meshes = _this._meshes;
  28024. var numOfMeshes = meshes.length;
  28025. for (var index = 0; index < numOfMeshes; index++) {
  28026. _this._applyToMesh(meshes[index]);
  28027. }
  28028. if (onLoaded) {
  28029. onLoaded();
  28030. }
  28031. }, function () { }, scene.database);
  28032. };
  28033. Geometry.prototype.isDisposed = function () {
  28034. return this._isDisposed;
  28035. };
  28036. Geometry.prototype.dispose = function () {
  28037. var meshes = this._meshes;
  28038. var numOfMeshes = meshes.length;
  28039. var index;
  28040. for (index = 0; index < numOfMeshes; index++) {
  28041. this.releaseForMesh(meshes[index]);
  28042. }
  28043. this._meshes = [];
  28044. for (var kind in this._vertexBuffers) {
  28045. this._vertexBuffers[kind].dispose();
  28046. }
  28047. this._vertexBuffers = [];
  28048. this._totalVertices = 0;
  28049. if (this._indexBuffer) {
  28050. this._engine._releaseBuffer(this._indexBuffer);
  28051. }
  28052. this._indexBuffer = null;
  28053. this._indices = [];
  28054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28055. this.delayLoadingFile = null;
  28056. this._delayLoadingFunction = null;
  28057. this._delayInfo = [];
  28058. this._boundingInfo = null;
  28059. this._scene.removeGeometry(this);
  28060. this._isDisposed = true;
  28061. };
  28062. Geometry.prototype.copy = function (id) {
  28063. var vertexData = new BABYLON.VertexData();
  28064. vertexData.indices = [];
  28065. var indices = this.getIndices();
  28066. for (var index = 0; index < indices.length; index++) {
  28067. vertexData.indices.push(indices[index]);
  28068. }
  28069. var updatable = false;
  28070. var stopChecking = false;
  28071. var kind;
  28072. for (kind in this._vertexBuffers) {
  28073. // using slice() to make a copy of the array and not just reference it
  28074. var data = this.getVerticesData(kind);
  28075. if (data instanceof Float32Array) {
  28076. vertexData.set(new Float32Array(data), kind);
  28077. }
  28078. else {
  28079. vertexData.set(data.slice(0), kind);
  28080. }
  28081. if (!stopChecking) {
  28082. updatable = this.getVertexBuffer(kind).isUpdatable();
  28083. stopChecking = !updatable;
  28084. }
  28085. }
  28086. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28087. geometry.delayLoadState = this.delayLoadState;
  28088. geometry.delayLoadingFile = this.delayLoadingFile;
  28089. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28090. for (kind in this._delayInfo) {
  28091. geometry._delayInfo = geometry._delayInfo || [];
  28092. geometry._delayInfo.push(kind);
  28093. }
  28094. // Bounding info
  28095. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28096. return geometry;
  28097. };
  28098. Geometry.prototype.serialize = function () {
  28099. var serializationObject = {};
  28100. serializationObject.id = this.id;
  28101. if (BABYLON.Tags.HasTags(this)) {
  28102. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28103. }
  28104. return serializationObject;
  28105. };
  28106. Geometry.prototype.serializeVerticeData = function () {
  28107. var serializationObject = this.serialize();
  28108. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28109. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28110. }
  28111. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28112. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28113. }
  28114. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28115. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28116. }
  28117. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28118. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28119. }
  28120. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28121. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28122. }
  28123. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28124. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28125. }
  28126. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28127. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28128. }
  28129. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28130. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28131. }
  28132. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28133. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28134. }
  28135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28136. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28137. serializationObject.matricesIndices._isExpanded = true;
  28138. }
  28139. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28140. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28141. }
  28142. serializationObject.indices = this.getIndices();
  28143. return serializationObject;
  28144. };
  28145. // Statics
  28146. Geometry.ExtractFromMesh = function (mesh, id) {
  28147. var geometry = mesh._geometry;
  28148. if (!geometry) {
  28149. return null;
  28150. }
  28151. return geometry.copy(id);
  28152. };
  28153. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28154. // be aware Math.random() could cause collisions
  28155. Geometry.RandomId = function () {
  28156. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28157. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28158. return v.toString(16);
  28159. });
  28160. };
  28161. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28162. var scene = mesh.getScene();
  28163. // Geometry
  28164. var geometryId = parsedGeometry.geometryId;
  28165. if (geometryId) {
  28166. var geometry = scene.getGeometryByID(geometryId);
  28167. if (geometry) {
  28168. geometry.applyToMesh(mesh);
  28169. }
  28170. }
  28171. else if (parsedGeometry instanceof ArrayBuffer) {
  28172. var binaryInfo = mesh._binaryInfo;
  28173. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28174. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28175. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28176. }
  28177. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28178. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28179. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28180. }
  28181. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28182. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28183. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28184. }
  28185. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28186. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28187. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28188. }
  28189. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28190. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28191. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28192. }
  28193. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28194. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28195. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28196. }
  28197. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28198. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28199. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28200. }
  28201. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28202. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28203. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28204. }
  28205. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28206. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28207. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28208. }
  28209. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28210. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28211. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28212. }
  28213. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28214. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28216. }
  28217. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28218. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28219. mesh.setIndices(indicesData);
  28220. }
  28221. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28222. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28223. mesh.subMeshes = [];
  28224. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28225. var materialIndex = subMeshesData[(i * 5) + 0];
  28226. var verticesStart = subMeshesData[(i * 5) + 1];
  28227. var verticesCount = subMeshesData[(i * 5) + 2];
  28228. var indexStart = subMeshesData[(i * 5) + 3];
  28229. var indexCount = subMeshesData[(i * 5) + 4];
  28230. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28231. }
  28232. }
  28233. }
  28234. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28235. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28236. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28237. if (parsedGeometry.uvs) {
  28238. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28239. }
  28240. if (parsedGeometry.uvs2) {
  28241. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28242. }
  28243. if (parsedGeometry.uvs3) {
  28244. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28245. }
  28246. if (parsedGeometry.uvs4) {
  28247. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28248. }
  28249. if (parsedGeometry.uvs5) {
  28250. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28251. }
  28252. if (parsedGeometry.uvs6) {
  28253. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28254. }
  28255. if (parsedGeometry.colors) {
  28256. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28257. }
  28258. if (parsedGeometry.matricesIndices) {
  28259. if (!parsedGeometry.matricesIndices._isExpanded) {
  28260. var floatIndices = [];
  28261. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28262. var matricesIndex = parsedGeometry.matricesIndices[i];
  28263. floatIndices.push(matricesIndex & 0x000000FF);
  28264. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28265. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28266. floatIndices.push(matricesIndex >> 24);
  28267. }
  28268. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28269. }
  28270. else {
  28271. delete parsedGeometry.matricesIndices._isExpanded;
  28272. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28273. }
  28274. }
  28275. if (parsedGeometry.matricesIndicesExtra) {
  28276. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28277. var floatIndices = [];
  28278. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28279. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28280. floatIndices.push(matricesIndex & 0x000000FF);
  28281. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28282. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28283. floatIndices.push(matricesIndex >> 24);
  28284. }
  28285. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28286. }
  28287. else {
  28288. delete parsedGeometry.matricesIndices._isExpanded;
  28289. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28290. }
  28291. }
  28292. if (parsedGeometry.matricesWeights) {
  28293. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28294. }
  28295. if (parsedGeometry.matricesWeightsExtra) {
  28296. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28297. }
  28298. mesh.setIndices(parsedGeometry.indices);
  28299. }
  28300. // SubMeshes
  28301. if (parsedGeometry.subMeshes) {
  28302. mesh.subMeshes = [];
  28303. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28304. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28305. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28306. }
  28307. }
  28308. // Flat shading
  28309. if (mesh._shouldGenerateFlatShading) {
  28310. mesh.convertToFlatShadedMesh();
  28311. delete mesh._shouldGenerateFlatShading;
  28312. }
  28313. // Update
  28314. mesh.computeWorldMatrix(true);
  28315. // Octree
  28316. if (scene['_selectionOctree']) {
  28317. scene['_selectionOctree'].addMesh(mesh);
  28318. }
  28319. };
  28320. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28321. if (scene.getGeometryByID(parsedVertexData.id)) {
  28322. return null; // null since geometry could be something else than a box...
  28323. }
  28324. var geometry = new Geometry(parsedVertexData.id, scene);
  28325. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28326. if (parsedVertexData.delayLoadingFile) {
  28327. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28328. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28329. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28330. geometry._delayInfo = [];
  28331. if (parsedVertexData.hasUVs) {
  28332. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28333. }
  28334. if (parsedVertexData.hasUVs2) {
  28335. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28336. }
  28337. if (parsedVertexData.hasUVs3) {
  28338. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28339. }
  28340. if (parsedVertexData.hasUVs4) {
  28341. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28342. }
  28343. if (parsedVertexData.hasUVs5) {
  28344. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28345. }
  28346. if (parsedVertexData.hasUVs6) {
  28347. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28348. }
  28349. if (parsedVertexData.hasColors) {
  28350. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28351. }
  28352. if (parsedVertexData.hasMatricesIndices) {
  28353. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28354. }
  28355. if (parsedVertexData.hasMatricesWeights) {
  28356. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28357. }
  28358. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28359. }
  28360. else {
  28361. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28362. }
  28363. scene.pushGeometry(geometry, true);
  28364. return geometry;
  28365. };
  28366. return Geometry;
  28367. })();
  28368. BABYLON.Geometry = Geometry;
  28369. /////// Primitives //////////////////////////////////////////////
  28370. var Geometry;
  28371. (function (Geometry) {
  28372. var Primitives;
  28373. (function (Primitives) {
  28374. /// Abstract class
  28375. var _Primitive = (function (_super) {
  28376. __extends(_Primitive, _super);
  28377. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28378. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28379. this._canBeRegenerated = _canBeRegenerated;
  28380. this._beingRegenerated = true;
  28381. this.regenerate();
  28382. this._beingRegenerated = false;
  28383. }
  28384. _Primitive.prototype.canBeRegenerated = function () {
  28385. return this._canBeRegenerated;
  28386. };
  28387. _Primitive.prototype.regenerate = function () {
  28388. if (!this._canBeRegenerated) {
  28389. return;
  28390. }
  28391. this._beingRegenerated = true;
  28392. this.setAllVerticesData(this._regenerateVertexData(), false);
  28393. this._beingRegenerated = false;
  28394. };
  28395. _Primitive.prototype.asNewGeometry = function (id) {
  28396. return _super.prototype.copy.call(this, id);
  28397. };
  28398. // overrides
  28399. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28400. if (!this._beingRegenerated) {
  28401. return;
  28402. }
  28403. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28404. };
  28405. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28406. if (!this._beingRegenerated) {
  28407. return;
  28408. }
  28409. _super.prototype.setVerticesData.call(this, kind, data, false);
  28410. };
  28411. // to override
  28412. // protected
  28413. _Primitive.prototype._regenerateVertexData = function () {
  28414. throw new Error("Abstract method");
  28415. };
  28416. _Primitive.prototype.copy = function (id) {
  28417. throw new Error("Must be overriden in sub-classes.");
  28418. };
  28419. _Primitive.prototype.serialize = function () {
  28420. var serializationObject = _super.prototype.serialize.call(this);
  28421. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28422. return serializationObject;
  28423. };
  28424. return _Primitive;
  28425. })(Geometry);
  28426. Primitives._Primitive = _Primitive;
  28427. var Ribbon = (function (_super) {
  28428. __extends(Ribbon, _super);
  28429. // Members
  28430. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28431. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28432. _super.call(this, id, scene, canBeRegenerated, mesh);
  28433. this.pathArray = pathArray;
  28434. this.closeArray = closeArray;
  28435. this.closePath = closePath;
  28436. this.offset = offset;
  28437. this.side = side;
  28438. }
  28439. Ribbon.prototype._regenerateVertexData = function () {
  28440. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28441. };
  28442. Ribbon.prototype.copy = function (id) {
  28443. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28444. };
  28445. return Ribbon;
  28446. })(_Primitive);
  28447. Primitives.Ribbon = Ribbon;
  28448. var Box = (function (_super) {
  28449. __extends(Box, _super);
  28450. // Members
  28451. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28453. _super.call(this, id, scene, canBeRegenerated, mesh);
  28454. this.size = size;
  28455. this.side = side;
  28456. }
  28457. Box.prototype._regenerateVertexData = function () {
  28458. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28459. };
  28460. Box.prototype.copy = function (id) {
  28461. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28462. };
  28463. Box.prototype.serialize = function () {
  28464. var serializationObject = _super.prototype.serialize.call(this);
  28465. serializationObject.size = this.size;
  28466. return serializationObject;
  28467. };
  28468. Box.Parse = function (parsedBox, scene) {
  28469. if (scene.getGeometryByID(parsedBox.id)) {
  28470. return null; // null since geometry could be something else than a box...
  28471. }
  28472. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28473. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28474. scene.pushGeometry(box, true);
  28475. return box;
  28476. };
  28477. return Box;
  28478. })(_Primitive);
  28479. Primitives.Box = Box;
  28480. var Sphere = (function (_super) {
  28481. __extends(Sphere, _super);
  28482. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28483. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28484. _super.call(this, id, scene, canBeRegenerated, mesh);
  28485. this.segments = segments;
  28486. this.diameter = diameter;
  28487. this.side = side;
  28488. }
  28489. Sphere.prototype._regenerateVertexData = function () {
  28490. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28491. };
  28492. Sphere.prototype.copy = function (id) {
  28493. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28494. };
  28495. Sphere.prototype.serialize = function () {
  28496. var serializationObject = _super.prototype.serialize.call(this);
  28497. serializationObject.segments = this.segments;
  28498. serializationObject.diameter = this.diameter;
  28499. return serializationObject;
  28500. };
  28501. Sphere.Parse = function (parsedSphere, scene) {
  28502. if (scene.getGeometryByID(parsedSphere.id)) {
  28503. return null; // null since geometry could be something else than a sphere...
  28504. }
  28505. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28506. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28507. scene.pushGeometry(sphere, true);
  28508. return sphere;
  28509. };
  28510. return Sphere;
  28511. })(_Primitive);
  28512. Primitives.Sphere = Sphere;
  28513. var Disc = (function (_super) {
  28514. __extends(Disc, _super);
  28515. // Members
  28516. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28517. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28518. _super.call(this, id, scene, canBeRegenerated, mesh);
  28519. this.radius = radius;
  28520. this.tessellation = tessellation;
  28521. this.side = side;
  28522. }
  28523. Disc.prototype._regenerateVertexData = function () {
  28524. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28525. };
  28526. Disc.prototype.copy = function (id) {
  28527. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28528. };
  28529. return Disc;
  28530. })(_Primitive);
  28531. Primitives.Disc = Disc;
  28532. var Cylinder = (function (_super) {
  28533. __extends(Cylinder, _super);
  28534. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28535. if (subdivisions === void 0) { subdivisions = 1; }
  28536. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28537. _super.call(this, id, scene, canBeRegenerated, mesh);
  28538. this.height = height;
  28539. this.diameterTop = diameterTop;
  28540. this.diameterBottom = diameterBottom;
  28541. this.tessellation = tessellation;
  28542. this.subdivisions = subdivisions;
  28543. this.side = side;
  28544. }
  28545. Cylinder.prototype._regenerateVertexData = function () {
  28546. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28547. };
  28548. Cylinder.prototype.copy = function (id) {
  28549. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28550. };
  28551. Cylinder.prototype.serialize = function () {
  28552. var serializationObject = _super.prototype.serialize.call(this);
  28553. serializationObject.height = this.height;
  28554. serializationObject.diameterTop = this.diameterTop;
  28555. serializationObject.diameterBottom = this.diameterBottom;
  28556. serializationObject.tessellation = this.tessellation;
  28557. return serializationObject;
  28558. };
  28559. Cylinder.Parse = function (parsedCylinder, scene) {
  28560. if (scene.getGeometryByID(parsedCylinder.id)) {
  28561. return null; // null since geometry could be something else than a cylinder...
  28562. }
  28563. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28564. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28565. scene.pushGeometry(cylinder, true);
  28566. return cylinder;
  28567. };
  28568. return Cylinder;
  28569. })(_Primitive);
  28570. Primitives.Cylinder = Cylinder;
  28571. var Torus = (function (_super) {
  28572. __extends(Torus, _super);
  28573. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28574. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28575. _super.call(this, id, scene, canBeRegenerated, mesh);
  28576. this.diameter = diameter;
  28577. this.thickness = thickness;
  28578. this.tessellation = tessellation;
  28579. this.side = side;
  28580. }
  28581. Torus.prototype._regenerateVertexData = function () {
  28582. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28583. };
  28584. Torus.prototype.copy = function (id) {
  28585. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28586. };
  28587. Torus.prototype.serialize = function () {
  28588. var serializationObject = _super.prototype.serialize.call(this);
  28589. serializationObject.diameter = this.diameter;
  28590. serializationObject.thickness = this.thickness;
  28591. serializationObject.tessellation = this.tessellation;
  28592. return serializationObject;
  28593. };
  28594. Torus.Parse = function (parsedTorus, scene) {
  28595. if (scene.getGeometryByID(parsedTorus.id)) {
  28596. return null; // null since geometry could be something else than a torus...
  28597. }
  28598. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28599. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28600. scene.pushGeometry(torus, true);
  28601. return torus;
  28602. };
  28603. return Torus;
  28604. })(_Primitive);
  28605. Primitives.Torus = Torus;
  28606. var Ground = (function (_super) {
  28607. __extends(Ground, _super);
  28608. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28609. _super.call(this, id, scene, canBeRegenerated, mesh);
  28610. this.width = width;
  28611. this.height = height;
  28612. this.subdivisions = subdivisions;
  28613. }
  28614. Ground.prototype._regenerateVertexData = function () {
  28615. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28616. };
  28617. Ground.prototype.copy = function (id) {
  28618. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28619. };
  28620. Ground.prototype.serialize = function () {
  28621. var serializationObject = _super.prototype.serialize.call(this);
  28622. serializationObject.width = this.width;
  28623. serializationObject.height = this.height;
  28624. serializationObject.subdivisions = this.subdivisions;
  28625. return serializationObject;
  28626. };
  28627. Ground.Parse = function (parsedGround, scene) {
  28628. if (scene.getGeometryByID(parsedGround.id)) {
  28629. return null; // null since geometry could be something else than a ground...
  28630. }
  28631. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28632. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28633. scene.pushGeometry(ground, true);
  28634. return ground;
  28635. };
  28636. return Ground;
  28637. })(_Primitive);
  28638. Primitives.Ground = Ground;
  28639. var TiledGround = (function (_super) {
  28640. __extends(TiledGround, _super);
  28641. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28642. _super.call(this, id, scene, canBeRegenerated, mesh);
  28643. this.xmin = xmin;
  28644. this.zmin = zmin;
  28645. this.xmax = xmax;
  28646. this.zmax = zmax;
  28647. this.subdivisions = subdivisions;
  28648. this.precision = precision;
  28649. }
  28650. TiledGround.prototype._regenerateVertexData = function () {
  28651. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28652. };
  28653. TiledGround.prototype.copy = function (id) {
  28654. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28655. };
  28656. return TiledGround;
  28657. })(_Primitive);
  28658. Primitives.TiledGround = TiledGround;
  28659. var Plane = (function (_super) {
  28660. __extends(Plane, _super);
  28661. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28662. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28663. _super.call(this, id, scene, canBeRegenerated, mesh);
  28664. this.size = size;
  28665. this.side = side;
  28666. }
  28667. Plane.prototype._regenerateVertexData = function () {
  28668. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28669. };
  28670. Plane.prototype.copy = function (id) {
  28671. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28672. };
  28673. Plane.prototype.serialize = function () {
  28674. var serializationObject = _super.prototype.serialize.call(this);
  28675. serializationObject.size = this.size;
  28676. return serializationObject;
  28677. };
  28678. Plane.Parse = function (parsedPlane, scene) {
  28679. if (scene.getGeometryByID(parsedPlane.id)) {
  28680. return null; // null since geometry could be something else than a ground...
  28681. }
  28682. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28683. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28684. scene.pushGeometry(plane, true);
  28685. return plane;
  28686. };
  28687. return Plane;
  28688. })(_Primitive);
  28689. Primitives.Plane = Plane;
  28690. var TorusKnot = (function (_super) {
  28691. __extends(TorusKnot, _super);
  28692. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28693. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28694. _super.call(this, id, scene, canBeRegenerated, mesh);
  28695. this.radius = radius;
  28696. this.tube = tube;
  28697. this.radialSegments = radialSegments;
  28698. this.tubularSegments = tubularSegments;
  28699. this.p = p;
  28700. this.q = q;
  28701. this.side = side;
  28702. }
  28703. TorusKnot.prototype._regenerateVertexData = function () {
  28704. 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 });
  28705. };
  28706. TorusKnot.prototype.copy = function (id) {
  28707. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28708. };
  28709. TorusKnot.prototype.serialize = function () {
  28710. var serializationObject = _super.prototype.serialize.call(this);
  28711. serializationObject.radius = this.radius;
  28712. serializationObject.tube = this.tube;
  28713. serializationObject.radialSegments = this.radialSegments;
  28714. serializationObject.tubularSegments = this.tubularSegments;
  28715. serializationObject.p = this.p;
  28716. serializationObject.q = this.q;
  28717. return serializationObject;
  28718. };
  28719. ;
  28720. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28721. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28722. return null; // null since geometry could be something else than a ground...
  28723. }
  28724. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28725. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28726. scene.pushGeometry(torusKnot, true);
  28727. return torusKnot;
  28728. };
  28729. return TorusKnot;
  28730. })(_Primitive);
  28731. Primitives.TorusKnot = TorusKnot;
  28732. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28733. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28734. })(BABYLON || (BABYLON = {}));
  28735. var BABYLON;
  28736. (function (BABYLON) {
  28737. var GroundMesh = (function (_super) {
  28738. __extends(GroundMesh, _super);
  28739. function GroundMesh(name, scene) {
  28740. _super.call(this, name, scene);
  28741. this.generateOctree = false;
  28742. this._worldInverse = new BABYLON.Matrix();
  28743. }
  28744. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28745. get: function () {
  28746. return this._subdivisions;
  28747. },
  28748. enumerable: true,
  28749. configurable: true
  28750. });
  28751. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28752. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28753. this._subdivisions = chunksCount;
  28754. this.subdivide(this._subdivisions);
  28755. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28756. };
  28757. /**
  28758. * Returns a height (y) value in the Worl system :
  28759. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28760. * Returns the ground y position if (x, z) are outside the ground surface.
  28761. * Not pertinent if the ground is rotated.
  28762. */
  28763. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28764. // express x and y in the ground local system
  28765. x -= this.position.x;
  28766. z -= this.position.z;
  28767. x /= this.scaling.x;
  28768. z /= this.scaling.z;
  28769. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28770. return this.position.y;
  28771. }
  28772. if (!this._heightQuads || this._heightQuads.length == 0) {
  28773. this._initHeightQuads();
  28774. this._computeHeightQuads();
  28775. }
  28776. var facet = this._getFacetAt(x, z);
  28777. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28778. // return y in the World system
  28779. return y * this.scaling.y + this.position.y;
  28780. };
  28781. /**
  28782. * Returns a normalized vector (Vector3) orthogonal to the ground
  28783. * at the ground coordinates (x, z) expressed in the World system.
  28784. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28785. * Not pertinent if the ground is rotated.
  28786. */
  28787. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28788. var normal = new BABYLON.Vector3(0, 1, 0);
  28789. this.getNormalAtCoordinatesToRef(x, z, normal);
  28790. return normal;
  28791. };
  28792. /**
  28793. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28794. * at the ground coordinates (x, z) expressed in the World system.
  28795. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28796. * Not pertinent if the ground is rotated.
  28797. */
  28798. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28799. // express x and y in the ground local system
  28800. x -= this.position.x;
  28801. z -= this.position.z;
  28802. x /= this.scaling.x;
  28803. z /= this.scaling.z;
  28804. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28805. return;
  28806. }
  28807. if (!this._heightQuads || this._heightQuads.length == 0) {
  28808. this._initHeightQuads();
  28809. this._computeHeightQuads();
  28810. }
  28811. var facet = this._getFacetAt(x, z);
  28812. ref.x = facet.x;
  28813. ref.y = facet.y;
  28814. ref.z = facet.z;
  28815. };
  28816. /**
  28817. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28818. * if the ground has been updated.
  28819. * This can be used in the render loop
  28820. */
  28821. GroundMesh.prototype.updateCoordinateHeights = function () {
  28822. if (!this._heightQuads || this._heightQuads.length == 0) {
  28823. this._initHeightQuads();
  28824. }
  28825. this._computeHeightQuads();
  28826. };
  28827. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28828. GroundMesh.prototype._getFacetAt = function (x, z) {
  28829. // retrieve col and row from x, z coordinates in the ground local system
  28830. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28831. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28832. var quad = this._heightQuads[row * this._subdivisions + col];
  28833. var facet;
  28834. if (z < quad.slope.x * x + quad.slope.y) {
  28835. facet = quad.facet1;
  28836. }
  28837. else {
  28838. facet = quad.facet2;
  28839. }
  28840. return facet;
  28841. };
  28842. // Creates and populates the heightMap array with "facet" elements :
  28843. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28844. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28845. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28846. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28847. GroundMesh.prototype._initHeightQuads = function () {
  28848. this._heightQuads = new Array();
  28849. for (var row = 0; row < this._subdivisions; row++) {
  28850. for (var col = 0; col < this._subdivisions; col++) {
  28851. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  28852. this._heightQuads[row * this._subdivisions + col] = quad;
  28853. }
  28854. }
  28855. };
  28856. // Compute each quad element values and update the the heightMap array :
  28857. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28858. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28859. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28860. GroundMesh.prototype._computeHeightQuads = function () {
  28861. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28862. var v1 = BABYLON.Tmp.Vector3[0];
  28863. var v2 = BABYLON.Tmp.Vector3[1];
  28864. var v3 = BABYLON.Tmp.Vector3[2];
  28865. var v4 = BABYLON.Tmp.Vector3[3];
  28866. var v1v2 = BABYLON.Tmp.Vector3[4];
  28867. var v1v3 = BABYLON.Tmp.Vector3[5];
  28868. var v1v4 = BABYLON.Tmp.Vector3[6];
  28869. var norm1 = BABYLON.Tmp.Vector3[7];
  28870. var norm2 = BABYLON.Tmp.Vector3[8];
  28871. var i = 0;
  28872. var j = 0;
  28873. var k = 0;
  28874. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28875. var h = 0;
  28876. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28877. var d2 = 0;
  28878. for (var row = 0; row < this._subdivisions; row++) {
  28879. for (var col = 0; col < this._subdivisions; col++) {
  28880. i = col * 3;
  28881. j = row * (this._subdivisions + 1) * 3;
  28882. k = (row + 1) * (this._subdivisions + 1) * 3;
  28883. v1.x = positions[j + i];
  28884. v1.y = positions[j + i + 1];
  28885. v1.z = positions[j + i + 2];
  28886. v2.x = positions[j + i + 3];
  28887. v2.y = positions[j + i + 4];
  28888. v2.z = positions[j + i + 5];
  28889. v3.x = positions[k + i];
  28890. v3.y = positions[k + i + 1];
  28891. v3.z = positions[k + i + 2];
  28892. v4.x = positions[k + i + 3];
  28893. v4.y = positions[k + i + 4];
  28894. v4.z = positions[k + i + 5];
  28895. // 2D slope V1V4
  28896. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28897. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28898. // facet equations :
  28899. // we compute each facet normal vector
  28900. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28901. // we compute the value d by applying the equation to v1 which belongs to the plane
  28902. // then we store the facet equation in a Vector4
  28903. v2.subtractToRef(v1, v1v2);
  28904. v3.subtractToRef(v1, v1v3);
  28905. v4.subtractToRef(v1, v1v4);
  28906. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28907. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28908. norm1.normalize();
  28909. norm2.normalize();
  28910. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28911. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28912. var quad = this._heightQuads[row * this._subdivisions + col];
  28913. quad.slope.copyFromFloats(cd, h);
  28914. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  28915. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  28916. }
  28917. }
  28918. };
  28919. return GroundMesh;
  28920. })(BABYLON.Mesh);
  28921. BABYLON.GroundMesh = GroundMesh;
  28922. })(BABYLON || (BABYLON = {}));
  28923. var BABYLON;
  28924. (function (BABYLON) {
  28925. var LinesMesh = (function (_super) {
  28926. __extends(LinesMesh, _super);
  28927. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28928. if (parent === void 0) { parent = null; }
  28929. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28930. this.color = new BABYLON.Color3(1, 1, 1);
  28931. this.alpha = 1;
  28932. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28933. attributes: ["position"],
  28934. uniforms: ["worldViewProjection", "color"],
  28935. needAlphaBlending: true
  28936. });
  28937. }
  28938. Object.defineProperty(LinesMesh.prototype, "material", {
  28939. get: function () {
  28940. return this._colorShader;
  28941. },
  28942. enumerable: true,
  28943. configurable: true
  28944. });
  28945. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28946. get: function () {
  28947. return false;
  28948. },
  28949. enumerable: true,
  28950. configurable: true
  28951. });
  28952. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28953. get: function () {
  28954. return false;
  28955. },
  28956. enumerable: true,
  28957. configurable: true
  28958. });
  28959. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28960. var engine = this.getScene().getEngine();
  28961. var indexToBind = this._geometry.getIndexBuffer();
  28962. // VBOs
  28963. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28964. // Color
  28965. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28966. };
  28967. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28968. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28969. return;
  28970. }
  28971. var engine = this.getScene().getEngine();
  28972. // Draw order
  28973. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28974. };
  28975. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28976. return null;
  28977. };
  28978. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28979. this._colorShader.dispose();
  28980. _super.prototype.dispose.call(this, doNotRecurse);
  28981. };
  28982. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28983. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28984. };
  28985. return LinesMesh;
  28986. })(BABYLON.Mesh);
  28987. BABYLON.LinesMesh = LinesMesh;
  28988. })(BABYLON || (BABYLON = {}));
  28989. var BABYLON;
  28990. (function (BABYLON) {
  28991. var DebugLayer = (function () {
  28992. function DebugLayer(scene) {
  28993. var _this = this;
  28994. this._transformationMatrix = BABYLON.Matrix.Identity();
  28995. this._enabled = false;
  28996. this._labelsEnabled = false;
  28997. this._displayStatistics = true;
  28998. this._displayTree = false;
  28999. this._displayLogs = false;
  29000. this._identityMatrix = BABYLON.Matrix.Identity();
  29001. this.axisRatio = 0.02;
  29002. this.accentColor = "orange";
  29003. this._scene = scene;
  29004. this._syncPositions = function () {
  29005. var engine = _this._scene.getEngine();
  29006. var canvasRect = engine.getRenderingCanvasClientRect();
  29007. if (_this._showUI) {
  29008. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29009. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29010. _this._statsDiv.style.width = "400px";
  29011. _this._statsDiv.style.height = "auto";
  29012. _this._statsSubsetDiv.style.maxHeight = "240px";
  29013. _this._optionsDiv.style.left = "0px";
  29014. _this._optionsDiv.style.top = "10px";
  29015. _this._optionsDiv.style.width = "200px";
  29016. _this._optionsDiv.style.height = "auto";
  29017. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29018. _this._logDiv.style.left = "0px";
  29019. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29020. _this._logDiv.style.width = "600px";
  29021. _this._logDiv.style.height = "160px";
  29022. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29023. _this._treeDiv.style.top = "10px";
  29024. _this._treeDiv.style.width = "300px";
  29025. _this._treeDiv.style.height = "auto";
  29026. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29027. }
  29028. _this._globalDiv.style.left = canvasRect.left + "px";
  29029. _this._globalDiv.style.top = canvasRect.top + "px";
  29030. _this._drawingCanvas.style.left = "0px";
  29031. _this._drawingCanvas.style.top = "0px";
  29032. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29033. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29034. var devicePixelRatio = window.devicePixelRatio || 1;
  29035. var context = _this._drawingContext;
  29036. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29037. context.mozBackingStorePixelRatio ||
  29038. context.msBackingStorePixelRatio ||
  29039. context.oBackingStorePixelRatio ||
  29040. context.backingStorePixelRatio || 1;
  29041. _this._ratio = devicePixelRatio / backingStoreRatio;
  29042. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29043. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29044. };
  29045. this._onCanvasClick = function (evt) {
  29046. _this._clickPosition = {
  29047. x: evt.clientX * _this._ratio,
  29048. y: evt.clientY * _this._ratio
  29049. };
  29050. };
  29051. this._syncUI = function () {
  29052. if (_this._showUI) {
  29053. if (_this._displayStatistics) {
  29054. _this._displayStats();
  29055. _this._statsDiv.style.display = "";
  29056. }
  29057. else {
  29058. _this._statsDiv.style.display = "none";
  29059. }
  29060. if (_this._displayLogs) {
  29061. _this._logDiv.style.display = "";
  29062. }
  29063. else {
  29064. _this._logDiv.style.display = "none";
  29065. }
  29066. if (_this._displayTree) {
  29067. _this._treeDiv.style.display = "";
  29068. if (_this._needToRefreshMeshesTree) {
  29069. _this._needToRefreshMeshesTree = false;
  29070. _this._refreshMeshesTreeContent();
  29071. }
  29072. }
  29073. else {
  29074. _this._treeDiv.style.display = "none";
  29075. }
  29076. }
  29077. };
  29078. this._syncData = function () {
  29079. if (_this._labelsEnabled || !_this._showUI) {
  29080. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29081. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29082. var engine = _this._scene.getEngine();
  29083. var viewport = _this._camera.viewport;
  29084. var globalViewport = viewport.toGlobal(engine);
  29085. // Meshes
  29086. var meshes = _this._camera.getActiveMeshes();
  29087. var index;
  29088. var projectedPosition;
  29089. for (index = 0; index < meshes.length; index++) {
  29090. var mesh = meshes.data[index];
  29091. var position = mesh.getBoundingInfo().boundingSphere.center;
  29092. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29093. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29094. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29095. }
  29096. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29097. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29098. }
  29099. }
  29100. // Cameras
  29101. var cameras = _this._scene.cameras;
  29102. for (index = 0; index < cameras.length; index++) {
  29103. var camera = cameras[index];
  29104. if (camera === _this._camera) {
  29105. continue;
  29106. }
  29107. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29108. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29109. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29110. _this._camera.detachControl(engine.getRenderingCanvas());
  29111. _this._camera = camera;
  29112. _this._camera.attachControl(engine.getRenderingCanvas());
  29113. }, function () { return "purple"; });
  29114. }
  29115. }
  29116. // Lights
  29117. var lights = _this._scene.lights;
  29118. for (index = 0; index < lights.length; index++) {
  29119. var light = lights[index];
  29120. if (light.position) {
  29121. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29122. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29123. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29124. light.setEnabled(!light.isEnabled());
  29125. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29126. }
  29127. }
  29128. }
  29129. }
  29130. _this._clickPosition = undefined;
  29131. };
  29132. }
  29133. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29134. while (this._treeSubsetDiv.hasChildNodes()) {
  29135. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29136. }
  29137. // Add meshes
  29138. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29139. sortedArray.sort(function (a, b) {
  29140. if (a.name === b.name) {
  29141. return 0;
  29142. }
  29143. return (a.name > b.name) ? 1 : -1;
  29144. });
  29145. for (var index = 0; index < sortedArray.length; index++) {
  29146. var mesh = sortedArray[index];
  29147. if (!mesh.isEnabled()) {
  29148. continue;
  29149. }
  29150. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29151. m.isVisible = element.checked;
  29152. }, mesh);
  29153. }
  29154. };
  29155. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29156. this._drawingContext.beginPath();
  29157. this._drawingContext.moveTo(zero.x, zero.y);
  29158. this._drawingContext.lineTo(unit.x, unit.y);
  29159. this._drawingContext.strokeStyle = color;
  29160. this._drawingContext.lineWidth = 4;
  29161. this._drawingContext.stroke();
  29162. this._drawingContext.font = "normal 14px Segoe UI";
  29163. this._drawingContext.fillStyle = color;
  29164. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29165. };
  29166. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29167. var position = mesh.getBoundingInfo().boundingSphere.center;
  29168. var worldMatrix = mesh.getWorldMatrix();
  29169. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29170. var unit = (unprojectedVector.subtract(position)).length();
  29171. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29172. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29173. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29174. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29175. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29176. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29177. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29178. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29179. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29180. };
  29181. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29182. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29183. this._drawingContext.font = "normal 12px Segoe UI";
  29184. var textMetrics = this._drawingContext.measureText(text);
  29185. var centerX = projectedPosition.x - textMetrics.width / 2;
  29186. var centerY = projectedPosition.y;
  29187. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29188. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29189. onClick();
  29190. }
  29191. this._drawingContext.beginPath();
  29192. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29193. this._drawingContext.fillStyle = getFillStyle();
  29194. this._drawingContext.globalAlpha = 0.5;
  29195. this._drawingContext.fill();
  29196. this._drawingContext.globalAlpha = 1.0;
  29197. this._drawingContext.strokeStyle = '#FFFFFF';
  29198. this._drawingContext.lineWidth = 1;
  29199. this._drawingContext.stroke();
  29200. this._drawingContext.fillStyle = "#FFFFFF";
  29201. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29202. this._drawingContext.beginPath();
  29203. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29204. this._drawingContext.fill();
  29205. }
  29206. };
  29207. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29208. if (!this._clickPosition) {
  29209. return false;
  29210. }
  29211. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29212. return false;
  29213. }
  29214. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29215. return false;
  29216. }
  29217. return true;
  29218. };
  29219. DebugLayer.prototype.isVisible = function () {
  29220. return this._enabled;
  29221. };
  29222. DebugLayer.prototype.hide = function () {
  29223. if (!this._enabled) {
  29224. return;
  29225. }
  29226. this._enabled = false;
  29227. var engine = this._scene.getEngine();
  29228. this._scene.unregisterBeforeRender(this._syncData);
  29229. this._scene.unregisterAfterRender(this._syncUI);
  29230. this._rootElement.removeChild(this._globalDiv);
  29231. this._scene.forceShowBoundingBoxes = false;
  29232. this._scene.forceWireframe = false;
  29233. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29234. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29235. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29236. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29237. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29238. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29239. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29240. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29241. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29242. this._scene.shadowsEnabled = true;
  29243. this._scene.particlesEnabled = true;
  29244. this._scene.postProcessesEnabled = true;
  29245. this._scene.collisionsEnabled = true;
  29246. this._scene.lightsEnabled = true;
  29247. this._scene.texturesEnabled = true;
  29248. this._scene.lensFlaresEnabled = true;
  29249. this._scene.proceduralTexturesEnabled = true;
  29250. this._scene.renderTargetsEnabled = true;
  29251. this._scene.probesEnabled = true;
  29252. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29253. };
  29254. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29255. if (showUI === void 0) { showUI = true; }
  29256. if (camera === void 0) { camera = null; }
  29257. if (rootElement === void 0) { rootElement = null; }
  29258. if (this._enabled) {
  29259. return;
  29260. }
  29261. this._enabled = true;
  29262. if (camera) {
  29263. this._camera = camera;
  29264. }
  29265. else {
  29266. this._camera = this._scene.activeCamera;
  29267. }
  29268. this._showUI = showUI;
  29269. var engine = this._scene.getEngine();
  29270. this._globalDiv = document.createElement("div");
  29271. this._rootElement = rootElement || document.body;
  29272. this._rootElement.appendChild(this._globalDiv);
  29273. this._generateDOMelements();
  29274. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29275. this._syncPositions();
  29276. this._scene.registerBeforeRender(this._syncData);
  29277. this._scene.registerAfterRender(this._syncUI);
  29278. };
  29279. DebugLayer.prototype._clearLabels = function () {
  29280. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29281. for (var index = 0; index < this._scene.meshes.length; index++) {
  29282. var mesh = this._scene.meshes[index];
  29283. mesh.renderOverlay = false;
  29284. }
  29285. };
  29286. DebugLayer.prototype._generateheader = function (root, text) {
  29287. var header = document.createElement("div");
  29288. header.innerHTML = text + "&nbsp;";
  29289. header.style.textAlign = "right";
  29290. header.style.width = "100%";
  29291. header.style.color = "white";
  29292. header.style.backgroundColor = "Black";
  29293. header.style.padding = "5px 5px 4px 0px";
  29294. header.style.marginLeft = "-5px";
  29295. header.style.fontWeight = "bold";
  29296. root.appendChild(header);
  29297. };
  29298. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29299. var label = document.createElement("label");
  29300. label.innerHTML = title;
  29301. label.style.color = color;
  29302. root.appendChild(label);
  29303. root.appendChild(document.createElement("br"));
  29304. };
  29305. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29306. if (tag === void 0) { tag = null; }
  29307. var label = document.createElement("label");
  29308. var boundingBoxesCheckbox = document.createElement("input");
  29309. boundingBoxesCheckbox.type = "checkbox";
  29310. boundingBoxesCheckbox.checked = initialState;
  29311. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29312. task(evt.target, tag);
  29313. });
  29314. label.appendChild(boundingBoxesCheckbox);
  29315. var container = document.createElement("span");
  29316. var leftPart = document.createElement("span");
  29317. var rightPart = document.createElement("span");
  29318. rightPart.style.cssFloat = "right";
  29319. leftPart.innerHTML = leftTitle;
  29320. rightPart.innerHTML = rightTitle;
  29321. rightPart.style.fontSize = "12px";
  29322. rightPart.style.maxWidth = "200px";
  29323. container.appendChild(leftPart);
  29324. container.appendChild(rightPart);
  29325. label.appendChild(container);
  29326. root.appendChild(label);
  29327. root.appendChild(document.createElement("br"));
  29328. };
  29329. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29330. if (tag === void 0) { tag = null; }
  29331. var label = document.createElement("label");
  29332. var checkBox = document.createElement("input");
  29333. checkBox.type = "checkbox";
  29334. checkBox.checked = initialState;
  29335. checkBox.addEventListener("change", function (evt) {
  29336. task(evt.target, tag);
  29337. });
  29338. label.appendChild(checkBox);
  29339. label.appendChild(document.createTextNode(title));
  29340. root.appendChild(label);
  29341. root.appendChild(document.createElement("br"));
  29342. };
  29343. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29344. if (tag === void 0) { tag = null; }
  29345. var button = document.createElement("button");
  29346. button.innerHTML = title;
  29347. button.style.height = "24px";
  29348. button.style.width = "150px";
  29349. button.style.marginBottom = "5px";
  29350. button.style.color = "#444444";
  29351. button.style.border = "1px solid white";
  29352. button.className = "debugLayerButton";
  29353. button.addEventListener("click", function (evt) {
  29354. task(evt.target, tag);
  29355. });
  29356. root.appendChild(button);
  29357. root.appendChild(document.createElement("br"));
  29358. };
  29359. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29360. if (tag === void 0) { tag = null; }
  29361. var label = document.createElement("label");
  29362. var boundingBoxesRadio = document.createElement("input");
  29363. boundingBoxesRadio.type = "radio";
  29364. boundingBoxesRadio.name = name;
  29365. boundingBoxesRadio.checked = initialState;
  29366. boundingBoxesRadio.addEventListener("change", function (evt) {
  29367. task(evt.target, tag);
  29368. });
  29369. label.appendChild(boundingBoxesRadio);
  29370. label.appendChild(document.createTextNode(title));
  29371. root.appendChild(label);
  29372. root.appendChild(document.createElement("br"));
  29373. };
  29374. DebugLayer.prototype._generateDOMelements = function () {
  29375. var _this = this;
  29376. this._globalDiv.id = "DebugLayer";
  29377. this._globalDiv.style.position = "absolute";
  29378. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29379. this._globalDiv.style.fontSize = "14px";
  29380. this._globalDiv.style.color = "white";
  29381. // Drawing canvas
  29382. this._drawingCanvas = document.createElement("canvas");
  29383. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29384. this._drawingCanvas.style.position = "absolute";
  29385. this._drawingCanvas.style.pointerEvents = "none";
  29386. this._drawingCanvas.style.backgroundColor = "transparent";
  29387. this._drawingContext = this._drawingCanvas.getContext("2d");
  29388. this._globalDiv.appendChild(this._drawingCanvas);
  29389. if (this._showUI) {
  29390. var background = "rgba(128, 128, 128, 0.4)";
  29391. var border = "rgb(180, 180, 180) solid 1px";
  29392. // Stats
  29393. this._statsDiv = document.createElement("div");
  29394. this._statsDiv.id = "DebugLayerStats";
  29395. this._statsDiv.style.border = border;
  29396. this._statsDiv.style.position = "absolute";
  29397. this._statsDiv.style.background = background;
  29398. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29399. this._generateheader(this._statsDiv, "STATISTICS");
  29400. this._statsSubsetDiv = document.createElement("div");
  29401. this._statsSubsetDiv.style.paddingTop = "5px";
  29402. this._statsSubsetDiv.style.paddingBottom = "5px";
  29403. this._statsSubsetDiv.style.overflowY = "auto";
  29404. this._statsDiv.appendChild(this._statsSubsetDiv);
  29405. // Tree
  29406. this._treeDiv = document.createElement("div");
  29407. this._treeDiv.id = "DebugLayerTree";
  29408. this._treeDiv.style.border = border;
  29409. this._treeDiv.style.position = "absolute";
  29410. this._treeDiv.style.background = background;
  29411. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29412. this._treeDiv.style.display = "none";
  29413. this._generateheader(this._treeDiv, "MESHES TREE");
  29414. this._treeSubsetDiv = document.createElement("div");
  29415. this._treeSubsetDiv.style.paddingTop = "5px";
  29416. this._treeSubsetDiv.style.paddingRight = "5px";
  29417. this._treeSubsetDiv.style.overflowY = "auto";
  29418. this._treeSubsetDiv.style.maxHeight = "300px";
  29419. this._treeDiv.appendChild(this._treeSubsetDiv);
  29420. this._needToRefreshMeshesTree = true;
  29421. // Logs
  29422. this._logDiv = document.createElement("div");
  29423. this._logDiv.style.border = border;
  29424. this._logDiv.id = "DebugLayerLogs";
  29425. this._logDiv.style.position = "absolute";
  29426. this._logDiv.style.background = background;
  29427. this._logDiv.style.padding = "0px 0px 0px 5px";
  29428. this._logDiv.style.display = "none";
  29429. this._generateheader(this._logDiv, "LOGS");
  29430. this._logSubsetDiv = document.createElement("div");
  29431. this._logSubsetDiv.style.height = "127px";
  29432. this._logSubsetDiv.style.paddingTop = "5px";
  29433. this._logSubsetDiv.style.overflowY = "auto";
  29434. this._logSubsetDiv.style.fontSize = "12px";
  29435. this._logSubsetDiv.style.fontFamily = "consolas";
  29436. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29437. this._logDiv.appendChild(this._logSubsetDiv);
  29438. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29439. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29440. };
  29441. // Options
  29442. this._optionsDiv = document.createElement("div");
  29443. this._optionsDiv.id = "DebugLayerOptions";
  29444. this._optionsDiv.style.border = border;
  29445. this._optionsDiv.style.position = "absolute";
  29446. this._optionsDiv.style.background = background;
  29447. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29448. this._optionsDiv.style.overflowY = "auto";
  29449. this._generateheader(this._optionsDiv, "OPTIONS");
  29450. this._optionsSubsetDiv = document.createElement("div");
  29451. this._optionsSubsetDiv.style.paddingTop = "5px";
  29452. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29453. this._optionsSubsetDiv.style.overflowY = "auto";
  29454. this._optionsSubsetDiv.style.maxHeight = "200px";
  29455. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29456. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29457. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29458. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29459. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29460. _this._displayTree = element.checked;
  29461. _this._needToRefreshMeshesTree = true;
  29462. });
  29463. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29464. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29465. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29466. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29467. _this._labelsEnabled = element.checked;
  29468. if (!_this._labelsEnabled) {
  29469. _this._clearLabels();
  29470. }
  29471. });
  29472. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29473. if (element.checked) {
  29474. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29475. }
  29476. else {
  29477. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29478. }
  29479. });
  29480. ;
  29481. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29482. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29483. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29484. if (element.checked) {
  29485. _this._scene.forceWireframe = false;
  29486. _this._scene.forcePointsCloud = false;
  29487. }
  29488. });
  29489. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29490. if (element.checked) {
  29491. _this._scene.forceWireframe = true;
  29492. _this._scene.forcePointsCloud = false;
  29493. }
  29494. });
  29495. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29496. if (element.checked) {
  29497. _this._scene.forceWireframe = false;
  29498. _this._scene.forcePointsCloud = true;
  29499. }
  29500. });
  29501. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29502. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29503. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29504. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29505. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29506. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29507. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29508. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29509. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29510. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29511. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29512. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29513. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29514. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29515. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29516. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29517. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29518. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29519. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29520. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29521. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29522. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29523. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29524. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29525. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29526. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29527. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29528. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29529. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29530. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29531. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29532. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29533. if (element.checked) {
  29534. _this._scene.headphone = true;
  29535. }
  29536. });
  29537. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29538. if (element.checked) {
  29539. _this._scene.headphone = false;
  29540. }
  29541. });
  29542. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29543. _this._scene.audioEnabled = !element.checked;
  29544. });
  29545. }
  29546. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29547. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29548. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29549. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29550. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29551. if (_this._camera) {
  29552. console.log(_this._camera);
  29553. }
  29554. else {
  29555. console.warn("No camera defined, or debug layer created before camera creation!");
  29556. }
  29557. });
  29558. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29559. this._globalDiv.appendChild(this._statsDiv);
  29560. this._globalDiv.appendChild(this._logDiv);
  29561. this._globalDiv.appendChild(this._optionsDiv);
  29562. this._globalDiv.appendChild(this._treeDiv);
  29563. }
  29564. };
  29565. DebugLayer.prototype._displayStats = function () {
  29566. var scene = this._scene;
  29567. var engine = scene.getEngine();
  29568. var glInfo = engine.getGlInfo();
  29569. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29570. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29571. + "<b>Count</b><br>"
  29572. + "Total meshes: " + scene.meshes.length + "<br>"
  29573. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29574. + "Total materials: " + scene.materials.length + "<br>"
  29575. + "Total textures: " + scene.textures.length + "<br>"
  29576. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29577. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29578. + "Active bones: " + scene.getActiveBones() + "<br>"
  29579. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29580. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29581. + "<b>Duration</b><br>"
  29582. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29583. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29584. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29585. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29586. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29587. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29588. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29589. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29590. + "</div>"
  29591. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29592. + "<b>Extensions</b><br>"
  29593. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29594. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29595. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29596. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29597. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29598. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29599. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29600. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29601. + "</div><br>"
  29602. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29603. + "<b>Caps.</b><br>"
  29604. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29605. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29606. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29607. + "<b>Info</b><br>"
  29608. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29609. + glInfo.version + "<br>"
  29610. + "</div><br>"
  29611. + glInfo.renderer + "<br>";
  29612. if (this.customStatsFunction) {
  29613. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29614. }
  29615. };
  29616. return DebugLayer;
  29617. })();
  29618. BABYLON.DebugLayer = DebugLayer;
  29619. })(BABYLON || (BABYLON = {}));
  29620. var BABYLON;
  29621. (function (BABYLON) {
  29622. var DefaultLoadingScreen = (function () {
  29623. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29624. var _this = this;
  29625. if (_loadingText === void 0) { _loadingText = ""; }
  29626. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29627. this._renderingCanvas = _renderingCanvas;
  29628. this._loadingText = _loadingText;
  29629. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29630. // Resize
  29631. this._resizeLoadingUI = function () {
  29632. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29633. _this._loadingDiv.style.position = "absolute";
  29634. _this._loadingDiv.style.left = canvasRect.left + "px";
  29635. _this._loadingDiv.style.top = canvasRect.top + "px";
  29636. _this._loadingDiv.style.width = canvasRect.width + "px";
  29637. _this._loadingDiv.style.height = canvasRect.height + "px";
  29638. };
  29639. }
  29640. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29641. var _this = this;
  29642. if (this._loadingDiv) {
  29643. // Do not add a loading screen if there is already one
  29644. return;
  29645. }
  29646. this._loadingDiv = document.createElement("div");
  29647. this._loadingDiv.id = "babylonjsLoadingDiv";
  29648. this._loadingDiv.style.opacity = "0";
  29649. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29650. // Loading text
  29651. this._loadingTextDiv = document.createElement("div");
  29652. this._loadingTextDiv.style.position = "absolute";
  29653. this._loadingTextDiv.style.left = "0";
  29654. this._loadingTextDiv.style.top = "50%";
  29655. this._loadingTextDiv.style.marginTop = "80px";
  29656. this._loadingTextDiv.style.width = "100%";
  29657. this._loadingTextDiv.style.height = "20px";
  29658. this._loadingTextDiv.style.fontFamily = "Arial";
  29659. this._loadingTextDiv.style.fontSize = "14px";
  29660. this._loadingTextDiv.style.color = "white";
  29661. this._loadingTextDiv.style.textAlign = "center";
  29662. this._loadingTextDiv.innerHTML = "Loading";
  29663. this._loadingDiv.appendChild(this._loadingTextDiv);
  29664. //set the predefined text
  29665. this._loadingTextDiv.innerHTML = this._loadingText;
  29666. // Loading img
  29667. var imgBack = new Image();
  29668. 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==";
  29669. imgBack.style.position = "absolute";
  29670. imgBack.style.left = "50%";
  29671. imgBack.style.top = "50%";
  29672. imgBack.style.marginLeft = "-50px";
  29673. imgBack.style.marginTop = "-50px";
  29674. imgBack.style.transition = "transform 1.0s ease";
  29675. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29676. var deg = 360;
  29677. var onTransitionEnd = function () {
  29678. deg += 360;
  29679. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29680. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29681. };
  29682. imgBack.addEventListener("transitionend", onTransitionEnd);
  29683. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29684. this._loadingDiv.appendChild(imgBack);
  29685. // front image
  29686. var imgFront = new Image();
  29687. 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=";
  29688. imgFront.style.position = "absolute";
  29689. imgFront.style.left = "50%";
  29690. imgFront.style.top = "50%";
  29691. imgFront.style.marginLeft = "-50px";
  29692. imgFront.style.marginTop = "-50px";
  29693. this._loadingDiv.appendChild(imgFront);
  29694. this._resizeLoadingUI();
  29695. window.addEventListener("resize", this._resizeLoadingUI);
  29696. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29697. document.body.appendChild(this._loadingDiv);
  29698. setTimeout(function () {
  29699. _this._loadingDiv.style.opacity = "1";
  29700. imgBack.style.transform = "rotateZ(360deg)";
  29701. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29702. }, 0);
  29703. };
  29704. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29705. var _this = this;
  29706. if (!this._loadingDiv) {
  29707. return;
  29708. }
  29709. var onTransitionEnd = function () {
  29710. if (!_this._loadingDiv) {
  29711. return;
  29712. }
  29713. document.body.removeChild(_this._loadingDiv);
  29714. window.removeEventListener("resize", _this._resizeLoadingUI);
  29715. _this._loadingDiv = null;
  29716. };
  29717. this._loadingDiv.style.opacity = "0";
  29718. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29719. };
  29720. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29721. set: function (text) {
  29722. this._loadingText = text;
  29723. if (this._loadingTextDiv) {
  29724. this._loadingTextDiv.innerHTML = this._loadingText;
  29725. }
  29726. },
  29727. enumerable: true,
  29728. configurable: true
  29729. });
  29730. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29731. get: function () {
  29732. return this._loadingDivBackgroundColor;
  29733. },
  29734. set: function (color) {
  29735. this._loadingDivBackgroundColor = color;
  29736. if (!this._loadingDiv) {
  29737. return;
  29738. }
  29739. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29740. },
  29741. enumerable: true,
  29742. configurable: true
  29743. });
  29744. return DefaultLoadingScreen;
  29745. })();
  29746. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29747. })(BABYLON || (BABYLON = {}));
  29748. var BABYLON;
  29749. (function (BABYLON) {
  29750. var SIMDVector3 = (function () {
  29751. function SIMDVector3() {
  29752. }
  29753. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29754. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29755. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29756. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29757. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29758. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29759. 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));
  29760. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29761. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29762. };
  29763. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29764. var v0 = SIMD.float32x4.splat(x);
  29765. var v1 = SIMD.float32x4.splat(y);
  29766. var v2 = SIMD.float32x4.splat(z);
  29767. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29768. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29769. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29770. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29771. 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));
  29772. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29773. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29774. };
  29775. return SIMDVector3;
  29776. })();
  29777. BABYLON.SIMDVector3 = SIMDVector3;
  29778. var SIMDMatrix = (function () {
  29779. function SIMDMatrix() {
  29780. }
  29781. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29782. if (offset === void 0) { offset = 0; }
  29783. var tm = this.m;
  29784. var om = other.m;
  29785. var om0 = SIMD.float32x4.load(om, 0);
  29786. var om1 = SIMD.float32x4.load(om, 4);
  29787. var om2 = SIMD.float32x4.load(om, 8);
  29788. var om3 = SIMD.float32x4.load(om, 12);
  29789. var tm0 = SIMD.float32x4.load(tm, 0);
  29790. 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)))));
  29791. var tm1 = SIMD.float32x4.load(tm, 4);
  29792. 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)))));
  29793. var tm2 = SIMD.float32x4.load(tm, 8);
  29794. 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)))));
  29795. var tm3 = SIMD.float32x4.load(tm, 12);
  29796. 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)))));
  29797. };
  29798. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29799. var src = this.m;
  29800. var dest = other.m;
  29801. var row0, row1, row2, row3;
  29802. var tmp1;
  29803. var minor0, minor1, minor2, minor3;
  29804. var det;
  29805. // Load the 4 rows
  29806. var src0 = SIMD.float32x4.load(src, 0);
  29807. var src1 = SIMD.float32x4.load(src, 4);
  29808. var src2 = SIMD.float32x4.load(src, 8);
  29809. var src3 = SIMD.float32x4.load(src, 12);
  29810. // Transpose the source matrix. Sort of. Not a true transpose operation
  29811. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29812. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29813. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29814. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29815. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29816. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29817. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29818. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29819. // This is a true transposition, but it will lead to an incorrect result
  29820. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29821. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29822. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29823. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29824. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29825. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29826. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29827. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29828. // ----
  29829. tmp1 = SIMD.float32x4.mul(row2, row3);
  29830. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29831. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29832. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29833. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29834. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29835. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29836. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29837. // ----
  29838. tmp1 = SIMD.float32x4.mul(row1, row2);
  29839. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29840. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29841. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29842. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29843. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29844. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29845. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29846. // ----
  29847. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29848. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29849. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29850. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29851. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29852. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29853. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29854. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29855. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29856. // ----
  29857. tmp1 = SIMD.float32x4.mul(row0, row1);
  29858. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29859. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29860. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29861. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29862. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29863. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29864. // ----
  29865. tmp1 = SIMD.float32x4.mul(row0, row3);
  29866. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29867. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29868. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29869. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29870. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29871. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29872. // ----
  29873. tmp1 = SIMD.float32x4.mul(row0, row2);
  29874. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29875. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29876. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29877. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29878. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29879. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29880. // Compute determinant
  29881. det = SIMD.float32x4.mul(row0, minor0);
  29882. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29883. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29884. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29885. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29886. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29887. // These shuffles aren't necessary if the faulty transposition is done
  29888. // up at the top of this function.
  29889. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29890. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29891. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29892. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29893. // Compute final values by multiplying with 1/det
  29894. minor0 = SIMD.float32x4.mul(det, minor0);
  29895. minor1 = SIMD.float32x4.mul(det, minor1);
  29896. minor2 = SIMD.float32x4.mul(det, minor2);
  29897. minor3 = SIMD.float32x4.mul(det, minor3);
  29898. SIMD.float32x4.store(dest, 0, minor0);
  29899. SIMD.float32x4.store(dest, 4, minor1);
  29900. SIMD.float32x4.store(dest, 8, minor2);
  29901. SIMD.float32x4.store(dest, 12, minor3);
  29902. return this;
  29903. };
  29904. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29905. var out = result.m;
  29906. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29907. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29908. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29909. // cc.kmVec3Subtract(f, pCenter, pEye);
  29910. var f = SIMD.float32x4.sub(center, eye);
  29911. // cc.kmVec3Normalize(f, f);
  29912. var tmp = SIMD.float32x4.mul(f, f);
  29913. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29914. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29915. // cc.kmVec3Assign(up, pUp);
  29916. // cc.kmVec3Normalize(up, up);
  29917. tmp = SIMD.float32x4.mul(up, up);
  29918. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29919. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29920. // cc.kmVec3Cross(s, f, up);
  29921. 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)));
  29922. // cc.kmVec3Normalize(s, s);
  29923. tmp = SIMD.float32x4.mul(s, s);
  29924. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29925. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29926. // cc.kmVec3Cross(u, s, f);
  29927. 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)));
  29928. // cc.kmVec3Normalize(s, s);
  29929. tmp = SIMD.float32x4.mul(s, s);
  29930. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29931. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29932. var zero = SIMD.float32x4.splat(0.0);
  29933. s = SIMD.float32x4.neg(s);
  29934. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29935. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29936. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29937. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29938. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29939. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29940. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29941. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29942. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29943. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29944. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29945. var b3 = SIMD.float32x4.neg(eye);
  29946. b3 = SIMD.float32x4.withW(b3, 1.0);
  29947. 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)))));
  29948. 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)))));
  29949. 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)))));
  29950. 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)))));
  29951. };
  29952. return SIMDMatrix;
  29953. })();
  29954. BABYLON.SIMDMatrix = SIMDMatrix;
  29955. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29956. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29957. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29958. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29959. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29960. var SIMDHelper = (function () {
  29961. function SIMDHelper() {
  29962. }
  29963. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29964. get: function () {
  29965. return SIMDHelper._isEnabled;
  29966. },
  29967. enumerable: true,
  29968. configurable: true
  29969. });
  29970. SIMDHelper.DisableSIMD = function () {
  29971. // Replace functions
  29972. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29973. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29974. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29975. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29977. SIMDHelper._isEnabled = false;
  29978. };
  29979. SIMDHelper.EnableSIMD = function () {
  29980. if (window.SIMD === undefined) {
  29981. return;
  29982. }
  29983. // Replace functions
  29984. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29985. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29986. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29987. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29988. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29989. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29990. get: function () { return this._data[0]; },
  29991. set: function (value) {
  29992. if (!this._data) {
  29993. this._data = new Float32Array(3);
  29994. }
  29995. this._data[0] = value;
  29996. }
  29997. });
  29998. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29999. get: function () { return this._data[1]; },
  30000. set: function (value) {
  30001. this._data[1] = value;
  30002. }
  30003. });
  30004. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30005. get: function () { return this._data[2]; },
  30006. set: function (value) {
  30007. this._data[2] = value;
  30008. }
  30009. });
  30010. SIMDHelper._isEnabled = true;
  30011. };
  30012. SIMDHelper._isEnabled = false;
  30013. return SIMDHelper;
  30014. })();
  30015. BABYLON.SIMDHelper = SIMDHelper;
  30016. })(BABYLON || (BABYLON = {}));
  30017. var BABYLON;
  30018. (function (BABYLON) {
  30019. var ShaderMaterial = (function (_super) {
  30020. __extends(ShaderMaterial, _super);
  30021. function ShaderMaterial(name, scene, shaderPath, options) {
  30022. _super.call(this, name, scene);
  30023. this._textures = {};
  30024. this._floats = {};
  30025. this._floatsArrays = {};
  30026. this._colors3 = {};
  30027. this._colors4 = {};
  30028. this._vectors2 = {};
  30029. this._vectors3 = {};
  30030. this._vectors4 = {};
  30031. this._matrices = {};
  30032. this._matrices3x3 = {};
  30033. this._matrices2x2 = {};
  30034. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30035. this._shaderPath = shaderPath;
  30036. options.needAlphaBlending = options.needAlphaBlending || false;
  30037. options.needAlphaTesting = options.needAlphaTesting || false;
  30038. options.attributes = options.attributes || ["position", "normal", "uv"];
  30039. options.uniforms = options.uniforms || ["worldViewProjection"];
  30040. options.samplers = options.samplers || [];
  30041. options.defines = options.defines || [];
  30042. this._options = options;
  30043. }
  30044. ShaderMaterial.prototype.needAlphaBlending = function () {
  30045. return this._options.needAlphaBlending;
  30046. };
  30047. ShaderMaterial.prototype.needAlphaTesting = function () {
  30048. return this._options.needAlphaTesting;
  30049. };
  30050. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30051. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30052. this._options.uniforms.push(uniformName);
  30053. }
  30054. };
  30055. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30056. if (this._options.samplers.indexOf(name) === -1) {
  30057. this._options.samplers.push(name);
  30058. }
  30059. this._textures[name] = texture;
  30060. return this;
  30061. };
  30062. ShaderMaterial.prototype.setFloat = function (name, value) {
  30063. this._checkUniform(name);
  30064. this._floats[name] = value;
  30065. return this;
  30066. };
  30067. ShaderMaterial.prototype.setFloats = function (name, value) {
  30068. this._checkUniform(name);
  30069. this._floatsArrays[name] = value;
  30070. return this;
  30071. };
  30072. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30073. this._checkUniform(name);
  30074. this._colors3[name] = value;
  30075. return this;
  30076. };
  30077. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30078. this._checkUniform(name);
  30079. this._colors4[name] = value;
  30080. return this;
  30081. };
  30082. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30083. this._checkUniform(name);
  30084. this._vectors2[name] = value;
  30085. return this;
  30086. };
  30087. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30088. this._checkUniform(name);
  30089. this._vectors3[name] = value;
  30090. return this;
  30091. };
  30092. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30093. this._checkUniform(name);
  30094. this._vectors4[name] = value;
  30095. return this;
  30096. };
  30097. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30098. this._checkUniform(name);
  30099. this._matrices[name] = value;
  30100. return this;
  30101. };
  30102. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30103. this._checkUniform(name);
  30104. this._matrices3x3[name] = value;
  30105. return this;
  30106. };
  30107. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30108. this._checkUniform(name);
  30109. this._matrices2x2[name] = value;
  30110. return this;
  30111. };
  30112. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30113. var scene = this.getScene();
  30114. var engine = scene.getEngine();
  30115. if (!this.checkReadyOnEveryCall) {
  30116. if (this._renderId === scene.getRenderId()) {
  30117. return true;
  30118. }
  30119. }
  30120. // Instances
  30121. var defines = [];
  30122. var fallbacks = new BABYLON.EffectFallbacks();
  30123. if (useInstances) {
  30124. defines.push("#define INSTANCES");
  30125. }
  30126. for (var index = 0; index < this._options.defines.length; index++) {
  30127. defines.push(this._options.defines[index]);
  30128. }
  30129. // Bones
  30130. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30131. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30132. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30133. fallbacks.addCPUSkinningFallback(0, mesh);
  30134. }
  30135. // Alpha test
  30136. if (engine.getAlphaTesting()) {
  30137. defines.push("#define ALPHATEST");
  30138. }
  30139. var previousEffect = this._effect;
  30140. var join = defines.join("\n");
  30141. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30142. if (!this._effect.isReady()) {
  30143. return false;
  30144. }
  30145. if (previousEffect !== this._effect) {
  30146. scene.resetCachedMaterial();
  30147. }
  30148. this._renderId = scene.getRenderId();
  30149. return true;
  30150. };
  30151. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30152. var scene = this.getScene();
  30153. if (this._options.uniforms.indexOf("world") !== -1) {
  30154. this._effect.setMatrix("world", world);
  30155. }
  30156. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30157. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30158. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30159. }
  30160. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30161. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30162. }
  30163. };
  30164. ShaderMaterial.prototype.bind = function (world, mesh) {
  30165. // Std values
  30166. this.bindOnlyWorldMatrix(world);
  30167. if (this.getScene().getCachedMaterial() !== this) {
  30168. if (this._options.uniforms.indexOf("view") !== -1) {
  30169. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30170. }
  30171. if (this._options.uniforms.indexOf("projection") !== -1) {
  30172. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30173. }
  30174. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30175. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30176. }
  30177. // Bones
  30178. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30179. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30180. }
  30181. // Texture
  30182. for (var name in this._textures) {
  30183. this._effect.setTexture(name, this._textures[name]);
  30184. }
  30185. // Float
  30186. for (name in this._floats) {
  30187. this._effect.setFloat(name, this._floats[name]);
  30188. }
  30189. // Float s
  30190. for (name in this._floatsArrays) {
  30191. this._effect.setArray(name, this._floatsArrays[name]);
  30192. }
  30193. // Color3
  30194. for (name in this._colors3) {
  30195. this._effect.setColor3(name, this._colors3[name]);
  30196. }
  30197. // Color4
  30198. for (name in this._colors4) {
  30199. var color = this._colors4[name];
  30200. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30201. }
  30202. // Vector2
  30203. for (name in this._vectors2) {
  30204. this._effect.setVector2(name, this._vectors2[name]);
  30205. }
  30206. // Vector3
  30207. for (name in this._vectors3) {
  30208. this._effect.setVector3(name, this._vectors3[name]);
  30209. }
  30210. // Vector4
  30211. for (name in this._vectors4) {
  30212. this._effect.setVector4(name, this._vectors4[name]);
  30213. }
  30214. // Matrix
  30215. for (name in this._matrices) {
  30216. this._effect.setMatrix(name, this._matrices[name]);
  30217. }
  30218. // Matrix 3x3
  30219. for (name in this._matrices3x3) {
  30220. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30221. }
  30222. // Matrix 2x2
  30223. for (name in this._matrices2x2) {
  30224. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30225. }
  30226. }
  30227. _super.prototype.bind.call(this, world, mesh);
  30228. };
  30229. ShaderMaterial.prototype.clone = function (name) {
  30230. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30231. return newShaderMaterial;
  30232. };
  30233. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30234. for (var name in this._textures) {
  30235. this._textures[name].dispose();
  30236. }
  30237. this._textures = {};
  30238. _super.prototype.dispose.call(this, forceDisposeEffect);
  30239. };
  30240. ShaderMaterial.prototype.serialize = function () {
  30241. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30242. serializationObject.customType = "BABYLON.ShaderMaterial";
  30243. serializationObject.options = this._options;
  30244. serializationObject.shaderPath = this._shaderPath;
  30245. // Texture
  30246. serializationObject.textures = {};
  30247. for (var name in this._textures) {
  30248. serializationObject.textures[name] = this._textures[name].serialize();
  30249. }
  30250. // Float
  30251. serializationObject.floats = {};
  30252. for (name in this._floats) {
  30253. serializationObject.floats[name] = this._floats[name];
  30254. }
  30255. // Float s
  30256. serializationObject.floatArrays = {};
  30257. for (name in this._floatsArrays) {
  30258. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30259. }
  30260. // Color3
  30261. serializationObject.colors3 = {};
  30262. for (name in this._colors3) {
  30263. serializationObject.colors3[name] = this._colors3[name].asArray();
  30264. }
  30265. // Color4
  30266. serializationObject.colors4 = {};
  30267. for (name in this._colors4) {
  30268. serializationObject.colors4[name] = this._colors4[name].asArray();
  30269. }
  30270. // Vector2
  30271. serializationObject.vectors2 = {};
  30272. for (name in this._vectors2) {
  30273. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30274. }
  30275. // Vector3
  30276. serializationObject.vectors3 = {};
  30277. for (name in this._vectors3) {
  30278. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30279. }
  30280. // Vector4
  30281. serializationObject.vectors4 = {};
  30282. for (name in this._vectors4) {
  30283. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30284. }
  30285. // Matrix
  30286. serializationObject.matrices = {};
  30287. for (name in this._matrices) {
  30288. serializationObject.matrices[name] = this._matrices[name].asArray();
  30289. }
  30290. // Matrix 3x3
  30291. serializationObject.matrices3x3 = {};
  30292. for (name in this._matrices3x3) {
  30293. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30294. }
  30295. // Matrix 2x2
  30296. serializationObject.matrices2x2 = {};
  30297. for (name in this._matrices2x2) {
  30298. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30299. }
  30300. return serializationObject;
  30301. };
  30302. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30303. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30304. // Texture
  30305. for (var name in source.textures) {
  30306. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30307. }
  30308. // Float
  30309. for (name in source.floats) {
  30310. material.setFloat(name, source.floats[name]);
  30311. }
  30312. // Float s
  30313. for (name in source.floatsArrays) {
  30314. material.setFloats(name, source.floatsArrays[name]);
  30315. }
  30316. // Color3
  30317. for (name in source.colors3) {
  30318. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30319. }
  30320. // Color4
  30321. for (name in source.colors4) {
  30322. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30323. }
  30324. // Vector2
  30325. for (name in source.vectors2) {
  30326. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30327. }
  30328. // Vector3
  30329. for (name in source.vectors3) {
  30330. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30331. }
  30332. // Vector4
  30333. for (name in source.vectors4) {
  30334. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30335. }
  30336. // Matrix
  30337. for (name in source.matrices) {
  30338. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30339. }
  30340. // Matrix 3x3
  30341. for (name in source.matrices3x3) {
  30342. material.setMatrix3x3(name, source.matrices3x3[name]);
  30343. }
  30344. // Matrix 2x2
  30345. for (name in source.matrices2x2) {
  30346. material.setMatrix2x2(name, source.matrices2x2[name]);
  30347. }
  30348. return material;
  30349. };
  30350. return ShaderMaterial;
  30351. })(BABYLON.Material);
  30352. BABYLON.ShaderMaterial = ShaderMaterial;
  30353. })(BABYLON || (BABYLON = {}));
  30354. var BABYLON;
  30355. (function (BABYLON) {
  30356. var Internals;
  30357. (function (Internals) {
  30358. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30359. // All values and structures referenced from:
  30360. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30361. var DDS_MAGIC = 0x20534444;
  30362. 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;
  30363. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30364. 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;
  30365. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30366. function FourCCToInt32(value) {
  30367. return value.charCodeAt(0) +
  30368. (value.charCodeAt(1) << 8) +
  30369. (value.charCodeAt(2) << 16) +
  30370. (value.charCodeAt(3) << 24);
  30371. }
  30372. function Int32ToFourCC(value) {
  30373. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30374. }
  30375. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30376. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30377. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30378. var headerLengthInt = 31; // The header length in 32 bit ints
  30379. // Offsets into the header array
  30380. var off_magic = 0;
  30381. var off_size = 1;
  30382. var off_flags = 2;
  30383. var off_height = 3;
  30384. var off_width = 4;
  30385. var off_mipmapCount = 7;
  30386. var off_pfFlags = 20;
  30387. var off_pfFourCC = 21;
  30388. var off_RGBbpp = 22;
  30389. var off_RMask = 23;
  30390. var off_GMask = 24;
  30391. var off_BMask = 25;
  30392. var off_AMask = 26;
  30393. var off_caps1 = 27;
  30394. var off_caps2 = 28;
  30395. ;
  30396. var DDSTools = (function () {
  30397. function DDSTools() {
  30398. }
  30399. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30400. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30401. var mipmapCount = 1;
  30402. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30403. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30404. }
  30405. return {
  30406. width: header[off_width],
  30407. height: header[off_height],
  30408. mipmapCount: mipmapCount,
  30409. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30410. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30411. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30412. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30413. };
  30414. };
  30415. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30416. var byteArray = new Uint8Array(dataLength);
  30417. var srcData = new Uint8Array(arrayBuffer);
  30418. var index = 0;
  30419. for (var y = height - 1; y >= 0; y--) {
  30420. for (var x = 0; x < width; x++) {
  30421. var srcPos = dataOffset + (x + y * width) * 4;
  30422. byteArray[index + 2] = srcData[srcPos];
  30423. byteArray[index + 1] = srcData[srcPos + 1];
  30424. byteArray[index] = srcData[srcPos + 2];
  30425. byteArray[index + 3] = srcData[srcPos + 3];
  30426. index += 4;
  30427. }
  30428. }
  30429. return byteArray;
  30430. };
  30431. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30432. var byteArray = new Uint8Array(dataLength);
  30433. var srcData = new Uint8Array(arrayBuffer);
  30434. var index = 0;
  30435. for (var y = height - 1; y >= 0; y--) {
  30436. for (var x = 0; x < width; x++) {
  30437. var srcPos = dataOffset + (x + y * width) * 3;
  30438. byteArray[index + 2] = srcData[srcPos];
  30439. byteArray[index + 1] = srcData[srcPos + 1];
  30440. byteArray[index] = srcData[srcPos + 2];
  30441. index += 3;
  30442. }
  30443. }
  30444. return byteArray;
  30445. };
  30446. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30447. var byteArray = new Uint8Array(dataLength);
  30448. var srcData = new Uint8Array(arrayBuffer);
  30449. var index = 0;
  30450. for (var y = height - 1; y >= 0; y--) {
  30451. for (var x = 0; x < width; x++) {
  30452. var srcPos = dataOffset + (x + y * width);
  30453. byteArray[index] = srcData[srcPos];
  30454. index++;
  30455. }
  30456. }
  30457. return byteArray;
  30458. };
  30459. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30460. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30461. if (header[off_magic] != DDS_MAGIC) {
  30462. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30463. return;
  30464. }
  30465. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30466. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30467. return;
  30468. }
  30469. if (info.isFourCC) {
  30470. fourCC = header[off_pfFourCC];
  30471. switch (fourCC) {
  30472. case FOURCC_DXT1:
  30473. blockBytes = 8;
  30474. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30475. break;
  30476. case FOURCC_DXT3:
  30477. blockBytes = 16;
  30478. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30479. break;
  30480. case FOURCC_DXT5:
  30481. blockBytes = 16;
  30482. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30483. break;
  30484. default:
  30485. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30486. return;
  30487. }
  30488. }
  30489. mipmapCount = 1;
  30490. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30491. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30492. }
  30493. var bpp = header[off_RGBbpp];
  30494. for (var face = 0; face < faces; face++) {
  30495. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30496. width = header[off_width];
  30497. height = header[off_height];
  30498. dataOffset = header[off_size] + 4;
  30499. for (i = 0; i < mipmapCount; ++i) {
  30500. if (info.isRGB) {
  30501. if (bpp === 24) {
  30502. dataLength = width * height * 3;
  30503. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30504. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30505. }
  30506. else {
  30507. dataLength = width * height * 4;
  30508. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30509. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30510. }
  30511. }
  30512. else if (info.isLuminance) {
  30513. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30514. var unpaddedRowSize = width;
  30515. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30516. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30517. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30518. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30519. }
  30520. else {
  30521. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30522. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30523. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30524. }
  30525. dataOffset += dataLength;
  30526. width *= 0.5;
  30527. height *= 0.5;
  30528. width = Math.max(1.0, width);
  30529. height = Math.max(1.0, height);
  30530. }
  30531. }
  30532. };
  30533. return DDSTools;
  30534. })();
  30535. Internals.DDSTools = DDSTools;
  30536. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30537. })(BABYLON || (BABYLON = {}));
  30538. var BABYLON;
  30539. (function (BABYLON) {
  30540. var CannonJSPlugin = (function () {
  30541. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30542. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30543. if (iterations === void 0) { iterations = 10; }
  30544. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30545. this.name = "CannonJSPlugin";
  30546. this._physicsMaterials = [];
  30547. this._fixedTimeStep = 1 / 60;
  30548. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30549. this._currentCollisionGroup = 2;
  30550. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30551. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30552. this._tmpPosition = BABYLON.Vector3.Zero();
  30553. this._tmpQuaternion = new BABYLON.Quaternion();
  30554. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30555. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30556. this._tmpUnityRotation = new BABYLON.Quaternion();
  30557. if (!this.isSupported()) {
  30558. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30559. return;
  30560. }
  30561. this.world = new CANNON.World();
  30562. this.world.broadphase = new CANNON.NaiveBroadphase();
  30563. this.world.solver.iterations = iterations;
  30564. }
  30565. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30566. this.world.gravity.copy(gravity);
  30567. };
  30568. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30569. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30570. };
  30571. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30572. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30573. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30574. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30575. };
  30576. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30577. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30578. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30579. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30580. };
  30581. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30582. //parent-child relationship. Does this impostor has a parent impostor?
  30583. if (impostor.parent) {
  30584. if (impostor.physicsBody) {
  30585. this.removePhysicsBody(impostor);
  30586. //TODO is that needed?
  30587. impostor.forceUpdate();
  30588. }
  30589. return;
  30590. }
  30591. //should a new body be created for this impostor?
  30592. if (impostor.isBodyInitRequired()) {
  30593. if (!impostor.mesh.rotationQuaternion) {
  30594. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30595. }
  30596. var shape = this._createShape(impostor);
  30597. //unregister events, if body is being changed
  30598. var oldBody = impostor.physicsBody;
  30599. if (oldBody) {
  30600. this.removePhysicsBody(impostor);
  30601. }
  30602. //create the body and material
  30603. var material = this._addMaterial(impostor.getParam("friction"), impostor.getParam("restitution"));
  30604. var bodyCreationObject = {
  30605. mass: impostor.getParam("mass"),
  30606. material: material
  30607. };
  30608. // A simple extend, in case native options were used.
  30609. var nativeOptions = impostor.getParam("nativeOptions");
  30610. for (var key in nativeOptions) {
  30611. if (nativeOptions.hasOwnProperty(key)) {
  30612. bodyCreationObject[key] = nativeOptions[key];
  30613. }
  30614. }
  30615. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30616. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30617. this.world.addEventListener("preStep", impostor.beforeStep);
  30618. this.world.addEventListener("postStep", impostor.afterStep);
  30619. impostor.physicsBody.addShape(shape);
  30620. this.world.add(impostor.physicsBody);
  30621. //try to keep the body moving in the right direction by taking old properties.
  30622. //Should be tested!
  30623. if (oldBody) {
  30624. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30625. impostor.physicsBody[param].copy(oldBody[param]);
  30626. });
  30627. }
  30628. this._processChildMeshes(impostor);
  30629. }
  30630. //now update the body's transformation
  30631. this._updatePhysicsBodyTransformation(impostor);
  30632. };
  30633. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30634. var _this = this;
  30635. var meshChildren = mainImpostor.mesh.getChildMeshes(true);
  30636. if (meshChildren.length) {
  30637. var processMesh = function (relativePosition, mesh) {
  30638. var childImpostor = mesh.getPhysicsImpostor();
  30639. if (childImpostor) {
  30640. var parent = childImpostor.parent;
  30641. if (parent !== mainImpostor) {
  30642. var localPosition = mesh.position.add(relativePosition);
  30643. if (childImpostor.physicsBody) {
  30644. _this.removePhysicsBody(childImpostor);
  30645. childImpostor.physicsBody = null;
  30646. }
  30647. childImpostor.parent = mainImpostor;
  30648. childImpostor.resetUpdateFlags();
  30649. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30650. //Add the mass of the children.
  30651. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30652. }
  30653. }
  30654. mesh.getChildMeshes(true).forEach(processMesh.bind(_this, mesh.position));
  30655. };
  30656. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30657. }
  30658. };
  30659. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30660. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30661. this.world.removeEventListener("preStep", impostor.beforeStep);
  30662. this.world.removeEventListener("postStep", impostor.afterStep);
  30663. this.world.remove(impostor.physicsBody);
  30664. };
  30665. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30666. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30667. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30668. if (!mainBody || !connectedBody) {
  30669. return;
  30670. }
  30671. var constraint;
  30672. var jointData = impostorJoint.joint.jointData;
  30673. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30674. var constraintData = {
  30675. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30676. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30677. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30678. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30679. maxForce: jointData.nativeParams.maxForce
  30680. };
  30681. if (!jointData.collision) {
  30682. //add 1st body to a collision group of its own, if it is not in 1
  30683. if (mainBody.collisionFilterGroup === 1) {
  30684. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30685. this._currentCollisionGroup <<= 1;
  30686. }
  30687. if (connectedBody.collisionFilterGroup === 1) {
  30688. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30689. this._currentCollisionGroup <<= 1;
  30690. }
  30691. //add their mask to the collisionFilterMask of each other:
  30692. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30693. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30694. }
  30695. switch (impostorJoint.joint.type) {
  30696. case BABYLON.PhysicsJoint.HingeJoint:
  30697. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30698. break;
  30699. case BABYLON.PhysicsJoint.DistanceJoint:
  30700. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30701. break;
  30702. default:
  30703. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30704. break;
  30705. }
  30706. impostorJoint.joint.physicsJoint = constraint;
  30707. this.world.addConstraint(constraint);
  30708. };
  30709. CannonJSPlugin.prototype.removeJoint = function (joint) {
  30710. //TODO
  30711. };
  30712. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30713. var index;
  30714. var mat;
  30715. for (index = 0; index < this._physicsMaterials.length; index++) {
  30716. mat = this._physicsMaterials[index];
  30717. if (mat.friction === friction && mat.restitution === restitution) {
  30718. return mat;
  30719. }
  30720. }
  30721. var currentMat = new CANNON.Material("mat");
  30722. this._physicsMaterials.push(currentMat);
  30723. for (index = 0; index < this._physicsMaterials.length; index++) {
  30724. mat = this._physicsMaterials[index];
  30725. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30726. this.world.addContactMaterial(contactMaterial);
  30727. }
  30728. return currentMat;
  30729. };
  30730. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30731. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30732. };
  30733. CannonJSPlugin.prototype._createShape = function (impostor) {
  30734. var mesh = impostor.mesh;
  30735. //get the correct bounding box
  30736. var oldQuaternion = mesh.rotationQuaternion;
  30737. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30738. mesh.computeWorldMatrix(true);
  30739. var returnValue;
  30740. switch (impostor.type) {
  30741. case BABYLON.PhysicsEngine.SphereImpostor:
  30742. var bbox = mesh.getBoundingInfo().boundingBox;
  30743. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30744. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30745. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30746. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30747. break;
  30748. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30749. case BABYLON.PhysicsEngine.CylinderImpostor:
  30750. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30751. case BABYLON.PhysicsEngine.BoxImpostor:
  30752. bbox = mesh.getBoundingInfo().boundingBox;
  30753. var min = bbox.minimumWorld;
  30754. var max = bbox.maximumWorld;
  30755. var box = max.subtract(min).scale(0.5);
  30756. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30757. break;
  30758. case BABYLON.PhysicsEngine.PlaneImpostor:
  30759. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  30760. returnValue = new CANNON.Plane();
  30761. break;
  30762. case BABYLON.PhysicsEngine.MeshImpostor:
  30763. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30764. var rawFaces = mesh.getIndices();
  30765. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30766. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  30767. break;
  30768. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30769. returnValue = this._createHeightmap(mesh);
  30770. break;
  30771. }
  30772. mesh.rotationQuaternion = oldQuaternion;
  30773. return returnValue;
  30774. };
  30775. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30776. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30777. var matrix = [];
  30778. //For now pointDepth will not be used and will be automatically calculated.
  30779. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30780. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30781. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30782. var elementSize = dim * 2 / arraySize;
  30783. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30784. for (var i = 0; i < pos.length; i = i + 3) {
  30785. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30786. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30787. var y = pos[i + 1] + minY;
  30788. if (!matrix[x]) {
  30789. matrix[x] = [];
  30790. }
  30791. if (!matrix[x][z]) {
  30792. matrix[x][z] = y;
  30793. }
  30794. matrix[x][z] = Math.max(y, matrix[x][z]);
  30795. }
  30796. for (var x = 0; x <= arraySize; ++x) {
  30797. if (!matrix[x]) {
  30798. var loc = 1;
  30799. while (!matrix[(x + loc) % arraySize]) {
  30800. loc++;
  30801. }
  30802. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30803. }
  30804. for (var z = 0; z <= arraySize; ++z) {
  30805. if (!matrix[x][z]) {
  30806. var loc = 1;
  30807. var newValue;
  30808. while (newValue === undefined) {
  30809. newValue = matrix[x][(z + loc++) % arraySize];
  30810. }
  30811. matrix[x][z] = newValue;
  30812. }
  30813. }
  30814. }
  30815. var shape = new CANNON.Heightfield(matrix, {
  30816. elementSize: elementSize
  30817. });
  30818. //For future reference, needed for body transformation
  30819. shape.minY = minY;
  30820. return shape;
  30821. };
  30822. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  30823. var mesh = impostor.mesh;
  30824. //make sure it is updated...
  30825. impostor.mesh.computeWorldMatrix(true);
  30826. // The delta between the mesh position and the mesh bounding box center
  30827. var bbox = mesh.getBoundingInfo().boundingBox;
  30828. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  30829. var quaternion = mesh.rotationQuaternion;
  30830. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  30831. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30832. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  30833. //-90 DEG in X, precalculated
  30834. quaternion = quaternion.multiply(this._minus90X);
  30835. //Invert! (Precalculated, 90 deg in X)
  30836. //No need to clone. this will never change.
  30837. impostor.setDeltaRotation(this._plus90X);
  30838. }
  30839. //If it is a heightfield, if should be centered.
  30840. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  30841. //calculate the correct body position:
  30842. var rotationQuaternion = mesh.rotationQuaternion;
  30843. mesh.rotationQuaternion = this._tmpUnityRotation;
  30844. mesh.computeWorldMatrix(true);
  30845. //get original center with no rotation
  30846. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30847. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30848. //rotation is back
  30849. mesh.rotationQuaternion = rotationQuaternion;
  30850. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30851. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30852. mesh.setPivotMatrix(p);
  30853. mesh.computeWorldMatrix(true);
  30854. //calculate the translation
  30855. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30856. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30857. //add it inverted to the delta
  30858. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  30859. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30860. mesh.setPivotMatrix(oldPivot);
  30861. mesh.computeWorldMatrix(true);
  30862. }
  30863. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  30864. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  30865. this._tmpPosition.copyFrom(mesh.position);
  30866. }
  30867. impostor.setDeltaPosition(this._tmpDeltaPosition);
  30868. //Now update the impostor object
  30869. impostor.physicsBody.position.copy(this._tmpPosition);
  30870. impostor.physicsBody.quaternion.copy(quaternion);
  30871. };
  30872. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  30873. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  30874. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  30875. };
  30876. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  30877. impostor.physicsBody.position.copy(newPosition);
  30878. impostor.physicsBody.quaternion.copy(newRotation);
  30879. };
  30880. CannonJSPlugin.prototype.isSupported = function () {
  30881. return window.CANNON !== undefined;
  30882. };
  30883. CannonJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  30884. impostor.physicsBody.velocity.copy(velocity);
  30885. };
  30886. CannonJSPlugin.prototype.dispose = function () {
  30887. //nothing to do, actually.
  30888. };
  30889. return CannonJSPlugin;
  30890. })();
  30891. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30892. })(BABYLON || (BABYLON = {}));
  30893. var BABYLON;
  30894. (function (BABYLON) {
  30895. var OimoJSPlugin = (function () {
  30896. function OimoJSPlugin(iterations) {
  30897. this.name = "OimoJSPlugin";
  30898. this._tmpImpostorsArray = [];
  30899. this._tmpPositionVector = BABYLON.Vector3.Zero();
  30900. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  30901. this.world.clear();
  30902. //making sure no stats are calculated
  30903. this.world.isNoStat = true;
  30904. }
  30905. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30906. this.world.gravity.copy(gravity);
  30907. };
  30908. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  30909. var _this = this;
  30910. impostors.forEach(function (impostor) {
  30911. impostor.beforeStep();
  30912. });
  30913. this.world.step();
  30914. impostors.forEach(function (impostor) {
  30915. impostor.afterStep();
  30916. //update the ordered impostors array
  30917. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  30918. });
  30919. //check for collisions
  30920. var contact = this.world.contacts;
  30921. while (contact !== null) {
  30922. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30923. contact = contact.next;
  30924. continue;
  30925. }
  30926. //is this body colliding with any other? get the impostor
  30927. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  30928. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  30929. if (!mainImpostor || !collidingImpostor) {
  30930. contact = contact.next;
  30931. continue;
  30932. }
  30933. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  30934. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  30935. contact = contact.next;
  30936. }
  30937. };
  30938. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30939. var mass = impostor.physicsBody.massInfo.mass;
  30940. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30941. };
  30942. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30943. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  30944. this.applyImpulse(impostor, force, contactPoint);
  30945. };
  30946. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30947. var _this = this;
  30948. //parent-child relationship. Does this impostor has a parent impostor?
  30949. if (impostor.parent) {
  30950. if (impostor.physicsBody) {
  30951. this.removePhysicsBody(impostor);
  30952. //TODO is that needed?
  30953. impostor.forceUpdate();
  30954. }
  30955. return;
  30956. }
  30957. impostor.mesh.computeWorldMatrix(true);
  30958. if (impostor.isBodyInitRequired()) {
  30959. if (!impostor.mesh.rotationQuaternion) {
  30960. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30961. }
  30962. var bodyConfig = {
  30963. name: impostor.mesh.uniqueId,
  30964. //Oimo must have mass, also for static objects.
  30965. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  30966. size: [],
  30967. type: [],
  30968. pos: [],
  30969. rot: [],
  30970. move: impostor.getParam("mass") !== 0,
  30971. //Supporting older versions of Oimo
  30972. world: this.world
  30973. };
  30974. var impostors = [impostor];
  30975. function addToArray(parent) {
  30976. parent.getChildMeshes().forEach(function (m) {
  30977. if (m.physicsImpostor) {
  30978. impostors.push(m.physicsImpostor);
  30979. m.physicsImpostor._init();
  30980. }
  30981. });
  30982. }
  30983. addToArray(impostor.mesh);
  30984. function checkWithEpsilon(value) {
  30985. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  30986. }
  30987. impostors.forEach(function (i) {
  30988. //get the correct bounding box
  30989. var oldQuaternion = i.mesh.rotationQuaternion;
  30990. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  30991. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30992. i.mesh.computeWorldMatrix(true);
  30993. var bbox = i.mesh.getBoundingInfo().boundingBox;
  30994. if (i === impostor) {
  30995. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  30996. //Can also use Array.prototype.push.apply
  30997. bodyConfig.pos.push(bbox.center.x);
  30998. bodyConfig.pos.push(bbox.center.y);
  30999. bodyConfig.pos.push(bbox.center.z);
  31000. //tmp solution
  31001. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31002. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31003. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31004. }
  31005. else {
  31006. bodyConfig.pos.push(i.mesh.position.x);
  31007. bodyConfig.pos.push(i.mesh.position.y);
  31008. bodyConfig.pos.push(i.mesh.position.z);
  31009. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31010. bodyConfig.rot.push(0);
  31011. bodyConfig.rot.push(0);
  31012. bodyConfig.rot.push(0);
  31013. }
  31014. // register mesh
  31015. switch (i.type) {
  31016. case BABYLON.PhysicsEngine.SphereImpostor:
  31017. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31018. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31019. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31020. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31021. bodyConfig.type.push('sphere');
  31022. //due to the way oimo works with compounds, add 3 times
  31023. bodyConfig.size.push(size);
  31024. bodyConfig.size.push(size);
  31025. bodyConfig.size.push(size);
  31026. break;
  31027. case BABYLON.PhysicsEngine.PlaneImpostor:
  31028. //TODO Oimo now supports cylinder!
  31029. case BABYLON.PhysicsEngine.CylinderImpostor:
  31030. case BABYLON.PhysicsEngine.BoxImpostor:
  31031. default:
  31032. var min = bbox.minimumWorld;
  31033. var max = bbox.maximumWorld;
  31034. var box = max.subtract(min);
  31035. var sizeX = checkWithEpsilon(box.x);
  31036. var sizeY = checkWithEpsilon(box.y);
  31037. var sizeZ = checkWithEpsilon(box.z);
  31038. bodyConfig.type.push('box');
  31039. bodyConfig.size.push(sizeX);
  31040. bodyConfig.size.push(sizeY);
  31041. bodyConfig.size.push(sizeZ);
  31042. break;
  31043. }
  31044. //actually not needed, but hey...
  31045. i.mesh.rotationQuaternion = oldQuaternion;
  31046. });
  31047. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31048. }
  31049. else {
  31050. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31051. }
  31052. impostor.setDeltaPosition(this._tmpPositionVector);
  31053. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31054. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31055. };
  31056. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31057. //impostor.physicsBody.dispose();
  31058. //Same as : (older oimo versions)
  31059. this.world.removeRigidBody(impostor.physicsBody);
  31060. };
  31061. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31062. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31063. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31064. if (!mainBody || !connectedBody) {
  31065. return;
  31066. }
  31067. var jointData = impostorJoint.joint.jointData;
  31068. var options = jointData.nativeParams || {};
  31069. var type;
  31070. var nativeJointData = {
  31071. body1: mainBody,
  31072. body2: connectedBody,
  31073. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31074. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31075. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31076. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31077. min: options.min,
  31078. max: options.max,
  31079. collision: options.collision || jointData.collision,
  31080. spring: options.spring,
  31081. //supporting older version of Oimo
  31082. world: this.world
  31083. };
  31084. switch (impostorJoint.joint.type) {
  31085. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31086. type = "jointBall";
  31087. break;
  31088. case BABYLON.PhysicsJoint.DistanceJoint:
  31089. type = "jointDistance";
  31090. nativeJointData.max = jointData.maxDistance;
  31091. break;
  31092. case BABYLON.PhysicsJoint.PrismaticJoint:
  31093. type = "jointPrisme";
  31094. break;
  31095. case BABYLON.PhysicsJoint.SliderJoint:
  31096. type = "jointSlide";
  31097. break;
  31098. case BABYLON.PhysicsJoint.WheelJoint:
  31099. type = "jointWheel";
  31100. break;
  31101. case BABYLON.PhysicsJoint.HingeJoint:
  31102. default:
  31103. type = "jointHinge";
  31104. break;
  31105. }
  31106. nativeJointData.type = type;
  31107. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31108. };
  31109. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31110. joint.joint.physicsJoint.dispose();
  31111. };
  31112. OimoJSPlugin.prototype.isSupported = function () {
  31113. return OIMO !== undefined;
  31114. };
  31115. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31116. if (!impostor.physicsBody.sleeping) {
  31117. //TODO check that
  31118. if (impostor.physicsBody.shapes.next) {
  31119. var parentShape = this._getLastShape(impostor.physicsBody);
  31120. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31121. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31122. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31123. }
  31124. else {
  31125. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31126. }
  31127. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31128. }
  31129. };
  31130. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31131. var body = impostor.physicsBody;
  31132. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31133. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31134. body.syncShapes();
  31135. body.awake();
  31136. };
  31137. OimoJSPlugin.prototype._getLastShape = function (body) {
  31138. var lastShape = body.shapes;
  31139. while (lastShape.next) {
  31140. lastShape = lastShape.next;
  31141. }
  31142. return lastShape;
  31143. };
  31144. OimoJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31145. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31146. };
  31147. OimoJSPlugin.prototype.dispose = function () {
  31148. this.world.clear();
  31149. };
  31150. return OimoJSPlugin;
  31151. })();
  31152. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31153. })(BABYLON || (BABYLON = {}));
  31154. var BABYLON;
  31155. (function (BABYLON) {
  31156. var DisplayPassPostProcess = (function (_super) {
  31157. __extends(DisplayPassPostProcess, _super);
  31158. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31159. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31160. }
  31161. return DisplayPassPostProcess;
  31162. })(BABYLON.PostProcess);
  31163. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31164. })(BABYLON || (BABYLON = {}));
  31165. var BABYLON;
  31166. (function (BABYLON) {
  31167. var SimplificationSettings = (function () {
  31168. function SimplificationSettings(quality, distance, optimizeMesh) {
  31169. this.quality = quality;
  31170. this.distance = distance;
  31171. this.optimizeMesh = optimizeMesh;
  31172. }
  31173. return SimplificationSettings;
  31174. })();
  31175. BABYLON.SimplificationSettings = SimplificationSettings;
  31176. var SimplificationQueue = (function () {
  31177. function SimplificationQueue() {
  31178. this.running = false;
  31179. this._simplificationArray = [];
  31180. }
  31181. SimplificationQueue.prototype.addTask = function (task) {
  31182. this._simplificationArray.push(task);
  31183. };
  31184. SimplificationQueue.prototype.executeNext = function () {
  31185. var task = this._simplificationArray.pop();
  31186. if (task) {
  31187. this.running = true;
  31188. this.runSimplification(task);
  31189. }
  31190. else {
  31191. this.running = false;
  31192. }
  31193. };
  31194. SimplificationQueue.prototype.runSimplification = function (task) {
  31195. var _this = this;
  31196. if (task.parallelProcessing) {
  31197. //parallel simplifier
  31198. task.settings.forEach(function (setting) {
  31199. var simplifier = _this.getSimplifier(task);
  31200. simplifier.simplify(setting, function (newMesh) {
  31201. task.mesh.addLODLevel(setting.distance, newMesh);
  31202. newMesh.isVisible = true;
  31203. //check if it is the last
  31204. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31205. //all done, run the success callback.
  31206. task.successCallback();
  31207. }
  31208. _this.executeNext();
  31209. });
  31210. });
  31211. }
  31212. else {
  31213. //single simplifier.
  31214. var simplifier = this.getSimplifier(task);
  31215. var runDecimation = function (setting, callback) {
  31216. simplifier.simplify(setting, function (newMesh) {
  31217. task.mesh.addLODLevel(setting.distance, newMesh);
  31218. newMesh.isVisible = true;
  31219. //run the next quality level
  31220. callback();
  31221. });
  31222. };
  31223. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31224. runDecimation(task.settings[loop.index], function () {
  31225. loop.executeNext();
  31226. });
  31227. }, function () {
  31228. //execution ended, run the success callback.
  31229. if (task.successCallback) {
  31230. task.successCallback();
  31231. }
  31232. _this.executeNext();
  31233. });
  31234. }
  31235. };
  31236. SimplificationQueue.prototype.getSimplifier = function (task) {
  31237. switch (task.simplificationType) {
  31238. case SimplificationType.QUADRATIC:
  31239. default:
  31240. return new QuadraticErrorSimplification(task.mesh);
  31241. }
  31242. };
  31243. return SimplificationQueue;
  31244. })();
  31245. BABYLON.SimplificationQueue = SimplificationQueue;
  31246. /**
  31247. * The implemented types of simplification.
  31248. * At the moment only Quadratic Error Decimation is implemented.
  31249. */
  31250. (function (SimplificationType) {
  31251. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31252. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31253. var SimplificationType = BABYLON.SimplificationType;
  31254. var DecimationTriangle = (function () {
  31255. function DecimationTriangle(vertices) {
  31256. this.vertices = vertices;
  31257. this.error = new Array(4);
  31258. this.deleted = false;
  31259. this.isDirty = false;
  31260. this.deletePending = false;
  31261. this.borderFactor = 0;
  31262. }
  31263. return DecimationTriangle;
  31264. })();
  31265. BABYLON.DecimationTriangle = DecimationTriangle;
  31266. var DecimationVertex = (function () {
  31267. function DecimationVertex(position, id) {
  31268. this.position = position;
  31269. this.id = id;
  31270. this.isBorder = true;
  31271. this.q = new QuadraticMatrix();
  31272. this.triangleCount = 0;
  31273. this.triangleStart = 0;
  31274. this.originalOffsets = [];
  31275. }
  31276. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31277. this.position.copyFrom(newPosition);
  31278. };
  31279. return DecimationVertex;
  31280. })();
  31281. BABYLON.DecimationVertex = DecimationVertex;
  31282. var QuadraticMatrix = (function () {
  31283. function QuadraticMatrix(data) {
  31284. this.data = new Array(10);
  31285. for (var i = 0; i < 10; ++i) {
  31286. if (data && data[i]) {
  31287. this.data[i] = data[i];
  31288. }
  31289. else {
  31290. this.data[i] = 0;
  31291. }
  31292. }
  31293. }
  31294. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31295. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31296. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31297. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31298. return det;
  31299. };
  31300. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31301. for (var i = 0; i < 10; ++i) {
  31302. this.data[i] += matrix.data[i];
  31303. }
  31304. };
  31305. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31306. for (var i = 0; i < 10; ++i) {
  31307. this.data[i] += data[i];
  31308. }
  31309. };
  31310. QuadraticMatrix.prototype.add = function (matrix) {
  31311. var m = new QuadraticMatrix();
  31312. for (var i = 0; i < 10; ++i) {
  31313. m.data[i] = this.data[i] + matrix.data[i];
  31314. }
  31315. return m;
  31316. };
  31317. QuadraticMatrix.FromData = function (a, b, c, d) {
  31318. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31319. };
  31320. //returning an array to avoid garbage collection
  31321. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31322. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31323. };
  31324. return QuadraticMatrix;
  31325. })();
  31326. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31327. var Reference = (function () {
  31328. function Reference(vertexId, triangleId) {
  31329. this.vertexId = vertexId;
  31330. this.triangleId = triangleId;
  31331. }
  31332. return Reference;
  31333. })();
  31334. BABYLON.Reference = Reference;
  31335. /**
  31336. * An implementation of the Quadratic Error simplification algorithm.
  31337. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31338. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31339. * @author RaananW
  31340. */
  31341. var QuadraticErrorSimplification = (function () {
  31342. function QuadraticErrorSimplification(_mesh) {
  31343. this._mesh = _mesh;
  31344. this.initialized = false;
  31345. this.syncIterations = 5000;
  31346. this.aggressiveness = 7;
  31347. this.decimationIterations = 100;
  31348. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31349. }
  31350. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31351. var _this = this;
  31352. this.initDecimatedMesh();
  31353. //iterating through the submeshes array, one after the other.
  31354. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31355. _this.initWithMesh(loop.index, function () {
  31356. _this.runDecimation(settings, loop.index, function () {
  31357. loop.executeNext();
  31358. });
  31359. }, settings.optimizeMesh);
  31360. }, function () {
  31361. setTimeout(function () {
  31362. successCallback(_this._reconstructedMesh);
  31363. }, 0);
  31364. });
  31365. };
  31366. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31367. var _this = this;
  31368. var gCount = 0;
  31369. triangle.vertices.forEach(function (vertex) {
  31370. var count = 0;
  31371. var vPos = vertex.position;
  31372. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31373. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31374. ++count;
  31375. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31376. ++count;
  31377. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31378. ++count;
  31379. if (count > 1) {
  31380. ++gCount;
  31381. }
  31382. ;
  31383. });
  31384. if (gCount > 1) {
  31385. console.log(triangle, gCount);
  31386. }
  31387. return gCount > 1;
  31388. };
  31389. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31390. var _this = this;
  31391. var targetCount = ~~(this.triangles.length * settings.quality);
  31392. var deletedTriangles = 0;
  31393. var triangleCount = this.triangles.length;
  31394. var iterationFunction = function (iteration, callback) {
  31395. setTimeout(function () {
  31396. if (iteration % 5 === 0) {
  31397. _this.updateMesh(iteration === 0);
  31398. }
  31399. for (var i = 0; i < _this.triangles.length; ++i) {
  31400. _this.triangles[i].isDirty = false;
  31401. }
  31402. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31403. var trianglesIterator = function (i) {
  31404. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31405. var t = _this.triangles[tIdx];
  31406. if (!t)
  31407. return;
  31408. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31409. return;
  31410. }
  31411. for (var j = 0; j < 3; ++j) {
  31412. if (t.error[j] < threshold) {
  31413. var deleted0 = [];
  31414. var deleted1 = [];
  31415. var v0 = t.vertices[j];
  31416. var v1 = t.vertices[(j + 1) % 3];
  31417. if (v0.isBorder !== v1.isBorder)
  31418. continue;
  31419. var p = BABYLON.Vector3.Zero();
  31420. var n = BABYLON.Vector3.Zero();
  31421. var uv = BABYLON.Vector2.Zero();
  31422. var color = new BABYLON.Color4(0, 0, 0, 1);
  31423. _this.calculateError(v0, v1, p, n, uv, color);
  31424. var delTr = [];
  31425. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31426. continue;
  31427. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31428. continue;
  31429. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31430. continue;
  31431. var uniqueArray = [];
  31432. delTr.forEach(function (deletedT) {
  31433. if (uniqueArray.indexOf(deletedT) === -1) {
  31434. deletedT.deletePending = true;
  31435. uniqueArray.push(deletedT);
  31436. }
  31437. });
  31438. if (uniqueArray.length % 2 !== 0) {
  31439. continue;
  31440. }
  31441. v0.q = v1.q.add(v0.q);
  31442. v0.updatePosition(p);
  31443. var tStart = _this.references.length;
  31444. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31445. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31446. var tCount = _this.references.length - tStart;
  31447. if (tCount <= v0.triangleCount) {
  31448. if (tCount) {
  31449. for (var c = 0; c < tCount; c++) {
  31450. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31451. }
  31452. }
  31453. }
  31454. else {
  31455. v0.triangleStart = tStart;
  31456. }
  31457. v0.triangleCount = tCount;
  31458. break;
  31459. }
  31460. }
  31461. };
  31462. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31463. }, 0);
  31464. };
  31465. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31466. if (triangleCount - deletedTriangles <= targetCount)
  31467. loop.breakLoop();
  31468. else {
  31469. iterationFunction(loop.index, function () {
  31470. loop.executeNext();
  31471. });
  31472. }
  31473. }, function () {
  31474. setTimeout(function () {
  31475. //reconstruct this part of the mesh
  31476. _this.reconstructMesh(submeshIndex);
  31477. successCallback();
  31478. }, 0);
  31479. });
  31480. };
  31481. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31482. var _this = this;
  31483. this.vertices = [];
  31484. this.triangles = [];
  31485. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31486. var indices = this._mesh.getIndices();
  31487. var submesh = this._mesh.subMeshes[submeshIndex];
  31488. var findInVertices = function (positionToSearch) {
  31489. if (optimizeMesh) {
  31490. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31491. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31492. return _this.vertices[ii];
  31493. }
  31494. }
  31495. }
  31496. return null;
  31497. };
  31498. var vertexReferences = [];
  31499. var vertexInit = function (i) {
  31500. var offset = i + submesh.verticesStart;
  31501. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31502. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31503. vertex.originalOffsets.push(offset);
  31504. if (vertex.id === _this.vertices.length) {
  31505. _this.vertices.push(vertex);
  31506. }
  31507. vertexReferences.push(vertex.id);
  31508. };
  31509. //var totalVertices = mesh.getTotalVertices();
  31510. var totalVertices = submesh.verticesCount;
  31511. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31512. var indicesInit = function (i) {
  31513. var offset = (submesh.indexStart / 3) + i;
  31514. var pos = (offset * 3);
  31515. var i0 = indices[pos + 0];
  31516. var i1 = indices[pos + 1];
  31517. var i2 = indices[pos + 2];
  31518. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31519. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31520. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31521. var triangle = new DecimationTriangle([v0, v1, v2]);
  31522. triangle.originalOffset = pos;
  31523. _this.triangles.push(triangle);
  31524. };
  31525. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31526. _this.init(callback);
  31527. });
  31528. });
  31529. };
  31530. QuadraticErrorSimplification.prototype.init = function (callback) {
  31531. var _this = this;
  31532. var triangleInit1 = function (i) {
  31533. var t = _this.triangles[i];
  31534. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31535. for (var j = 0; j < 3; j++) {
  31536. 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))));
  31537. }
  31538. };
  31539. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31540. var triangleInit2 = function (i) {
  31541. var t = _this.triangles[i];
  31542. for (var j = 0; j < 3; ++j) {
  31543. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31544. }
  31545. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31546. };
  31547. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31548. _this.initialized = true;
  31549. callback();
  31550. });
  31551. });
  31552. };
  31553. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31554. var newTriangles = [];
  31555. var i;
  31556. for (i = 0; i < this.vertices.length; ++i) {
  31557. this.vertices[i].triangleCount = 0;
  31558. }
  31559. var t;
  31560. var j;
  31561. for (i = 0; i < this.triangles.length; ++i) {
  31562. if (!this.triangles[i].deleted) {
  31563. t = this.triangles[i];
  31564. for (j = 0; j < 3; ++j) {
  31565. t.vertices[j].triangleCount = 1;
  31566. }
  31567. newTriangles.push(t);
  31568. }
  31569. }
  31570. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31571. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31572. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31573. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31574. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31575. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31576. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31577. var vertexCount = 0;
  31578. for (i = 0; i < this.vertices.length; ++i) {
  31579. var vertex = this.vertices[i];
  31580. vertex.id = vertexCount;
  31581. if (vertex.triangleCount) {
  31582. vertex.originalOffsets.forEach(function (originalOffset) {
  31583. newPositionData.push(vertex.position.x);
  31584. newPositionData.push(vertex.position.y);
  31585. newPositionData.push(vertex.position.z);
  31586. newNormalData.push(normalData[originalOffset * 3]);
  31587. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31588. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31589. if (uvs && uvs.length) {
  31590. newUVsData.push(uvs[(originalOffset * 2)]);
  31591. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31592. }
  31593. else if (colorsData && colorsData.length) {
  31594. newColorsData.push(colorsData[(originalOffset * 4)]);
  31595. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31596. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31597. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31598. }
  31599. ++vertexCount;
  31600. });
  31601. }
  31602. }
  31603. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31604. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31605. var submeshesArray = this._reconstructedMesh.subMeshes;
  31606. this._reconstructedMesh.subMeshes = [];
  31607. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31608. var originalIndices = this._mesh.getIndices();
  31609. for (i = 0; i < newTriangles.length; ++i) {
  31610. t = newTriangles[i]; //now get the new referencing point for each vertex
  31611. [0, 1, 2].forEach(function (idx) {
  31612. var id = originalIndices[t.originalOffset + idx];
  31613. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31614. if (offset < 0)
  31615. offset = 0;
  31616. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31617. });
  31618. }
  31619. //overwriting the old vertex buffers and indices.
  31620. this._reconstructedMesh.setIndices(newIndicesArray);
  31621. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31622. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31623. if (newUVsData.length > 0)
  31624. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31625. if (newColorsData.length > 0)
  31626. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31627. //create submesh
  31628. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31629. if (submeshIndex > 0) {
  31630. this._reconstructedMesh.subMeshes = [];
  31631. submeshesArray.forEach(function (submesh) {
  31632. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31633. });
  31634. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31635. }
  31636. };
  31637. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31638. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31639. this._reconstructedMesh.material = this._mesh.material;
  31640. this._reconstructedMesh.parent = this._mesh.parent;
  31641. this._reconstructedMesh.isVisible = false;
  31642. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31643. };
  31644. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31645. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31646. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31647. if (t.deleted)
  31648. continue;
  31649. var s = this.references[vertex1.triangleStart + i].vertexId;
  31650. var v1 = t.vertices[(s + 1) % 3];
  31651. var v2 = t.vertices[(s + 2) % 3];
  31652. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31653. deletedArray[i] = true;
  31654. delTr.push(t);
  31655. continue;
  31656. }
  31657. var d1 = v1.position.subtract(point);
  31658. d1 = d1.normalize();
  31659. var d2 = v2.position.subtract(point);
  31660. d2 = d2.normalize();
  31661. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31662. return true;
  31663. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31664. deletedArray[i] = false;
  31665. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31666. return true;
  31667. }
  31668. return false;
  31669. };
  31670. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31671. var newDeleted = deletedTriangles;
  31672. for (var i = 0; i < vertex.triangleCount; ++i) {
  31673. var ref = this.references[vertex.triangleStart + i];
  31674. var t = this.triangles[ref.triangleId];
  31675. if (t.deleted)
  31676. continue;
  31677. if (deletedArray[i] && t.deletePending) {
  31678. t.deleted = true;
  31679. newDeleted++;
  31680. continue;
  31681. }
  31682. t.vertices[ref.vertexId] = origVertex;
  31683. t.isDirty = true;
  31684. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31685. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31686. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31687. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31688. this.references.push(ref);
  31689. }
  31690. return newDeleted;
  31691. };
  31692. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31693. for (var i = 0; i < this.vertices.length; ++i) {
  31694. var vCount = [];
  31695. var vId = [];
  31696. var v = this.vertices[i];
  31697. var j;
  31698. for (j = 0; j < v.triangleCount; ++j) {
  31699. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31700. for (var ii = 0; ii < 3; ii++) {
  31701. var ofs = 0;
  31702. var vv = triangle.vertices[ii];
  31703. while (ofs < vCount.length) {
  31704. if (vId[ofs] === vv.id)
  31705. break;
  31706. ++ofs;
  31707. }
  31708. if (ofs === vCount.length) {
  31709. vCount.push(1);
  31710. vId.push(vv.id);
  31711. }
  31712. else {
  31713. vCount[ofs]++;
  31714. }
  31715. }
  31716. }
  31717. for (j = 0; j < vCount.length; ++j) {
  31718. if (vCount[j] === 1) {
  31719. this.vertices[vId[j]].isBorder = true;
  31720. }
  31721. else {
  31722. this.vertices[vId[j]].isBorder = false;
  31723. }
  31724. }
  31725. }
  31726. };
  31727. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31728. if (identifyBorders === void 0) { identifyBorders = false; }
  31729. var i;
  31730. if (!identifyBorders) {
  31731. var newTrianglesVector = [];
  31732. for (i = 0; i < this.triangles.length; ++i) {
  31733. if (!this.triangles[i].deleted) {
  31734. newTrianglesVector.push(this.triangles[i]);
  31735. }
  31736. }
  31737. this.triangles = newTrianglesVector;
  31738. }
  31739. for (i = 0; i < this.vertices.length; ++i) {
  31740. this.vertices[i].triangleCount = 0;
  31741. this.vertices[i].triangleStart = 0;
  31742. }
  31743. var t;
  31744. var j;
  31745. var v;
  31746. for (i = 0; i < this.triangles.length; ++i) {
  31747. t = this.triangles[i];
  31748. for (j = 0; j < 3; ++j) {
  31749. v = t.vertices[j];
  31750. v.triangleCount++;
  31751. }
  31752. }
  31753. var tStart = 0;
  31754. for (i = 0; i < this.vertices.length; ++i) {
  31755. this.vertices[i].triangleStart = tStart;
  31756. tStart += this.vertices[i].triangleCount;
  31757. this.vertices[i].triangleCount = 0;
  31758. }
  31759. var newReferences = new Array(this.triangles.length * 3);
  31760. for (i = 0; i < this.triangles.length; ++i) {
  31761. t = this.triangles[i];
  31762. for (j = 0; j < 3; ++j) {
  31763. v = t.vertices[j];
  31764. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31765. v.triangleCount++;
  31766. }
  31767. }
  31768. this.references = newReferences;
  31769. if (identifyBorders) {
  31770. this.identifyBorder();
  31771. }
  31772. };
  31773. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31774. var x = point.x;
  31775. var y = point.y;
  31776. var z = point.z;
  31777. 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
  31778. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31779. };
  31780. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31781. var q = vertex1.q.add(vertex2.q);
  31782. var border = vertex1.isBorder && vertex2.isBorder;
  31783. var error = 0;
  31784. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31785. if (qDet !== 0 && !border) {
  31786. if (!pointResult) {
  31787. pointResult = BABYLON.Vector3.Zero();
  31788. }
  31789. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31790. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31791. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31792. error = this.vertexError(q, pointResult);
  31793. }
  31794. else {
  31795. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31796. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31797. var error1 = this.vertexError(q, vertex1.position);
  31798. var error2 = this.vertexError(q, vertex2.position);
  31799. var error3 = this.vertexError(q, p3);
  31800. error = Math.min(error1, error2, error3);
  31801. if (error === error1) {
  31802. if (pointResult) {
  31803. pointResult.copyFrom(vertex1.position);
  31804. }
  31805. }
  31806. else if (error === error2) {
  31807. if (pointResult) {
  31808. pointResult.copyFrom(vertex2.position);
  31809. }
  31810. }
  31811. else {
  31812. if (pointResult) {
  31813. pointResult.copyFrom(p3);
  31814. }
  31815. }
  31816. }
  31817. return error;
  31818. };
  31819. return QuadraticErrorSimplification;
  31820. })();
  31821. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31822. })(BABYLON || (BABYLON = {}));
  31823. var BABYLON;
  31824. (function (BABYLON) {
  31825. var serializedGeometries = [];
  31826. var serializeGeometry = function (geometry, serializationGeometries) {
  31827. if (serializedGeometries[geometry.id]) {
  31828. return;
  31829. }
  31830. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31831. serializationGeometries.boxes.push(geometry.serialize());
  31832. }
  31833. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31834. serializationGeometries.spheres.push(geometry.serialize());
  31835. }
  31836. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31837. serializationGeometries.cylinders.push(geometry.serialize());
  31838. }
  31839. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31840. serializationGeometries.toruses.push(geometry.serialize());
  31841. }
  31842. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31843. serializationGeometries.grounds.push(geometry.serialize());
  31844. }
  31845. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31846. serializationGeometries.planes.push(geometry.serialize());
  31847. }
  31848. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31849. serializationGeometries.torusKnots.push(geometry.serialize());
  31850. }
  31851. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31852. throw new Error("Unknown primitive type");
  31853. }
  31854. else {
  31855. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31856. }
  31857. serializedGeometries[geometry.id] = true;
  31858. };
  31859. var serializeMesh = function (mesh, serializationScene) {
  31860. var serializationObject = {};
  31861. serializationObject.name = mesh.name;
  31862. serializationObject.id = mesh.id;
  31863. if (BABYLON.Tags.HasTags(mesh)) {
  31864. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31865. }
  31866. serializationObject.position = mesh.position.asArray();
  31867. if (mesh.rotationQuaternion) {
  31868. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31869. }
  31870. else if (mesh.rotation) {
  31871. serializationObject.rotation = mesh.rotation.asArray();
  31872. }
  31873. serializationObject.scaling = mesh.scaling.asArray();
  31874. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31875. serializationObject.isEnabled = mesh.isEnabled();
  31876. serializationObject.isVisible = mesh.isVisible;
  31877. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31878. serializationObject.pickable = mesh.isPickable;
  31879. serializationObject.receiveShadows = mesh.receiveShadows;
  31880. serializationObject.billboardMode = mesh.billboardMode;
  31881. serializationObject.visibility = mesh.visibility;
  31882. serializationObject.checkCollisions = mesh.checkCollisions;
  31883. // Parent
  31884. if (mesh.parent) {
  31885. serializationObject.parentId = mesh.parent.id;
  31886. }
  31887. // Geometry
  31888. var geometry = mesh._geometry;
  31889. if (geometry) {
  31890. var geometryId = geometry.id;
  31891. serializationObject.geometryId = geometryId;
  31892. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31893. // 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
  31894. serializeGeometry(geometry, serializationScene.geometries);
  31895. }
  31896. // SubMeshes
  31897. serializationObject.subMeshes = [];
  31898. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31899. var subMesh = mesh.subMeshes[subIndex];
  31900. serializationObject.subMeshes.push({
  31901. materialIndex: subMesh.materialIndex,
  31902. verticesStart: subMesh.verticesStart,
  31903. verticesCount: subMesh.verticesCount,
  31904. indexStart: subMesh.indexStart,
  31905. indexCount: subMesh.indexCount
  31906. });
  31907. }
  31908. }
  31909. // Material
  31910. if (mesh.material) {
  31911. serializationObject.materialId = mesh.material.id;
  31912. }
  31913. else {
  31914. mesh.material = null;
  31915. }
  31916. // Skeleton
  31917. if (mesh.skeleton) {
  31918. serializationObject.skeletonId = mesh.skeleton.id;
  31919. }
  31920. // Physics
  31921. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  31922. serializationObject.physicsMass = mesh.getPhysicsMass();
  31923. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31924. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31925. switch (mesh.getPhysicsImpostor().type) {
  31926. case BABYLON.PhysicsEngine.BoxImpostor:
  31927. serializationObject.physicsImpostor = 1;
  31928. break;
  31929. case BABYLON.PhysicsEngine.SphereImpostor:
  31930. serializationObject.physicsImpostor = 2;
  31931. break;
  31932. }
  31933. }
  31934. // Instances
  31935. serializationObject.instances = [];
  31936. for (var index = 0; index < mesh.instances.length; index++) {
  31937. var instance = mesh.instances[index];
  31938. var serializationInstance = {
  31939. name: instance.name,
  31940. position: instance.position.asArray(),
  31941. scaling: instance.scaling.asArray()
  31942. };
  31943. if (instance.rotationQuaternion) {
  31944. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31945. }
  31946. else if (instance.rotation) {
  31947. serializationInstance.rotation = instance.rotation.asArray();
  31948. }
  31949. serializationObject.instances.push(serializationInstance);
  31950. // Animations
  31951. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31952. serializationInstance.ranges = instance.serializeAnimationRanges();
  31953. }
  31954. // Animations
  31955. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31956. serializationObject.ranges = mesh.serializeAnimationRanges();
  31957. // Layer mask
  31958. serializationObject.layerMask = mesh.layerMask;
  31959. return serializationObject;
  31960. };
  31961. var finalizeSingleMesh = function (mesh, serializationObject) {
  31962. //only works if the mesh is already loaded
  31963. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31964. //serialize material
  31965. if (mesh.material) {
  31966. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31967. serializationObject.materials = serializationObject.materials || [];
  31968. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31969. serializationObject.materials.push(mesh.material.serialize());
  31970. }
  31971. }
  31972. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31973. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31974. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31975. serializationObject.multiMaterials.push(mesh.material.serialize());
  31976. }
  31977. }
  31978. }
  31979. //serialize geometry
  31980. var geometry = mesh._geometry;
  31981. if (geometry) {
  31982. if (!serializationObject.geometries) {
  31983. serializationObject.geometries = {};
  31984. serializationObject.geometries.boxes = [];
  31985. serializationObject.geometries.spheres = [];
  31986. serializationObject.geometries.cylinders = [];
  31987. serializationObject.geometries.toruses = [];
  31988. serializationObject.geometries.grounds = [];
  31989. serializationObject.geometries.planes = [];
  31990. serializationObject.geometries.torusKnots = [];
  31991. serializationObject.geometries.vertexData = [];
  31992. }
  31993. serializeGeometry(geometry, serializationObject.geometries);
  31994. }
  31995. // Skeletons
  31996. if (mesh.skeleton) {
  31997. serializationObject.skeletons = serializationObject.skeletons || [];
  31998. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31999. }
  32000. //serialize the actual mesh
  32001. serializationObject.meshes = serializationObject.meshes || [];
  32002. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32003. }
  32004. };
  32005. var SceneSerializer = (function () {
  32006. function SceneSerializer() {
  32007. }
  32008. SceneSerializer.ClearCache = function () {
  32009. serializedGeometries = [];
  32010. };
  32011. SceneSerializer.Serialize = function (scene) {
  32012. var serializationObject = {};
  32013. // Scene
  32014. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32015. serializationObject.autoClear = scene.autoClear;
  32016. serializationObject.clearColor = scene.clearColor.asArray();
  32017. serializationObject.ambientColor = scene.ambientColor.asArray();
  32018. serializationObject.gravity = scene.gravity.asArray();
  32019. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32020. serializationObject.workerCollisions = scene.workerCollisions;
  32021. // Fog
  32022. if (scene.fogMode && scene.fogMode !== 0) {
  32023. serializationObject.fogMode = scene.fogMode;
  32024. serializationObject.fogColor = scene.fogColor.asArray();
  32025. serializationObject.fogStart = scene.fogStart;
  32026. serializationObject.fogEnd = scene.fogEnd;
  32027. serializationObject.fogDensity = scene.fogDensity;
  32028. }
  32029. //Physics
  32030. if (scene.isPhysicsEnabled()) {
  32031. serializationObject.physicsEnabled = true;
  32032. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32033. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32034. }
  32035. // Lights
  32036. serializationObject.lights = [];
  32037. var index;
  32038. var light;
  32039. for (index = 0; index < scene.lights.length; index++) {
  32040. light = scene.lights[index];
  32041. serializationObject.lights.push(light.serialize());
  32042. }
  32043. // Cameras
  32044. serializationObject.cameras = [];
  32045. for (index = 0; index < scene.cameras.length; index++) {
  32046. var camera = scene.cameras[index];
  32047. serializationObject.cameras.push(camera.serialize());
  32048. }
  32049. if (scene.activeCamera) {
  32050. serializationObject.activeCameraID = scene.activeCamera.id;
  32051. }
  32052. // Animations
  32053. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32054. // Materials
  32055. serializationObject.materials = [];
  32056. serializationObject.multiMaterials = [];
  32057. var material;
  32058. for (index = 0; index < scene.materials.length; index++) {
  32059. material = scene.materials[index];
  32060. serializationObject.materials.push(material.serialize());
  32061. }
  32062. // MultiMaterials
  32063. serializationObject.multiMaterials = [];
  32064. for (index = 0; index < scene.multiMaterials.length; index++) {
  32065. var multiMaterial = scene.multiMaterials[index];
  32066. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32067. }
  32068. // Skeletons
  32069. serializationObject.skeletons = [];
  32070. for (index = 0; index < scene.skeletons.length; index++) {
  32071. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32072. }
  32073. // Geometries
  32074. serializationObject.geometries = {};
  32075. serializationObject.geometries.boxes = [];
  32076. serializationObject.geometries.spheres = [];
  32077. serializationObject.geometries.cylinders = [];
  32078. serializationObject.geometries.toruses = [];
  32079. serializationObject.geometries.grounds = [];
  32080. serializationObject.geometries.planes = [];
  32081. serializationObject.geometries.torusKnots = [];
  32082. serializationObject.geometries.vertexData = [];
  32083. serializedGeometries = [];
  32084. var geometries = scene.getGeometries();
  32085. for (index = 0; index < geometries.length; index++) {
  32086. var geometry = geometries[index];
  32087. if (geometry.isReady()) {
  32088. serializeGeometry(geometry, serializationObject.geometries);
  32089. }
  32090. }
  32091. // Meshes
  32092. serializationObject.meshes = [];
  32093. for (index = 0; index < scene.meshes.length; index++) {
  32094. var abstractMesh = scene.meshes[index];
  32095. if (abstractMesh instanceof BABYLON.Mesh) {
  32096. var mesh = abstractMesh;
  32097. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32098. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32099. }
  32100. }
  32101. }
  32102. // Particles Systems
  32103. serializationObject.particleSystems = [];
  32104. for (index = 0; index < scene.particleSystems.length; index++) {
  32105. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32106. }
  32107. // Lens flares
  32108. serializationObject.lensFlareSystems = [];
  32109. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32110. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32111. }
  32112. // Shadows
  32113. serializationObject.shadowGenerators = [];
  32114. for (index = 0; index < scene.lights.length; index++) {
  32115. light = scene.lights[index];
  32116. if (light.getShadowGenerator()) {
  32117. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32118. }
  32119. }
  32120. return serializationObject;
  32121. };
  32122. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32123. if (withParents === void 0) { withParents = false; }
  32124. if (withChildren === void 0) { withChildren = false; }
  32125. var serializationObject = {};
  32126. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32127. if (withParents || withChildren) {
  32128. //deliberate for loop! not for each, appended should be processed as well.
  32129. for (var i = 0; i < toSerialize.length; ++i) {
  32130. if (withChildren) {
  32131. toSerialize[i].getDescendants().forEach(function (node) {
  32132. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32133. toSerialize.push(node);
  32134. }
  32135. });
  32136. }
  32137. //make sure the array doesn't contain the object already
  32138. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32139. toSerialize.push(toSerialize[i].parent);
  32140. }
  32141. }
  32142. }
  32143. toSerialize.forEach(function (mesh) {
  32144. finalizeSingleMesh(mesh, serializationObject);
  32145. });
  32146. return serializationObject;
  32147. };
  32148. return SceneSerializer;
  32149. })();
  32150. BABYLON.SceneSerializer = SceneSerializer;
  32151. })(BABYLON || (BABYLON = {}));
  32152. var BABYLON;
  32153. (function (BABYLON) {
  32154. // Unique ID when we import meshes from Babylon to CSG
  32155. var currentCSGMeshId = 0;
  32156. // # class Vertex
  32157. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32158. // one to provide additional features like texture coordinates and vertex
  32159. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32160. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32161. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32162. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32163. // is not used anywhere else.
  32164. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32165. var Vertex = (function () {
  32166. function Vertex(pos, normal, uv) {
  32167. this.pos = pos;
  32168. this.normal = normal;
  32169. this.uv = uv;
  32170. }
  32171. Vertex.prototype.clone = function () {
  32172. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32173. };
  32174. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32175. // orientation of a polygon is flipped.
  32176. Vertex.prototype.flip = function () {
  32177. this.normal = this.normal.scale(-1);
  32178. };
  32179. // Create a new vertex between this vertex and `other` by linearly
  32180. // interpolating all properties using a parameter of `t`. Subclasses should
  32181. // override this to interpolate additional properties.
  32182. Vertex.prototype.interpolate = function (other, t) {
  32183. 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));
  32184. };
  32185. return Vertex;
  32186. })();
  32187. // # class Plane
  32188. // Represents a plane in 3D space.
  32189. var Plane = (function () {
  32190. function Plane(normal, w) {
  32191. this.normal = normal;
  32192. this.w = w;
  32193. }
  32194. Plane.FromPoints = function (a, b, c) {
  32195. var v0 = c.subtract(a);
  32196. var v1 = b.subtract(a);
  32197. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32198. return null;
  32199. }
  32200. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32201. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32202. };
  32203. Plane.prototype.clone = function () {
  32204. return new Plane(this.normal.clone(), this.w);
  32205. };
  32206. Plane.prototype.flip = function () {
  32207. this.normal.scaleInPlace(-1);
  32208. this.w = -this.w;
  32209. };
  32210. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32211. // fragments in the appropriate lists. Coplanar polygons go into either
  32212. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32213. // respect to this plane. Polygons in front or in back of this plane go into
  32214. // either `front` or `back`.
  32215. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32216. var COPLANAR = 0;
  32217. var FRONT = 1;
  32218. var BACK = 2;
  32219. var SPANNING = 3;
  32220. // Classify each point as well as the entire polygon into one of the above
  32221. // four classes.
  32222. var polygonType = 0;
  32223. var types = [];
  32224. var i;
  32225. var t;
  32226. for (i = 0; i < polygon.vertices.length; i++) {
  32227. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32228. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32229. polygonType |= type;
  32230. types.push(type);
  32231. }
  32232. // Put the polygon in the correct list, splitting it when necessary.
  32233. switch (polygonType) {
  32234. case COPLANAR:
  32235. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32236. break;
  32237. case FRONT:
  32238. front.push(polygon);
  32239. break;
  32240. case BACK:
  32241. back.push(polygon);
  32242. break;
  32243. case SPANNING:
  32244. var f = [], b = [];
  32245. for (i = 0; i < polygon.vertices.length; i++) {
  32246. var j = (i + 1) % polygon.vertices.length;
  32247. var ti = types[i], tj = types[j];
  32248. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32249. if (ti !== BACK)
  32250. f.push(vi);
  32251. if (ti !== FRONT)
  32252. b.push(ti !== BACK ? vi.clone() : vi);
  32253. if ((ti | tj) === SPANNING) {
  32254. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32255. var v = vi.interpolate(vj, t);
  32256. f.push(v);
  32257. b.push(v.clone());
  32258. }
  32259. }
  32260. var poly;
  32261. if (f.length >= 3) {
  32262. poly = new Polygon(f, polygon.shared);
  32263. if (poly.plane)
  32264. front.push(poly);
  32265. }
  32266. if (b.length >= 3) {
  32267. poly = new Polygon(b, polygon.shared);
  32268. if (poly.plane)
  32269. back.push(poly);
  32270. }
  32271. break;
  32272. }
  32273. };
  32274. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32275. // point is on the plane.
  32276. Plane.EPSILON = 1e-5;
  32277. return Plane;
  32278. })();
  32279. // # class Polygon
  32280. // Represents a convex polygon. The vertices used to initialize a polygon must
  32281. // be coplanar and form a convex loop.
  32282. //
  32283. // Each convex polygon has a `shared` property, which is shared between all
  32284. // polygons that are clones of each other or were split from the same polygon.
  32285. // This can be used to define per-polygon properties (such as surface color).
  32286. var Polygon = (function () {
  32287. function Polygon(vertices, shared) {
  32288. this.vertices = vertices;
  32289. this.shared = shared;
  32290. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32291. }
  32292. Polygon.prototype.clone = function () {
  32293. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32294. return new Polygon(vertices, this.shared);
  32295. };
  32296. Polygon.prototype.flip = function () {
  32297. this.vertices.reverse().map(function (v) { v.flip(); });
  32298. this.plane.flip();
  32299. };
  32300. return Polygon;
  32301. })();
  32302. // # class Node
  32303. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32304. // by picking a polygon to split along. That polygon (and all other coplanar
  32305. // polygons) are added directly to that node and the other polygons are added to
  32306. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32307. // no distinction between internal and leaf nodes.
  32308. var Node = (function () {
  32309. function Node(polygons) {
  32310. this.plane = null;
  32311. this.front = null;
  32312. this.back = null;
  32313. this.polygons = [];
  32314. if (polygons) {
  32315. this.build(polygons);
  32316. }
  32317. }
  32318. Node.prototype.clone = function () {
  32319. var node = new Node();
  32320. node.plane = this.plane && this.plane.clone();
  32321. node.front = this.front && this.front.clone();
  32322. node.back = this.back && this.back.clone();
  32323. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32324. return node;
  32325. };
  32326. // Convert solid space to empty space and empty space to solid space.
  32327. Node.prototype.invert = function () {
  32328. for (var i = 0; i < this.polygons.length; i++) {
  32329. this.polygons[i].flip();
  32330. }
  32331. if (this.plane) {
  32332. this.plane.flip();
  32333. }
  32334. if (this.front) {
  32335. this.front.invert();
  32336. }
  32337. if (this.back) {
  32338. this.back.invert();
  32339. }
  32340. var temp = this.front;
  32341. this.front = this.back;
  32342. this.back = temp;
  32343. };
  32344. // Recursively remove all polygons in `polygons` that are inside this BSP
  32345. // tree.
  32346. Node.prototype.clipPolygons = function (polygons) {
  32347. if (!this.plane)
  32348. return polygons.slice();
  32349. var front = [], back = [];
  32350. for (var i = 0; i < polygons.length; i++) {
  32351. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32352. }
  32353. if (this.front) {
  32354. front = this.front.clipPolygons(front);
  32355. }
  32356. if (this.back) {
  32357. back = this.back.clipPolygons(back);
  32358. }
  32359. else {
  32360. back = [];
  32361. }
  32362. return front.concat(back);
  32363. };
  32364. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32365. // `bsp`.
  32366. Node.prototype.clipTo = function (bsp) {
  32367. this.polygons = bsp.clipPolygons(this.polygons);
  32368. if (this.front)
  32369. this.front.clipTo(bsp);
  32370. if (this.back)
  32371. this.back.clipTo(bsp);
  32372. };
  32373. // Return a list of all polygons in this BSP tree.
  32374. Node.prototype.allPolygons = function () {
  32375. var polygons = this.polygons.slice();
  32376. if (this.front)
  32377. polygons = polygons.concat(this.front.allPolygons());
  32378. if (this.back)
  32379. polygons = polygons.concat(this.back.allPolygons());
  32380. return polygons;
  32381. };
  32382. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32383. // new polygons are filtered down to the bottom of the tree and become new
  32384. // nodes there. Each set of polygons is partitioned using the first polygon
  32385. // (no heuristic is used to pick a good split).
  32386. Node.prototype.build = function (polygons) {
  32387. if (!polygons.length)
  32388. return;
  32389. if (!this.plane)
  32390. this.plane = polygons[0].plane.clone();
  32391. var front = [], back = [];
  32392. for (var i = 0; i < polygons.length; i++) {
  32393. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32394. }
  32395. if (front.length) {
  32396. if (!this.front)
  32397. this.front = new Node();
  32398. this.front.build(front);
  32399. }
  32400. if (back.length) {
  32401. if (!this.back)
  32402. this.back = new Node();
  32403. this.back.build(back);
  32404. }
  32405. };
  32406. return Node;
  32407. })();
  32408. var CSG = (function () {
  32409. function CSG() {
  32410. this.polygons = new Array();
  32411. }
  32412. // Convert BABYLON.Mesh to BABYLON.CSG
  32413. CSG.FromMesh = function (mesh) {
  32414. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32415. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32416. if (mesh instanceof BABYLON.Mesh) {
  32417. mesh.computeWorldMatrix(true);
  32418. matrix = mesh.getWorldMatrix();
  32419. meshPosition = mesh.position.clone();
  32420. meshRotation = mesh.rotation.clone();
  32421. if (mesh.rotationQuaternion) {
  32422. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32423. }
  32424. meshScaling = mesh.scaling.clone();
  32425. }
  32426. else {
  32427. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32428. }
  32429. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32430. var subMeshes = mesh.subMeshes;
  32431. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32432. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32433. vertices = [];
  32434. for (var j = 0; j < 3; j++) {
  32435. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32436. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32437. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32438. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32439. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32440. vertex = new Vertex(position, normal, uv);
  32441. vertices.push(vertex);
  32442. }
  32443. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32444. // To handle the case of degenerated triangle
  32445. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32446. if (polygon.plane)
  32447. polygons.push(polygon);
  32448. }
  32449. }
  32450. var csg = CSG.FromPolygons(polygons);
  32451. csg.matrix = matrix;
  32452. csg.position = meshPosition;
  32453. csg.rotation = meshRotation;
  32454. csg.scaling = meshScaling;
  32455. csg.rotationQuaternion = meshRotationQuaternion;
  32456. currentCSGMeshId++;
  32457. return csg;
  32458. };
  32459. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32460. CSG.FromPolygons = function (polygons) {
  32461. var csg = new CSG();
  32462. csg.polygons = polygons;
  32463. return csg;
  32464. };
  32465. CSG.prototype.clone = function () {
  32466. var csg = new CSG();
  32467. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32468. csg.copyTransformAttributes(this);
  32469. return csg;
  32470. };
  32471. CSG.prototype.toPolygons = function () {
  32472. return this.polygons;
  32473. };
  32474. CSG.prototype.union = function (csg) {
  32475. var a = new Node(this.clone().polygons);
  32476. var b = new Node(csg.clone().polygons);
  32477. a.clipTo(b);
  32478. b.clipTo(a);
  32479. b.invert();
  32480. b.clipTo(a);
  32481. b.invert();
  32482. a.build(b.allPolygons());
  32483. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32484. };
  32485. CSG.prototype.unionInPlace = function (csg) {
  32486. var a = new Node(this.polygons);
  32487. var b = new Node(csg.polygons);
  32488. a.clipTo(b);
  32489. b.clipTo(a);
  32490. b.invert();
  32491. b.clipTo(a);
  32492. b.invert();
  32493. a.build(b.allPolygons());
  32494. this.polygons = a.allPolygons();
  32495. };
  32496. CSG.prototype.subtract = function (csg) {
  32497. var a = new Node(this.clone().polygons);
  32498. var b = new Node(csg.clone().polygons);
  32499. a.invert();
  32500. a.clipTo(b);
  32501. b.clipTo(a);
  32502. b.invert();
  32503. b.clipTo(a);
  32504. b.invert();
  32505. a.build(b.allPolygons());
  32506. a.invert();
  32507. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32508. };
  32509. CSG.prototype.subtractInPlace = function (csg) {
  32510. var a = new Node(this.polygons);
  32511. var b = new Node(csg.polygons);
  32512. a.invert();
  32513. a.clipTo(b);
  32514. b.clipTo(a);
  32515. b.invert();
  32516. b.clipTo(a);
  32517. b.invert();
  32518. a.build(b.allPolygons());
  32519. a.invert();
  32520. this.polygons = a.allPolygons();
  32521. };
  32522. CSG.prototype.intersect = function (csg) {
  32523. var a = new Node(this.clone().polygons);
  32524. var b = new Node(csg.clone().polygons);
  32525. a.invert();
  32526. b.clipTo(a);
  32527. b.invert();
  32528. a.clipTo(b);
  32529. b.clipTo(a);
  32530. a.build(b.allPolygons());
  32531. a.invert();
  32532. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32533. };
  32534. CSG.prototype.intersectInPlace = function (csg) {
  32535. var a = new Node(this.polygons);
  32536. var b = new Node(csg.polygons);
  32537. a.invert();
  32538. b.clipTo(a);
  32539. b.invert();
  32540. a.clipTo(b);
  32541. b.clipTo(a);
  32542. a.build(b.allPolygons());
  32543. a.invert();
  32544. this.polygons = a.allPolygons();
  32545. };
  32546. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32547. // not modified.
  32548. CSG.prototype.inverse = function () {
  32549. var csg = this.clone();
  32550. csg.inverseInPlace();
  32551. return csg;
  32552. };
  32553. CSG.prototype.inverseInPlace = function () {
  32554. this.polygons.map(function (p) { p.flip(); });
  32555. };
  32556. // This is used to keep meshes transformations so they can be restored
  32557. // when we build back a Babylon Mesh
  32558. // NB : All CSG operations are performed in world coordinates
  32559. CSG.prototype.copyTransformAttributes = function (csg) {
  32560. this.matrix = csg.matrix;
  32561. this.position = csg.position;
  32562. this.rotation = csg.rotation;
  32563. this.scaling = csg.scaling;
  32564. this.rotationQuaternion = csg.rotationQuaternion;
  32565. return this;
  32566. };
  32567. // Build Raw mesh from CSG
  32568. // Coordinates here are in world space
  32569. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32570. var matrix = this.matrix.clone();
  32571. matrix.invert();
  32572. 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;
  32573. if (keepSubMeshes) {
  32574. // Sort Polygons, since subMeshes are indices range
  32575. polygons.sort(function (a, b) {
  32576. if (a.shared.meshId === b.shared.meshId) {
  32577. return a.shared.subMeshId - b.shared.subMeshId;
  32578. }
  32579. else {
  32580. return a.shared.meshId - b.shared.meshId;
  32581. }
  32582. });
  32583. }
  32584. for (var i = 0, il = polygons.length; i < il; i++) {
  32585. polygon = polygons[i];
  32586. // Building SubMeshes
  32587. if (!subMesh_dict[polygon.shared.meshId]) {
  32588. subMesh_dict[polygon.shared.meshId] = {};
  32589. }
  32590. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32591. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32592. indexStart: +Infinity,
  32593. indexEnd: -Infinity,
  32594. materialIndex: polygon.shared.materialIndex
  32595. };
  32596. }
  32597. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32598. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32599. polygonIndices[0] = 0;
  32600. polygonIndices[1] = j - 1;
  32601. polygonIndices[2] = j;
  32602. for (var k = 0; k < 3; k++) {
  32603. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32604. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32605. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32606. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32607. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32608. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32609. // Check if 2 points can be merged
  32610. if (!(typeof vertex_idx !== 'undefined' &&
  32611. normals[vertex_idx * 3] === localNormal.x &&
  32612. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32613. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32614. uvs[vertex_idx * 2] === uv.x &&
  32615. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32616. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32617. uvs.push(uv.x, uv.y);
  32618. normals.push(normal.x, normal.y, normal.z);
  32619. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32620. }
  32621. indices.push(vertex_idx);
  32622. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32623. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32624. currentIndex++;
  32625. }
  32626. }
  32627. }
  32628. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32629. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32630. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32631. mesh.setIndices(indices);
  32632. if (keepSubMeshes) {
  32633. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32634. var materialIndexOffset = 0, materialMaxIndex;
  32635. mesh.subMeshes = new Array();
  32636. for (var m in subMesh_dict) {
  32637. materialMaxIndex = -1;
  32638. for (var sm in subMesh_dict[m]) {
  32639. subMesh_obj = subMesh_dict[m][sm];
  32640. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32641. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32642. }
  32643. materialIndexOffset += ++materialMaxIndex;
  32644. }
  32645. }
  32646. return mesh;
  32647. };
  32648. // Build Mesh from CSG taking material and transforms into account
  32649. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32650. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32651. mesh.material = material;
  32652. mesh.position.copyFrom(this.position);
  32653. mesh.rotation.copyFrom(this.rotation);
  32654. if (this.rotationQuaternion) {
  32655. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32656. }
  32657. mesh.scaling.copyFrom(this.scaling);
  32658. mesh.computeWorldMatrix(true);
  32659. return mesh;
  32660. };
  32661. return CSG;
  32662. })();
  32663. BABYLON.CSG = CSG;
  32664. })(BABYLON || (BABYLON = {}));
  32665. var BABYLON;
  32666. (function (BABYLON) {
  32667. var VRDistortionCorrectionPostProcess = (function (_super) {
  32668. __extends(VRDistortionCorrectionPostProcess, _super);
  32669. //ANY
  32670. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32671. var _this = this;
  32672. _super.call(this, name, "vrDistortionCorrection", [
  32673. 'LensCenter',
  32674. 'Scale',
  32675. 'ScaleIn',
  32676. 'HmdWarpParam'
  32677. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32678. this._isRightEye = isRightEye;
  32679. this._distortionFactors = vrMetrics.distortionK;
  32680. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32681. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32682. this.onSizeChanged = function () {
  32683. _this.aspectRatio = _this.width * .5 / _this.height;
  32684. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32685. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32686. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32687. };
  32688. this.onApply = function (effect) {
  32689. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32690. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32691. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32692. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32693. };
  32694. }
  32695. return VRDistortionCorrectionPostProcess;
  32696. })(BABYLON.PostProcess);
  32697. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32698. })(BABYLON || (BABYLON = {}));
  32699. // Mainly based on these 2 articles :
  32700. // 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
  32701. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32702. var BABYLON;
  32703. (function (BABYLON) {
  32704. (function (JoystickAxis) {
  32705. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32706. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32707. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32708. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32709. var JoystickAxis = BABYLON.JoystickAxis;
  32710. var VirtualJoystick = (function () {
  32711. function VirtualJoystick(leftJoystick) {
  32712. var _this = this;
  32713. if (leftJoystick) {
  32714. this._leftJoystick = true;
  32715. }
  32716. else {
  32717. this._leftJoystick = false;
  32718. }
  32719. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32720. VirtualJoystick._globalJoystickIndex++;
  32721. // By default left & right arrow keys are moving the X
  32722. // and up & down keys are moving the Y
  32723. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32724. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32725. this.reverseLeftRight = false;
  32726. this.reverseUpDown = false;
  32727. // collections of pointers
  32728. this._touches = new BABYLON.SmartCollection();
  32729. this.deltaPosition = BABYLON.Vector3.Zero();
  32730. this._joystickSensibility = 25;
  32731. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32732. this._rotationSpeed = 25;
  32733. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32734. this._rotateOnAxisRelativeToMesh = false;
  32735. this._onResize = function (evt) {
  32736. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32737. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32738. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32739. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32740. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32741. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32742. };
  32743. // injecting a canvas element on top of the canvas 3D game
  32744. if (!VirtualJoystick.vjCanvas) {
  32745. window.addEventListener("resize", this._onResize, false);
  32746. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32747. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32748. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32749. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32750. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32751. VirtualJoystick.vjCanvas.style.width = "100%";
  32752. VirtualJoystick.vjCanvas.style.height = "100%";
  32753. VirtualJoystick.vjCanvas.style.position = "absolute";
  32754. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32755. VirtualJoystick.vjCanvas.style.top = "0px";
  32756. VirtualJoystick.vjCanvas.style.left = "0px";
  32757. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32758. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32759. // Support for jQuery PEP polyfill
  32760. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32761. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32762. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32763. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32764. document.body.appendChild(VirtualJoystick.vjCanvas);
  32765. }
  32766. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32767. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32768. this.pressed = false;
  32769. // default joystick color
  32770. this._joystickColor = "cyan";
  32771. this._joystickPointerID = -1;
  32772. // current joystick position
  32773. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32774. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32775. // origin joystick position
  32776. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32777. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32778. this._onPointerDownHandlerRef = function (evt) {
  32779. _this._onPointerDown(evt);
  32780. };
  32781. this._onPointerMoveHandlerRef = function (evt) {
  32782. _this._onPointerMove(evt);
  32783. };
  32784. this._onPointerOutHandlerRef = function (evt) {
  32785. _this._onPointerUp(evt);
  32786. };
  32787. this._onPointerUpHandlerRef = function (evt) {
  32788. _this._onPointerUp(evt);
  32789. };
  32790. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32791. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32792. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32793. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32794. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32795. evt.preventDefault(); // Disables system menu
  32796. }, false);
  32797. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32798. }
  32799. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32800. this._joystickSensibility = newJoystickSensibility;
  32801. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32802. };
  32803. VirtualJoystick.prototype._onPointerDown = function (e) {
  32804. var positionOnScreenCondition;
  32805. e.preventDefault();
  32806. if (this._leftJoystick === true) {
  32807. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32808. }
  32809. else {
  32810. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32811. }
  32812. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32813. // First contact will be dedicated to the virtual joystick
  32814. this._joystickPointerID = e.pointerId;
  32815. this._joystickPointerStartPos.x = e.clientX;
  32816. this._joystickPointerStartPos.y = e.clientY;
  32817. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32818. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32819. this._deltaJoystickVector.x = 0;
  32820. this._deltaJoystickVector.y = 0;
  32821. this.pressed = true;
  32822. this._touches.add(e.pointerId.toString(), e);
  32823. }
  32824. else {
  32825. // You can only trigger the action buttons with a joystick declared
  32826. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32827. this._action();
  32828. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32829. }
  32830. }
  32831. };
  32832. VirtualJoystick.prototype._onPointerMove = function (e) {
  32833. // If the current pointer is the one associated to the joystick (first touch contact)
  32834. if (this._joystickPointerID == e.pointerId) {
  32835. this._joystickPointerPos.x = e.clientX;
  32836. this._joystickPointerPos.y = e.clientY;
  32837. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32838. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32839. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32840. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32841. switch (this._axisTargetedByLeftAndRight) {
  32842. case JoystickAxis.X:
  32843. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32844. break;
  32845. case JoystickAxis.Y:
  32846. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32847. break;
  32848. case JoystickAxis.Z:
  32849. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32850. break;
  32851. }
  32852. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32853. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32854. switch (this._axisTargetedByUpAndDown) {
  32855. case JoystickAxis.X:
  32856. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32857. break;
  32858. case JoystickAxis.Y:
  32859. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32860. break;
  32861. case JoystickAxis.Z:
  32862. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32863. break;
  32864. }
  32865. }
  32866. else {
  32867. if (this._touches.item(e.pointerId.toString())) {
  32868. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32869. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32870. }
  32871. }
  32872. };
  32873. VirtualJoystick.prototype._onPointerUp = function (e) {
  32874. if (this._joystickPointerID == e.pointerId) {
  32875. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32876. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32877. this._joystickPointerID = -1;
  32878. this.pressed = false;
  32879. }
  32880. else {
  32881. var touch = this._touches.item(e.pointerId.toString());
  32882. if (touch) {
  32883. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32884. }
  32885. }
  32886. this._deltaJoystickVector.x = 0;
  32887. this._deltaJoystickVector.y = 0;
  32888. this._touches.remove(e.pointerId.toString());
  32889. };
  32890. /**
  32891. * Change the color of the virtual joystick
  32892. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32893. */
  32894. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32895. this._joystickColor = newColor;
  32896. };
  32897. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32898. this._action = action;
  32899. };
  32900. // Define which axis you'd like to control for left & right
  32901. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32902. switch (axis) {
  32903. case JoystickAxis.X:
  32904. case JoystickAxis.Y:
  32905. case JoystickAxis.Z:
  32906. this._axisTargetedByLeftAndRight = axis;
  32907. break;
  32908. default:
  32909. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32910. break;
  32911. }
  32912. };
  32913. // Define which axis you'd like to control for up & down
  32914. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32915. switch (axis) {
  32916. case JoystickAxis.X:
  32917. case JoystickAxis.Y:
  32918. case JoystickAxis.Z:
  32919. this._axisTargetedByUpAndDown = axis;
  32920. break;
  32921. default:
  32922. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32923. break;
  32924. }
  32925. };
  32926. VirtualJoystick.prototype._clearCanvas = function () {
  32927. if (this._leftJoystick) {
  32928. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32929. }
  32930. else {
  32931. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32932. }
  32933. };
  32934. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32935. var _this = this;
  32936. if (this.pressed) {
  32937. this._touches.forEach(function (touch) {
  32938. if (touch.pointerId === _this._joystickPointerID) {
  32939. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32940. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32941. VirtualJoystick.vjCanvasContext.beginPath();
  32942. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32943. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32944. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32945. VirtualJoystick.vjCanvasContext.stroke();
  32946. VirtualJoystick.vjCanvasContext.closePath();
  32947. VirtualJoystick.vjCanvasContext.beginPath();
  32948. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32949. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32950. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32951. VirtualJoystick.vjCanvasContext.stroke();
  32952. VirtualJoystick.vjCanvasContext.closePath();
  32953. VirtualJoystick.vjCanvasContext.beginPath();
  32954. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32955. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32956. VirtualJoystick.vjCanvasContext.stroke();
  32957. VirtualJoystick.vjCanvasContext.closePath();
  32958. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32959. }
  32960. else {
  32961. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32962. VirtualJoystick.vjCanvasContext.beginPath();
  32963. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32964. VirtualJoystick.vjCanvasContext.beginPath();
  32965. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32966. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32967. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32968. VirtualJoystick.vjCanvasContext.stroke();
  32969. VirtualJoystick.vjCanvasContext.closePath();
  32970. touch.prevX = touch.x;
  32971. touch.prevY = touch.y;
  32972. }
  32973. ;
  32974. });
  32975. }
  32976. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32977. };
  32978. VirtualJoystick.prototype.releaseCanvas = function () {
  32979. if (VirtualJoystick.vjCanvas) {
  32980. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32981. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32982. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32983. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32984. window.removeEventListener("resize", this._onResize);
  32985. document.body.removeChild(VirtualJoystick.vjCanvas);
  32986. VirtualJoystick.vjCanvas = null;
  32987. }
  32988. };
  32989. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32990. VirtualJoystick._globalJoystickIndex = 0;
  32991. return VirtualJoystick;
  32992. })();
  32993. BABYLON.VirtualJoystick = VirtualJoystick;
  32994. })(BABYLON || (BABYLON = {}));
  32995. var BABYLON;
  32996. (function (BABYLON) {
  32997. // We're mainly based on the logic defined into the FreeCamera code
  32998. var VirtualJoysticksCamera = (function (_super) {
  32999. __extends(VirtualJoysticksCamera, _super);
  33000. function VirtualJoysticksCamera(name, position, scene) {
  33001. _super.call(this, name, position, scene);
  33002. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33003. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33004. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33005. this._leftjoystick.setJoystickSensibility(0.15);
  33006. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33007. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33008. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33009. this._rightjoystick.reverseUpDown = true;
  33010. this._rightjoystick.setJoystickSensibility(0.05);
  33011. this._rightjoystick.setJoystickColor("yellow");
  33012. }
  33013. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33014. return this._leftjoystick;
  33015. };
  33016. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33017. return this._rightjoystick;
  33018. };
  33019. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33020. var speed = this._computeLocalCameraSpeed() * 50;
  33021. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33022. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33023. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33024. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33025. if (!this._leftjoystick.pressed) {
  33026. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33027. }
  33028. if (!this._rightjoystick.pressed) {
  33029. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33030. }
  33031. _super.prototype._checkInputs.call(this);
  33032. };
  33033. VirtualJoysticksCamera.prototype.dispose = function () {
  33034. this._leftjoystick.releaseCanvas();
  33035. _super.prototype.dispose.call(this);
  33036. };
  33037. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33038. return "VirtualJoysticksCamera";
  33039. };
  33040. return VirtualJoysticksCamera;
  33041. })(BABYLON.FreeCamera);
  33042. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33043. })(BABYLON || (BABYLON = {}));
  33044. var BABYLON;
  33045. (function (BABYLON) {
  33046. var AnaglyphPostProcess = (function (_super) {
  33047. __extends(AnaglyphPostProcess, _super);
  33048. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33049. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33050. }
  33051. return AnaglyphPostProcess;
  33052. })(BABYLON.PostProcess);
  33053. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33054. })(BABYLON || (BABYLON = {}));
  33055. var BABYLON;
  33056. (function (BABYLON) {
  33057. var OutlineRenderer = (function () {
  33058. function OutlineRenderer(scene) {
  33059. this._scene = scene;
  33060. }
  33061. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33062. var _this = this;
  33063. if (useOverlay === void 0) { useOverlay = false; }
  33064. var scene = this._scene;
  33065. var engine = this._scene.getEngine();
  33066. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33067. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33068. return;
  33069. }
  33070. var mesh = subMesh.getRenderingMesh();
  33071. var material = subMesh.getMaterial();
  33072. engine.enableEffect(this._effect);
  33073. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33074. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33075. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33076. // Bones
  33077. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33078. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33079. }
  33080. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33081. // Alpha test
  33082. if (material && material.needAlphaTesting()) {
  33083. var alphaTexture = material.getAlphaTestTexture();
  33084. this._effect.setTexture("diffuseSampler", alphaTexture);
  33085. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33086. }
  33087. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33088. };
  33089. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33090. var defines = [];
  33091. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33092. var mesh = subMesh.getMesh();
  33093. var material = subMesh.getMaterial();
  33094. // Alpha test
  33095. if (material && material.needAlphaTesting()) {
  33096. defines.push("#define ALPHATEST");
  33097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33098. attribs.push(BABYLON.VertexBuffer.UVKind);
  33099. defines.push("#define UV1");
  33100. }
  33101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33102. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33103. defines.push("#define UV2");
  33104. }
  33105. }
  33106. // Bones
  33107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33110. if (mesh.numBoneInfluencers > 4) {
  33111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33113. }
  33114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33115. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33116. }
  33117. else {
  33118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33119. }
  33120. // Instances
  33121. if (useInstances) {
  33122. defines.push("#define INSTANCES");
  33123. attribs.push("world0");
  33124. attribs.push("world1");
  33125. attribs.push("world2");
  33126. attribs.push("world3");
  33127. }
  33128. // Get correct effect
  33129. var join = defines.join("\n");
  33130. if (this._cachedDefines !== join) {
  33131. this._cachedDefines = join;
  33132. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33133. }
  33134. return this._effect.isReady();
  33135. };
  33136. return OutlineRenderer;
  33137. })();
  33138. BABYLON.OutlineRenderer = OutlineRenderer;
  33139. })(BABYLON || (BABYLON = {}));
  33140. var BABYLON;
  33141. (function (BABYLON) {
  33142. var MeshAssetTask = (function () {
  33143. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33144. this.name = name;
  33145. this.meshesNames = meshesNames;
  33146. this.rootUrl = rootUrl;
  33147. this.sceneFilename = sceneFilename;
  33148. this.isCompleted = false;
  33149. }
  33150. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33151. var _this = this;
  33152. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33153. _this.loadedMeshes = meshes;
  33154. _this.loadedParticleSystems = particleSystems;
  33155. _this.loadedSkeletons = skeletons;
  33156. _this.isCompleted = true;
  33157. if (_this.onSuccess) {
  33158. _this.onSuccess(_this);
  33159. }
  33160. onSuccess();
  33161. }, null, function () {
  33162. if (_this.onError) {
  33163. _this.onError(_this);
  33164. }
  33165. onError();
  33166. });
  33167. };
  33168. return MeshAssetTask;
  33169. })();
  33170. BABYLON.MeshAssetTask = MeshAssetTask;
  33171. var TextFileAssetTask = (function () {
  33172. function TextFileAssetTask(name, url) {
  33173. this.name = name;
  33174. this.url = url;
  33175. this.isCompleted = false;
  33176. }
  33177. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33178. var _this = this;
  33179. BABYLON.Tools.LoadFile(this.url, function (data) {
  33180. _this.text = data;
  33181. _this.isCompleted = true;
  33182. if (_this.onSuccess) {
  33183. _this.onSuccess(_this);
  33184. }
  33185. onSuccess();
  33186. }, null, scene.database, false, function () {
  33187. if (_this.onError) {
  33188. _this.onError(_this);
  33189. }
  33190. onError();
  33191. });
  33192. };
  33193. return TextFileAssetTask;
  33194. })();
  33195. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33196. var BinaryFileAssetTask = (function () {
  33197. function BinaryFileAssetTask(name, url) {
  33198. this.name = name;
  33199. this.url = url;
  33200. this.isCompleted = false;
  33201. }
  33202. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33203. var _this = this;
  33204. BABYLON.Tools.LoadFile(this.url, function (data) {
  33205. _this.data = data;
  33206. _this.isCompleted = true;
  33207. if (_this.onSuccess) {
  33208. _this.onSuccess(_this);
  33209. }
  33210. onSuccess();
  33211. }, null, scene.database, true, function () {
  33212. if (_this.onError) {
  33213. _this.onError(_this);
  33214. }
  33215. onError();
  33216. });
  33217. };
  33218. return BinaryFileAssetTask;
  33219. })();
  33220. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33221. var ImageAssetTask = (function () {
  33222. function ImageAssetTask(name, url) {
  33223. this.name = name;
  33224. this.url = url;
  33225. this.isCompleted = false;
  33226. }
  33227. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33228. var _this = this;
  33229. var img = new Image();
  33230. img.onload = function () {
  33231. _this.image = img;
  33232. _this.isCompleted = true;
  33233. if (_this.onSuccess) {
  33234. _this.onSuccess(_this);
  33235. }
  33236. onSuccess();
  33237. };
  33238. img.onerror = function () {
  33239. if (_this.onError) {
  33240. _this.onError(_this);
  33241. }
  33242. onError();
  33243. };
  33244. img.src = this.url;
  33245. };
  33246. return ImageAssetTask;
  33247. })();
  33248. BABYLON.ImageAssetTask = ImageAssetTask;
  33249. var TextureAssetTask = (function () {
  33250. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33252. this.name = name;
  33253. this.url = url;
  33254. this.noMipmap = noMipmap;
  33255. this.invertY = invertY;
  33256. this.samplingMode = samplingMode;
  33257. this.isCompleted = false;
  33258. }
  33259. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33260. var _this = this;
  33261. var onload = function () {
  33262. _this.isCompleted = true;
  33263. if (_this.onSuccess) {
  33264. _this.onSuccess(_this);
  33265. }
  33266. onSuccess();
  33267. };
  33268. var onerror = function () {
  33269. if (_this.onError) {
  33270. _this.onError(_this);
  33271. }
  33272. onError();
  33273. };
  33274. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33275. };
  33276. return TextureAssetTask;
  33277. })();
  33278. BABYLON.TextureAssetTask = TextureAssetTask;
  33279. var AssetsManager = (function () {
  33280. function AssetsManager(scene) {
  33281. this._tasks = new Array();
  33282. this._waitingTasksCount = 0;
  33283. this.useDefaultLoadingScreen = true;
  33284. this._scene = scene;
  33285. }
  33286. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33287. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33288. this._tasks.push(task);
  33289. return task;
  33290. };
  33291. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33292. var task = new TextFileAssetTask(taskName, url);
  33293. this._tasks.push(task);
  33294. return task;
  33295. };
  33296. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33297. var task = new BinaryFileAssetTask(taskName, url);
  33298. this._tasks.push(task);
  33299. return task;
  33300. };
  33301. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33302. var task = new ImageAssetTask(taskName, url);
  33303. this._tasks.push(task);
  33304. return task;
  33305. };
  33306. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33307. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33308. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33309. this._tasks.push(task);
  33310. return task;
  33311. };
  33312. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33313. this._waitingTasksCount--;
  33314. if (this._waitingTasksCount === 0) {
  33315. if (this.onFinish) {
  33316. this.onFinish(this._tasks);
  33317. }
  33318. this._scene.getEngine().hideLoadingUI();
  33319. }
  33320. };
  33321. AssetsManager.prototype._runTask = function (task) {
  33322. var _this = this;
  33323. task.run(this._scene, function () {
  33324. if (_this.onTaskSuccess) {
  33325. _this.onTaskSuccess(task);
  33326. }
  33327. _this._decreaseWaitingTasksCount();
  33328. }, function () {
  33329. if (_this.onTaskError) {
  33330. _this.onTaskError(task);
  33331. }
  33332. _this._decreaseWaitingTasksCount();
  33333. });
  33334. };
  33335. AssetsManager.prototype.reset = function () {
  33336. this._tasks = new Array();
  33337. return this;
  33338. };
  33339. AssetsManager.prototype.load = function () {
  33340. this._waitingTasksCount = this._tasks.length;
  33341. if (this._waitingTasksCount === 0) {
  33342. if (this.onFinish) {
  33343. this.onFinish(this._tasks);
  33344. }
  33345. return this;
  33346. }
  33347. if (this.useDefaultLoadingScreen) {
  33348. this._scene.getEngine().displayLoadingUI();
  33349. }
  33350. for (var index = 0; index < this._tasks.length; index++) {
  33351. var task = this._tasks[index];
  33352. this._runTask(task);
  33353. }
  33354. return this;
  33355. };
  33356. return AssetsManager;
  33357. })();
  33358. BABYLON.AssetsManager = AssetsManager;
  33359. })(BABYLON || (BABYLON = {}));
  33360. var BABYLON;
  33361. (function (BABYLON) {
  33362. var VRCameraMetrics = (function () {
  33363. function VRCameraMetrics() {
  33364. this.compensateDistortion = true;
  33365. }
  33366. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33367. get: function () {
  33368. return this.hResolution / (2 * this.vResolution);
  33369. },
  33370. enumerable: true,
  33371. configurable: true
  33372. });
  33373. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33374. get: function () {
  33375. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33376. },
  33377. enumerable: true,
  33378. configurable: true
  33379. });
  33380. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33381. get: function () {
  33382. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33383. var h = (4 * meters) / this.hScreenSize;
  33384. return BABYLON.Matrix.Translation(h, 0, 0);
  33385. },
  33386. enumerable: true,
  33387. configurable: true
  33388. });
  33389. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33390. get: function () {
  33391. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33392. var h = (4 * meters) / this.hScreenSize;
  33393. return BABYLON.Matrix.Translation(-h, 0, 0);
  33394. },
  33395. enumerable: true,
  33396. configurable: true
  33397. });
  33398. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33399. get: function () {
  33400. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33401. },
  33402. enumerable: true,
  33403. configurable: true
  33404. });
  33405. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33406. get: function () {
  33407. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33408. },
  33409. enumerable: true,
  33410. configurable: true
  33411. });
  33412. VRCameraMetrics.GetDefault = function () {
  33413. var result = new VRCameraMetrics();
  33414. result.hResolution = 1280;
  33415. result.vResolution = 800;
  33416. result.hScreenSize = 0.149759993;
  33417. result.vScreenSize = 0.0935999975;
  33418. result.vScreenCenter = 0.0467999987,
  33419. result.eyeToScreenDistance = 0.0410000011;
  33420. result.lensSeparationDistance = 0.0635000020;
  33421. result.interpupillaryDistance = 0.0640000030;
  33422. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33423. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33424. result.postProcessScaleFactor = 1.714605507808412;
  33425. result.lensCenterOffset = 0.151976421;
  33426. return result;
  33427. };
  33428. return VRCameraMetrics;
  33429. })();
  33430. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33431. })(BABYLON || (BABYLON = {}));
  33432. var BABYLON;
  33433. (function (BABYLON) {
  33434. var VRDeviceOrientationFreeCamera = (function (_super) {
  33435. __extends(VRDeviceOrientationFreeCamera, _super);
  33436. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33437. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33438. _super.call(this, name, position, scene);
  33439. this._alpha = 0;
  33440. this._beta = 0;
  33441. this._gamma = 0;
  33442. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33443. metrics.compensateDistortion = compensateDistortion;
  33444. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33445. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33446. }
  33447. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33448. this._alpha = +evt.alpha | 0;
  33449. this._beta = +evt.beta | 0;
  33450. this._gamma = +evt.gamma | 0;
  33451. if (this._gamma < 0) {
  33452. this._gamma = 90 + this._gamma;
  33453. }
  33454. else {
  33455. // Incline it in the correct angle.
  33456. this._gamma = 270 - this._gamma;
  33457. }
  33458. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33459. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33460. this.rotation.z = this._beta / 180.0 * Math.PI;
  33461. };
  33462. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33463. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33464. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33465. };
  33466. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33467. _super.prototype.detachControl.call(this, element);
  33468. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33469. };
  33470. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33471. return "VRDeviceOrientationFreeCamera";
  33472. };
  33473. return VRDeviceOrientationFreeCamera;
  33474. })(BABYLON.FreeCamera);
  33475. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33476. })(BABYLON || (BABYLON = {}));
  33477. var BABYLON;
  33478. (function (BABYLON) {
  33479. var WebVRFreeCamera = (function (_super) {
  33480. __extends(WebVRFreeCamera, _super);
  33481. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33482. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33483. _super.call(this, name, position, scene);
  33484. this._hmdDevice = null;
  33485. this._sensorDevice = null;
  33486. this._cacheState = null;
  33487. this._cacheQuaternion = new BABYLON.Quaternion();
  33488. this._cacheRotation = BABYLON.Vector3.Zero();
  33489. this._vrEnabled = false;
  33490. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33491. metrics.compensateDistortion = compensateDistortion;
  33492. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33493. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33494. }
  33495. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33496. var size = devices.length;
  33497. var i = 0;
  33498. // Reset devices.
  33499. this._sensorDevice = null;
  33500. this._hmdDevice = null;
  33501. // Search for a HmdDevice.
  33502. while (i < size && this._hmdDevice === null) {
  33503. if (devices[i] instanceof HMDVRDevice) {
  33504. this._hmdDevice = devices[i];
  33505. }
  33506. i++;
  33507. }
  33508. i = 0;
  33509. while (i < size && this._sensorDevice === null) {
  33510. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33511. this._sensorDevice = devices[i];
  33512. }
  33513. i++;
  33514. }
  33515. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33516. };
  33517. WebVRFreeCamera.prototype._checkInputs = function () {
  33518. if (this._vrEnabled) {
  33519. this._cacheState = this._sensorDevice.getState();
  33520. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33521. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33522. this.rotation.x = -this._cacheRotation.z;
  33523. this.rotation.y = -this._cacheRotation.y;
  33524. this.rotation.z = this._cacheRotation.x;
  33525. }
  33526. _super.prototype._checkInputs.call(this);
  33527. };
  33528. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33529. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33530. if (navigator.getVRDevices) {
  33531. navigator.getVRDevices().then(this._getWebVRDevices);
  33532. }
  33533. else if (navigator.mozGetVRDevices) {
  33534. navigator.mozGetVRDevices(this._getWebVRDevices);
  33535. }
  33536. };
  33537. WebVRFreeCamera.prototype.detachControl = function (element) {
  33538. _super.prototype.detachControl.call(this, element);
  33539. this._vrEnabled = false;
  33540. };
  33541. WebVRFreeCamera.prototype.getTypeName = function () {
  33542. return "WebVRFreeCamera";
  33543. };
  33544. return WebVRFreeCamera;
  33545. })(BABYLON.FreeCamera);
  33546. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33547. })(BABYLON || (BABYLON = {}));
  33548. var BABYLON;
  33549. (function (BABYLON) {
  33550. // Standard optimizations
  33551. var SceneOptimization = (function () {
  33552. function SceneOptimization(priority) {
  33553. if (priority === void 0) { priority = 0; }
  33554. this.priority = priority;
  33555. this.apply = function (scene) {
  33556. return true; // Return true if everything that can be done was applied
  33557. };
  33558. }
  33559. return SceneOptimization;
  33560. })();
  33561. BABYLON.SceneOptimization = SceneOptimization;
  33562. var TextureOptimization = (function (_super) {
  33563. __extends(TextureOptimization, _super);
  33564. function TextureOptimization(priority, maximumSize) {
  33565. var _this = this;
  33566. if (priority === void 0) { priority = 0; }
  33567. if (maximumSize === void 0) { maximumSize = 1024; }
  33568. _super.call(this, priority);
  33569. this.priority = priority;
  33570. this.maximumSize = maximumSize;
  33571. this.apply = function (scene) {
  33572. var allDone = true;
  33573. for (var index = 0; index < scene.textures.length; index++) {
  33574. var texture = scene.textures[index];
  33575. if (!texture.canRescale) {
  33576. continue;
  33577. }
  33578. var currentSize = texture.getSize();
  33579. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33580. if (maxDimension > _this.maximumSize) {
  33581. texture.scale(0.5);
  33582. allDone = false;
  33583. }
  33584. }
  33585. return allDone;
  33586. };
  33587. }
  33588. return TextureOptimization;
  33589. })(SceneOptimization);
  33590. BABYLON.TextureOptimization = TextureOptimization;
  33591. var HardwareScalingOptimization = (function (_super) {
  33592. __extends(HardwareScalingOptimization, _super);
  33593. function HardwareScalingOptimization(priority, maximumScale) {
  33594. var _this = this;
  33595. if (priority === void 0) { priority = 0; }
  33596. if (maximumScale === void 0) { maximumScale = 2; }
  33597. _super.call(this, priority);
  33598. this.priority = priority;
  33599. this.maximumScale = maximumScale;
  33600. this._currentScale = 1;
  33601. this.apply = function (scene) {
  33602. _this._currentScale++;
  33603. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33604. return _this._currentScale >= _this.maximumScale;
  33605. };
  33606. }
  33607. return HardwareScalingOptimization;
  33608. })(SceneOptimization);
  33609. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33610. var ShadowsOptimization = (function (_super) {
  33611. __extends(ShadowsOptimization, _super);
  33612. function ShadowsOptimization() {
  33613. _super.apply(this, arguments);
  33614. this.apply = function (scene) {
  33615. scene.shadowsEnabled = false;
  33616. return true;
  33617. };
  33618. }
  33619. return ShadowsOptimization;
  33620. })(SceneOptimization);
  33621. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33622. var PostProcessesOptimization = (function (_super) {
  33623. __extends(PostProcessesOptimization, _super);
  33624. function PostProcessesOptimization() {
  33625. _super.apply(this, arguments);
  33626. this.apply = function (scene) {
  33627. scene.postProcessesEnabled = false;
  33628. return true;
  33629. };
  33630. }
  33631. return PostProcessesOptimization;
  33632. })(SceneOptimization);
  33633. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33634. var LensFlaresOptimization = (function (_super) {
  33635. __extends(LensFlaresOptimization, _super);
  33636. function LensFlaresOptimization() {
  33637. _super.apply(this, arguments);
  33638. this.apply = function (scene) {
  33639. scene.lensFlaresEnabled = false;
  33640. return true;
  33641. };
  33642. }
  33643. return LensFlaresOptimization;
  33644. })(SceneOptimization);
  33645. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33646. var ParticlesOptimization = (function (_super) {
  33647. __extends(ParticlesOptimization, _super);
  33648. function ParticlesOptimization() {
  33649. _super.apply(this, arguments);
  33650. this.apply = function (scene) {
  33651. scene.particlesEnabled = false;
  33652. return true;
  33653. };
  33654. }
  33655. return ParticlesOptimization;
  33656. })(SceneOptimization);
  33657. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33658. var RenderTargetsOptimization = (function (_super) {
  33659. __extends(RenderTargetsOptimization, _super);
  33660. function RenderTargetsOptimization() {
  33661. _super.apply(this, arguments);
  33662. this.apply = function (scene) {
  33663. scene.renderTargetsEnabled = false;
  33664. return true;
  33665. };
  33666. }
  33667. return RenderTargetsOptimization;
  33668. })(SceneOptimization);
  33669. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33670. var MergeMeshesOptimization = (function (_super) {
  33671. __extends(MergeMeshesOptimization, _super);
  33672. function MergeMeshesOptimization() {
  33673. var _this = this;
  33674. _super.apply(this, arguments);
  33675. this._canBeMerged = function (abstractMesh) {
  33676. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33677. return false;
  33678. }
  33679. var mesh = abstractMesh;
  33680. if (!mesh.isVisible || !mesh.isEnabled()) {
  33681. return false;
  33682. }
  33683. if (mesh.instances.length > 0) {
  33684. return false;
  33685. }
  33686. if (mesh.skeleton || mesh.hasLODLevels) {
  33687. return false;
  33688. }
  33689. if (mesh.parent) {
  33690. return false;
  33691. }
  33692. return true;
  33693. };
  33694. this.apply = function (scene, updateSelectionTree) {
  33695. var globalPool = scene.meshes.slice(0);
  33696. var globalLength = globalPool.length;
  33697. for (var index = 0; index < globalLength; index++) {
  33698. var currentPool = new Array();
  33699. var current = globalPool[index];
  33700. // Checks
  33701. if (!_this._canBeMerged(current)) {
  33702. continue;
  33703. }
  33704. currentPool.push(current);
  33705. // Find compatible meshes
  33706. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33707. var otherMesh = globalPool[subIndex];
  33708. if (!_this._canBeMerged(otherMesh)) {
  33709. continue;
  33710. }
  33711. if (otherMesh.material !== current.material) {
  33712. continue;
  33713. }
  33714. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33715. continue;
  33716. }
  33717. currentPool.push(otherMesh);
  33718. globalLength--;
  33719. globalPool.splice(subIndex, 1);
  33720. subIndex--;
  33721. }
  33722. if (currentPool.length < 2) {
  33723. continue;
  33724. }
  33725. // Merge meshes
  33726. BABYLON.Mesh.MergeMeshes(currentPool);
  33727. }
  33728. if (updateSelectionTree != undefined) {
  33729. if (updateSelectionTree) {
  33730. scene.createOrUpdateSelectionOctree();
  33731. }
  33732. }
  33733. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33734. scene.createOrUpdateSelectionOctree();
  33735. }
  33736. return true;
  33737. };
  33738. }
  33739. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33740. get: function () {
  33741. return MergeMeshesOptimization._UpdateSelectionTree;
  33742. },
  33743. set: function (value) {
  33744. MergeMeshesOptimization._UpdateSelectionTree = value;
  33745. },
  33746. enumerable: true,
  33747. configurable: true
  33748. });
  33749. MergeMeshesOptimization._UpdateSelectionTree = false;
  33750. return MergeMeshesOptimization;
  33751. })(SceneOptimization);
  33752. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33753. // Options
  33754. var SceneOptimizerOptions = (function () {
  33755. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33756. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33757. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33758. this.targetFrameRate = targetFrameRate;
  33759. this.trackerDuration = trackerDuration;
  33760. this.optimizations = new Array();
  33761. }
  33762. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33763. var result = new SceneOptimizerOptions(targetFrameRate);
  33764. var priority = 0;
  33765. result.optimizations.push(new MergeMeshesOptimization(priority));
  33766. result.optimizations.push(new ShadowsOptimization(priority));
  33767. result.optimizations.push(new LensFlaresOptimization(priority));
  33768. // Next priority
  33769. priority++;
  33770. result.optimizations.push(new PostProcessesOptimization(priority));
  33771. result.optimizations.push(new ParticlesOptimization(priority));
  33772. // Next priority
  33773. priority++;
  33774. result.optimizations.push(new TextureOptimization(priority, 1024));
  33775. return result;
  33776. };
  33777. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33778. var result = new SceneOptimizerOptions(targetFrameRate);
  33779. var priority = 0;
  33780. result.optimizations.push(new MergeMeshesOptimization(priority));
  33781. result.optimizations.push(new ShadowsOptimization(priority));
  33782. result.optimizations.push(new LensFlaresOptimization(priority));
  33783. // Next priority
  33784. priority++;
  33785. result.optimizations.push(new PostProcessesOptimization(priority));
  33786. result.optimizations.push(new ParticlesOptimization(priority));
  33787. // Next priority
  33788. priority++;
  33789. result.optimizations.push(new TextureOptimization(priority, 512));
  33790. // Next priority
  33791. priority++;
  33792. result.optimizations.push(new RenderTargetsOptimization(priority));
  33793. // Next priority
  33794. priority++;
  33795. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33796. return result;
  33797. };
  33798. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33799. var result = new SceneOptimizerOptions(targetFrameRate);
  33800. var priority = 0;
  33801. result.optimizations.push(new MergeMeshesOptimization(priority));
  33802. result.optimizations.push(new ShadowsOptimization(priority));
  33803. result.optimizations.push(new LensFlaresOptimization(priority));
  33804. // Next priority
  33805. priority++;
  33806. result.optimizations.push(new PostProcessesOptimization(priority));
  33807. result.optimizations.push(new ParticlesOptimization(priority));
  33808. // Next priority
  33809. priority++;
  33810. result.optimizations.push(new TextureOptimization(priority, 256));
  33811. // Next priority
  33812. priority++;
  33813. result.optimizations.push(new RenderTargetsOptimization(priority));
  33814. // Next priority
  33815. priority++;
  33816. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33817. return result;
  33818. };
  33819. return SceneOptimizerOptions;
  33820. })();
  33821. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33822. // Scene optimizer tool
  33823. var SceneOptimizer = (function () {
  33824. function SceneOptimizer() {
  33825. }
  33826. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33827. // TODO: add an epsilon
  33828. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33829. if (onSuccess) {
  33830. onSuccess();
  33831. }
  33832. return;
  33833. }
  33834. // Apply current level of optimizations
  33835. var allDone = true;
  33836. var noOptimizationApplied = true;
  33837. for (var index = 0; index < options.optimizations.length; index++) {
  33838. var optimization = options.optimizations[index];
  33839. if (optimization.priority === currentPriorityLevel) {
  33840. noOptimizationApplied = false;
  33841. allDone = allDone && optimization.apply(scene);
  33842. }
  33843. }
  33844. // If no optimization was applied, this is a failure :(
  33845. if (noOptimizationApplied) {
  33846. if (onFailure) {
  33847. onFailure();
  33848. }
  33849. return;
  33850. }
  33851. // If all optimizations were done, move to next level
  33852. if (allDone) {
  33853. currentPriorityLevel++;
  33854. }
  33855. // Let's the system running for a specific amount of time before checking FPS
  33856. scene.executeWhenReady(function () {
  33857. setTimeout(function () {
  33858. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33859. }, options.trackerDuration);
  33860. });
  33861. };
  33862. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33863. if (!options) {
  33864. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33865. }
  33866. // Let's the system running for a specific amount of time before checking FPS
  33867. scene.executeWhenReady(function () {
  33868. setTimeout(function () {
  33869. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33870. }, options.trackerDuration);
  33871. });
  33872. };
  33873. return SceneOptimizer;
  33874. })();
  33875. BABYLON.SceneOptimizer = SceneOptimizer;
  33876. })(BABYLON || (BABYLON = {}));
  33877. var BABYLON;
  33878. (function (BABYLON) {
  33879. var Internals;
  33880. (function (Internals) {
  33881. var MeshLODLevel = (function () {
  33882. function MeshLODLevel(distance, mesh) {
  33883. this.distance = distance;
  33884. this.mesh = mesh;
  33885. }
  33886. return MeshLODLevel;
  33887. })();
  33888. Internals.MeshLODLevel = MeshLODLevel;
  33889. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33890. })(BABYLON || (BABYLON = {}));
  33891. var BABYLON;
  33892. (function (BABYLON) {
  33893. var RawTexture = (function (_super) {
  33894. __extends(RawTexture, _super);
  33895. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33896. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33897. if (invertY === void 0) { invertY = false; }
  33898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33899. _super.call(this, null, scene, !generateMipMaps, invertY);
  33900. this.format = format;
  33901. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33902. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33903. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33904. }
  33905. RawTexture.prototype.update = function (data) {
  33906. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33907. };
  33908. // Statics
  33909. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33910. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33911. if (invertY === void 0) { invertY = false; }
  33912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33913. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33914. };
  33915. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33916. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33917. if (invertY === void 0) { invertY = false; }
  33918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33919. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33920. };
  33921. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33922. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33923. if (invertY === void 0) { invertY = false; }
  33924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33925. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33926. };
  33927. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33928. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33929. if (invertY === void 0) { invertY = false; }
  33930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33931. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33932. };
  33933. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33934. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33935. if (invertY === void 0) { invertY = false; }
  33936. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33937. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33938. };
  33939. return RawTexture;
  33940. })(BABYLON.Texture);
  33941. BABYLON.RawTexture = RawTexture;
  33942. })(BABYLON || (BABYLON = {}));
  33943. var BABYLON;
  33944. (function (BABYLON) {
  33945. var IndexedVector2 = (function (_super) {
  33946. __extends(IndexedVector2, _super);
  33947. function IndexedVector2(original, index) {
  33948. _super.call(this, original.x, original.y);
  33949. this.index = index;
  33950. }
  33951. return IndexedVector2;
  33952. })(BABYLON.Vector2);
  33953. var PolygonPoints = (function () {
  33954. function PolygonPoints() {
  33955. this.elements = new Array();
  33956. }
  33957. PolygonPoints.prototype.add = function (originalPoints) {
  33958. var _this = this;
  33959. var result = new Array();
  33960. originalPoints.forEach(function (point) {
  33961. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33962. var newPoint = new IndexedVector2(point, _this.elements.length);
  33963. result.push(newPoint);
  33964. _this.elements.push(newPoint);
  33965. }
  33966. });
  33967. return result;
  33968. };
  33969. PolygonPoints.prototype.computeBounds = function () {
  33970. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33971. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33972. this.elements.forEach(function (point) {
  33973. // x
  33974. if (point.x < lmin.x) {
  33975. lmin.x = point.x;
  33976. }
  33977. else if (point.x > lmax.x) {
  33978. lmax.x = point.x;
  33979. }
  33980. // y
  33981. if (point.y < lmin.y) {
  33982. lmin.y = point.y;
  33983. }
  33984. else if (point.y > lmax.y) {
  33985. lmax.y = point.y;
  33986. }
  33987. });
  33988. return {
  33989. min: lmin,
  33990. max: lmax,
  33991. width: lmax.x - lmin.x,
  33992. height: lmax.y - lmin.y
  33993. };
  33994. };
  33995. return PolygonPoints;
  33996. })();
  33997. var Polygon = (function () {
  33998. function Polygon() {
  33999. }
  34000. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34001. return [
  34002. new BABYLON.Vector2(xmin, ymin),
  34003. new BABYLON.Vector2(xmax, ymin),
  34004. new BABYLON.Vector2(xmax, ymax),
  34005. new BABYLON.Vector2(xmin, ymax)
  34006. ];
  34007. };
  34008. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34009. if (cx === void 0) { cx = 0; }
  34010. if (cy === void 0) { cy = 0; }
  34011. if (numberOfSides === void 0) { numberOfSides = 32; }
  34012. var result = new Array();
  34013. var angle = 0;
  34014. var increment = (Math.PI * 2) / numberOfSides;
  34015. for (var i = 0; i < numberOfSides; i++) {
  34016. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34017. angle -= increment;
  34018. }
  34019. return result;
  34020. };
  34021. Polygon.Parse = function (input) {
  34022. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34023. var i, result = [];
  34024. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34025. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34026. }
  34027. return result;
  34028. };
  34029. Polygon.StartingAt = function (x, y) {
  34030. return BABYLON.Path2.StartingAt(x, y);
  34031. };
  34032. return Polygon;
  34033. })();
  34034. BABYLON.Polygon = Polygon;
  34035. var PolygonMeshBuilder = (function () {
  34036. function PolygonMeshBuilder(name, contours, scene) {
  34037. this._points = new PolygonPoints();
  34038. this._outlinepoints = new PolygonPoints();
  34039. this._holes = [];
  34040. if (!("poly2tri" in window)) {
  34041. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34042. }
  34043. this._name = name;
  34044. this._scene = scene;
  34045. var points;
  34046. if (contours instanceof BABYLON.Path2) {
  34047. points = contours.getPoints();
  34048. }
  34049. else {
  34050. points = contours;
  34051. }
  34052. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34053. this._outlinepoints.add(points);
  34054. }
  34055. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34056. this._swctx.addHole(this._points.add(hole));
  34057. var holepoints = new PolygonPoints();
  34058. holepoints.add(hole);
  34059. this._holes.push(holepoints);
  34060. return this;
  34061. };
  34062. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34063. var _this = this;
  34064. if (updatable === void 0) { updatable = false; }
  34065. var result = new BABYLON.Mesh(this._name, this._scene);
  34066. var normals = [];
  34067. var positions = [];
  34068. var uvs = [];
  34069. var bounds = this._points.computeBounds();
  34070. this._points.elements.forEach(function (p) {
  34071. normals.push(0, 1.0, 0);
  34072. positions.push(p.x, 0, p.y);
  34073. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34074. });
  34075. var indices = [];
  34076. this._swctx.triangulate();
  34077. this._swctx.getTriangles().forEach(function (triangle) {
  34078. triangle.getPoints().forEach(function (point) {
  34079. indices.push(point.index);
  34080. });
  34081. });
  34082. if (depth > 0) {
  34083. var positionscount = (positions.length / 3); //get the current pointcount
  34084. this._points.elements.forEach(function (p) {
  34085. normals.push(0, -1.0, 0);
  34086. positions.push(p.x, -depth, p.y);
  34087. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34088. });
  34089. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34090. var p2;
  34091. var poscounter = 0;
  34092. this._swctx.getTriangles().forEach(function (triangle) {
  34093. triangle.getPoints().forEach(function (point) {
  34094. switch (poscounter) {
  34095. case 0:
  34096. p1 = point;
  34097. break;
  34098. case 1:
  34099. p2 = point;
  34100. break;
  34101. case 2:
  34102. indices.push(point.index + positionscount);
  34103. indices.push(p2.index + positionscount);
  34104. indices.push(p1.index + positionscount);
  34105. poscounter = -1;
  34106. break;
  34107. }
  34108. poscounter++;
  34109. //indices.push((<IndexedVector2>point).index + positionscount);
  34110. });
  34111. });
  34112. //Add the sides
  34113. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34114. this._holes.forEach(function (hole) {
  34115. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34116. });
  34117. }
  34118. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34119. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34120. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34121. result.setIndices(indices);
  34122. return result;
  34123. };
  34124. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34125. var StartIndex = positions.length / 3;
  34126. var ulength = 0;
  34127. for (var i = 0; i < points.elements.length; i++) {
  34128. var p = points.elements[i];
  34129. var p1;
  34130. if ((i + 1) > points.elements.length - 1) {
  34131. p1 = points.elements[0];
  34132. }
  34133. else {
  34134. p1 = points.elements[i + 1];
  34135. }
  34136. positions.push(p.x, 0, p.y);
  34137. positions.push(p.x, -depth, p.y);
  34138. positions.push(p1.x, 0, p1.y);
  34139. positions.push(p1.x, -depth, p1.y);
  34140. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34141. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34142. var v3 = v2.subtract(v1);
  34143. var v4 = new BABYLON.Vector3(0, 1, 0);
  34144. var vn = BABYLON.Vector3.Cross(v3, v4);
  34145. vn = vn.normalize();
  34146. uvs.push(ulength / bounds.width, 0);
  34147. uvs.push(ulength / bounds.width, 1);
  34148. ulength += v3.length();
  34149. uvs.push((ulength / bounds.width), 0);
  34150. uvs.push((ulength / bounds.width), 1);
  34151. if (!flip) {
  34152. normals.push(-vn.x, -vn.y, -vn.z);
  34153. normals.push(-vn.x, -vn.y, -vn.z);
  34154. normals.push(-vn.x, -vn.y, -vn.z);
  34155. normals.push(-vn.x, -vn.y, -vn.z);
  34156. indices.push(StartIndex);
  34157. indices.push(StartIndex + 1);
  34158. indices.push(StartIndex + 2);
  34159. indices.push(StartIndex + 1);
  34160. indices.push(StartIndex + 3);
  34161. indices.push(StartIndex + 2);
  34162. }
  34163. else {
  34164. normals.push(vn.x, vn.y, vn.z);
  34165. normals.push(vn.x, vn.y, vn.z);
  34166. normals.push(vn.x, vn.y, vn.z);
  34167. normals.push(vn.x, vn.y, vn.z);
  34168. indices.push(StartIndex);
  34169. indices.push(StartIndex + 2);
  34170. indices.push(StartIndex + 1);
  34171. indices.push(StartIndex + 1);
  34172. indices.push(StartIndex + 2);
  34173. indices.push(StartIndex + 3);
  34174. }
  34175. StartIndex += 4;
  34176. }
  34177. ;
  34178. };
  34179. return PolygonMeshBuilder;
  34180. })();
  34181. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34182. })(BABYLON || (BABYLON = {}));
  34183. var BABYLON;
  34184. (function (BABYLON) {
  34185. var Octree = (function () {
  34186. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34187. if (maxDepth === void 0) { maxDepth = 2; }
  34188. this.maxDepth = maxDepth;
  34189. this.dynamicContent = new Array();
  34190. this._maxBlockCapacity = maxBlockCapacity || 64;
  34191. this._selectionContent = new BABYLON.SmartArray(1024);
  34192. this._creationFunc = creationFunc;
  34193. }
  34194. // Methods
  34195. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34196. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34197. };
  34198. Octree.prototype.addMesh = function (entry) {
  34199. for (var index = 0; index < this.blocks.length; index++) {
  34200. var block = this.blocks[index];
  34201. block.addEntry(entry);
  34202. }
  34203. };
  34204. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34205. this._selectionContent.reset();
  34206. for (var index = 0; index < this.blocks.length; index++) {
  34207. var block = this.blocks[index];
  34208. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34209. }
  34210. if (allowDuplicate) {
  34211. this._selectionContent.concat(this.dynamicContent);
  34212. }
  34213. else {
  34214. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34215. }
  34216. return this._selectionContent;
  34217. };
  34218. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34219. this._selectionContent.reset();
  34220. for (var index = 0; index < this.blocks.length; index++) {
  34221. var block = this.blocks[index];
  34222. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34223. }
  34224. if (allowDuplicate) {
  34225. this._selectionContent.concat(this.dynamicContent);
  34226. }
  34227. else {
  34228. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34229. }
  34230. return this._selectionContent;
  34231. };
  34232. Octree.prototype.intersectsRay = function (ray) {
  34233. this._selectionContent.reset();
  34234. for (var index = 0; index < this.blocks.length; index++) {
  34235. var block = this.blocks[index];
  34236. block.intersectsRay(ray, this._selectionContent);
  34237. }
  34238. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34239. return this._selectionContent;
  34240. };
  34241. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34242. target.blocks = new Array();
  34243. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34244. // Segmenting space
  34245. for (var x = 0; x < 2; x++) {
  34246. for (var y = 0; y < 2; y++) {
  34247. for (var z = 0; z < 2; z++) {
  34248. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34249. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34250. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34251. block.addEntries(entries);
  34252. target.blocks.push(block);
  34253. }
  34254. }
  34255. }
  34256. };
  34257. Octree.CreationFuncForMeshes = function (entry, block) {
  34258. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34259. block.entries.push(entry);
  34260. }
  34261. };
  34262. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34263. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34264. block.entries.push(entry);
  34265. }
  34266. };
  34267. return Octree;
  34268. })();
  34269. BABYLON.Octree = Octree;
  34270. })(BABYLON || (BABYLON = {}));
  34271. var BABYLON;
  34272. (function (BABYLON) {
  34273. var OctreeBlock = (function () {
  34274. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34275. this.entries = new Array();
  34276. this._boundingVectors = new Array();
  34277. this._capacity = capacity;
  34278. this._depth = depth;
  34279. this._maxDepth = maxDepth;
  34280. this._creationFunc = creationFunc;
  34281. this._minPoint = minPoint;
  34282. this._maxPoint = maxPoint;
  34283. this._boundingVectors.push(minPoint.clone());
  34284. this._boundingVectors.push(maxPoint.clone());
  34285. this._boundingVectors.push(minPoint.clone());
  34286. this._boundingVectors[2].x = maxPoint.x;
  34287. this._boundingVectors.push(minPoint.clone());
  34288. this._boundingVectors[3].y = maxPoint.y;
  34289. this._boundingVectors.push(minPoint.clone());
  34290. this._boundingVectors[4].z = maxPoint.z;
  34291. this._boundingVectors.push(maxPoint.clone());
  34292. this._boundingVectors[5].z = minPoint.z;
  34293. this._boundingVectors.push(maxPoint.clone());
  34294. this._boundingVectors[6].x = minPoint.x;
  34295. this._boundingVectors.push(maxPoint.clone());
  34296. this._boundingVectors[7].y = minPoint.y;
  34297. }
  34298. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34299. // Property
  34300. get: function () {
  34301. return this._capacity;
  34302. },
  34303. enumerable: true,
  34304. configurable: true
  34305. });
  34306. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34307. get: function () {
  34308. return this._minPoint;
  34309. },
  34310. enumerable: true,
  34311. configurable: true
  34312. });
  34313. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34314. get: function () {
  34315. return this._maxPoint;
  34316. },
  34317. enumerable: true,
  34318. configurable: true
  34319. });
  34320. // Methods
  34321. OctreeBlock.prototype.addEntry = function (entry) {
  34322. if (this.blocks) {
  34323. for (var index = 0; index < this.blocks.length; index++) {
  34324. var block = this.blocks[index];
  34325. block.addEntry(entry);
  34326. }
  34327. return;
  34328. }
  34329. this._creationFunc(entry, this);
  34330. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34331. this.createInnerBlocks();
  34332. }
  34333. };
  34334. OctreeBlock.prototype.addEntries = function (entries) {
  34335. for (var index = 0; index < entries.length; index++) {
  34336. var mesh = entries[index];
  34337. this.addEntry(mesh);
  34338. }
  34339. };
  34340. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34341. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34342. if (this.blocks) {
  34343. for (var index = 0; index < this.blocks.length; index++) {
  34344. var block = this.blocks[index];
  34345. block.select(frustumPlanes, selection, allowDuplicate);
  34346. }
  34347. return;
  34348. }
  34349. if (allowDuplicate) {
  34350. selection.concat(this.entries);
  34351. }
  34352. else {
  34353. selection.concatWithNoDuplicate(this.entries);
  34354. }
  34355. }
  34356. };
  34357. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34358. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34359. if (this.blocks) {
  34360. for (var index = 0; index < this.blocks.length; index++) {
  34361. var block = this.blocks[index];
  34362. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34363. }
  34364. return;
  34365. }
  34366. if (allowDuplicate) {
  34367. selection.concat(this.entries);
  34368. }
  34369. else {
  34370. selection.concatWithNoDuplicate(this.entries);
  34371. }
  34372. }
  34373. };
  34374. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34375. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34376. if (this.blocks) {
  34377. for (var index = 0; index < this.blocks.length; index++) {
  34378. var block = this.blocks[index];
  34379. block.intersectsRay(ray, selection);
  34380. }
  34381. return;
  34382. }
  34383. selection.concatWithNoDuplicate(this.entries);
  34384. }
  34385. };
  34386. OctreeBlock.prototype.createInnerBlocks = function () {
  34387. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34388. };
  34389. return OctreeBlock;
  34390. })();
  34391. BABYLON.OctreeBlock = OctreeBlock;
  34392. })(BABYLON || (BABYLON = {}));
  34393. var BABYLON;
  34394. (function (BABYLON) {
  34395. var BlurPostProcess = (function (_super) {
  34396. __extends(BlurPostProcess, _super);
  34397. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34398. var _this = this;
  34399. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34400. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34401. this.direction = direction;
  34402. this.blurWidth = blurWidth;
  34403. this.onApply = function (effect) {
  34404. effect.setFloat2("screenSize", _this.width, _this.height);
  34405. effect.setVector2("direction", _this.direction);
  34406. effect.setFloat("blurWidth", _this.blurWidth);
  34407. };
  34408. }
  34409. return BlurPostProcess;
  34410. })(BABYLON.PostProcess);
  34411. BABYLON.BlurPostProcess = BlurPostProcess;
  34412. })(BABYLON || (BABYLON = {}));
  34413. var BABYLON;
  34414. (function (BABYLON) {
  34415. var RefractionPostProcess = (function (_super) {
  34416. __extends(RefractionPostProcess, _super);
  34417. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34418. var _this = this;
  34419. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34420. this.color = color;
  34421. this.depth = depth;
  34422. this.colorLevel = colorLevel;
  34423. this.onActivate = function (cam) {
  34424. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34425. };
  34426. this.onApply = function (effect) {
  34427. effect.setColor3("baseColor", _this.color);
  34428. effect.setFloat("depth", _this.depth);
  34429. effect.setFloat("colorLevel", _this.colorLevel);
  34430. effect.setTexture("refractionSampler", _this._refRexture);
  34431. };
  34432. }
  34433. // Methods
  34434. RefractionPostProcess.prototype.dispose = function (camera) {
  34435. if (this._refRexture) {
  34436. this._refRexture.dispose();
  34437. }
  34438. _super.prototype.dispose.call(this, camera);
  34439. };
  34440. return RefractionPostProcess;
  34441. })(BABYLON.PostProcess);
  34442. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34443. })(BABYLON || (BABYLON = {}));
  34444. var BABYLON;
  34445. (function (BABYLON) {
  34446. var BlackAndWhitePostProcess = (function (_super) {
  34447. __extends(BlackAndWhitePostProcess, _super);
  34448. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34449. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34450. }
  34451. return BlackAndWhitePostProcess;
  34452. })(BABYLON.PostProcess);
  34453. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34454. })(BABYLON || (BABYLON = {}));
  34455. var BABYLON;
  34456. (function (BABYLON) {
  34457. var ConvolutionPostProcess = (function (_super) {
  34458. __extends(ConvolutionPostProcess, _super);
  34459. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34460. var _this = this;
  34461. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34462. this.kernel = kernel;
  34463. this.onApply = function (effect) {
  34464. effect.setFloat2("screenSize", _this.width, _this.height);
  34465. effect.setArray("kernel", _this.kernel);
  34466. };
  34467. }
  34468. // Statics
  34469. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34470. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34471. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34472. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34473. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34474. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34475. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34476. return ConvolutionPostProcess;
  34477. })(BABYLON.PostProcess);
  34478. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34479. })(BABYLON || (BABYLON = {}));
  34480. var BABYLON;
  34481. (function (BABYLON) {
  34482. var FilterPostProcess = (function (_super) {
  34483. __extends(FilterPostProcess, _super);
  34484. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34485. var _this = this;
  34486. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34487. this.kernelMatrix = kernelMatrix;
  34488. this.onApply = function (effect) {
  34489. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34490. };
  34491. }
  34492. return FilterPostProcess;
  34493. })(BABYLON.PostProcess);
  34494. BABYLON.FilterPostProcess = FilterPostProcess;
  34495. })(BABYLON || (BABYLON = {}));
  34496. var BABYLON;
  34497. (function (BABYLON) {
  34498. var FxaaPostProcess = (function (_super) {
  34499. __extends(FxaaPostProcess, _super);
  34500. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34501. var _this = this;
  34502. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34503. this.onSizeChanged = function () {
  34504. _this.texelWidth = 1.0 / _this.width;
  34505. _this.texelHeight = 1.0 / _this.height;
  34506. };
  34507. this.onApply = function (effect) {
  34508. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34509. };
  34510. }
  34511. return FxaaPostProcess;
  34512. })(BABYLON.PostProcess);
  34513. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34514. })(BABYLON || (BABYLON = {}));
  34515. var BABYLON;
  34516. (function (BABYLON) {
  34517. var StereoscopicInterlacePostProcess = (function (_super) {
  34518. __extends(StereoscopicInterlacePostProcess, _super);
  34519. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34520. var _this = this;
  34521. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34522. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34523. this.onSizeChanged = function () {
  34524. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34525. };
  34526. this.onApply = function (effect) {
  34527. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34528. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34529. };
  34530. }
  34531. return StereoscopicInterlacePostProcess;
  34532. })(BABYLON.PostProcess);
  34533. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34534. })(BABYLON || (BABYLON = {}));
  34535. var BABYLON;
  34536. (function (BABYLON) {
  34537. var LensFlare = (function () {
  34538. function LensFlare(size, position, color, imgUrl, system) {
  34539. this.size = size;
  34540. this.position = position;
  34541. this.dispose = function () {
  34542. if (this.texture) {
  34543. this.texture.dispose();
  34544. }
  34545. // Remove from scene
  34546. var index = this._system.lensFlares.indexOf(this);
  34547. this._system.lensFlares.splice(index, 1);
  34548. };
  34549. this.color = color || new BABYLON.Color3(1, 1, 1);
  34550. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34551. this._system = system;
  34552. system.lensFlares.push(this);
  34553. }
  34554. return LensFlare;
  34555. })();
  34556. BABYLON.LensFlare = LensFlare;
  34557. })(BABYLON || (BABYLON = {}));
  34558. var BABYLON;
  34559. (function (BABYLON) {
  34560. var LensFlareSystem = (function () {
  34561. function LensFlareSystem(name, emitter, scene) {
  34562. this.name = name;
  34563. this.lensFlares = new Array();
  34564. this.borderLimit = 300;
  34565. this.layerMask = 0x0FFFFFFF;
  34566. this._vertexDeclaration = [2];
  34567. this._vertexStrideSize = 2 * 4;
  34568. this._isEnabled = true;
  34569. this._scene = scene;
  34570. this._emitter = emitter;
  34571. scene.lensFlareSystems.push(this);
  34572. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34573. // VBO
  34574. var vertices = [];
  34575. vertices.push(1, 1);
  34576. vertices.push(-1, 1);
  34577. vertices.push(-1, -1);
  34578. vertices.push(1, -1);
  34579. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34580. // Indices
  34581. var indices = [];
  34582. indices.push(0);
  34583. indices.push(1);
  34584. indices.push(2);
  34585. indices.push(0);
  34586. indices.push(2);
  34587. indices.push(3);
  34588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34589. // Effects
  34590. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34591. }
  34592. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34593. get: function () {
  34594. return this._isEnabled;
  34595. },
  34596. set: function (value) {
  34597. this._isEnabled = value;
  34598. },
  34599. enumerable: true,
  34600. configurable: true
  34601. });
  34602. LensFlareSystem.prototype.getScene = function () {
  34603. return this._scene;
  34604. };
  34605. LensFlareSystem.prototype.getEmitter = function () {
  34606. return this._emitter;
  34607. };
  34608. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34609. this._emitter = newEmitter;
  34610. };
  34611. LensFlareSystem.prototype.getEmitterPosition = function () {
  34612. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34613. };
  34614. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34615. var position = this.getEmitterPosition();
  34616. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34617. this._positionX = position.x;
  34618. this._positionY = position.y;
  34619. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34620. if (position.z > 0) {
  34621. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34622. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34623. return true;
  34624. }
  34625. }
  34626. return false;
  34627. };
  34628. LensFlareSystem.prototype._isVisible = function () {
  34629. if (!this._isEnabled) {
  34630. return false;
  34631. }
  34632. var emitterPosition = this.getEmitterPosition();
  34633. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34634. var distance = direction.length();
  34635. direction.normalize();
  34636. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34637. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34638. return !pickInfo.hit || pickInfo.distance > distance;
  34639. };
  34640. LensFlareSystem.prototype.render = function () {
  34641. if (!this._effect.isReady())
  34642. return false;
  34643. var engine = this._scene.getEngine();
  34644. var viewport = this._scene.activeCamera.viewport;
  34645. var globalViewport = viewport.toScreenGlobal(engine);
  34646. // Position
  34647. if (!this.computeEffectivePosition(globalViewport)) {
  34648. return false;
  34649. }
  34650. // Visibility
  34651. if (!this._isVisible()) {
  34652. return false;
  34653. }
  34654. // Intensity
  34655. var awayX;
  34656. var awayY;
  34657. if (this._positionX < this.borderLimit + globalViewport.x) {
  34658. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34659. }
  34660. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34661. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34662. }
  34663. else {
  34664. awayX = 0;
  34665. }
  34666. if (this._positionY < this.borderLimit + globalViewport.y) {
  34667. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34668. }
  34669. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34670. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34671. }
  34672. else {
  34673. awayY = 0;
  34674. }
  34675. var away = (awayX > awayY) ? awayX : awayY;
  34676. if (away > this.borderLimit) {
  34677. away = this.borderLimit;
  34678. }
  34679. var intensity = 1.0 - (away / this.borderLimit);
  34680. if (intensity < 0) {
  34681. return false;
  34682. }
  34683. if (intensity > 1.0) {
  34684. intensity = 1.0;
  34685. }
  34686. // Position
  34687. var centerX = globalViewport.x + globalViewport.width / 2;
  34688. var centerY = globalViewport.y + globalViewport.height / 2;
  34689. var distX = centerX - this._positionX;
  34690. var distY = centerY - this._positionY;
  34691. // Effects
  34692. engine.enableEffect(this._effect);
  34693. engine.setState(false);
  34694. engine.setDepthBuffer(false);
  34695. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34696. // VBOs
  34697. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34698. // Flares
  34699. for (var index = 0; index < this.lensFlares.length; index++) {
  34700. var flare = this.lensFlares[index];
  34701. var x = centerX - (distX * flare.position);
  34702. var y = centerY - (distY * flare.position);
  34703. var cw = flare.size;
  34704. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34705. var cx = 2 * (x / globalViewport.width) - 1.0;
  34706. var cy = 1.0 - 2 * (y / globalViewport.height);
  34707. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34708. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34709. // Texture
  34710. this._effect.setTexture("textureSampler", flare.texture);
  34711. // Color
  34712. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34713. // Draw order
  34714. engine.draw(true, 0, 6);
  34715. }
  34716. engine.setDepthBuffer(true);
  34717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34718. return true;
  34719. };
  34720. LensFlareSystem.prototype.dispose = function () {
  34721. if (this._vertexBuffer) {
  34722. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34723. this._vertexBuffer = null;
  34724. }
  34725. if (this._indexBuffer) {
  34726. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34727. this._indexBuffer = null;
  34728. }
  34729. while (this.lensFlares.length) {
  34730. this.lensFlares[0].dispose();
  34731. }
  34732. // Remove from scene
  34733. var index = this._scene.lensFlareSystems.indexOf(this);
  34734. this._scene.lensFlareSystems.splice(index, 1);
  34735. };
  34736. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34737. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34738. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34739. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34740. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34741. var parsedFlare = parsedLensFlareSystem.flares[index];
  34742. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34743. }
  34744. return lensFlareSystem;
  34745. };
  34746. LensFlareSystem.prototype.serialize = function () {
  34747. var serializationObject = {};
  34748. serializationObject.emitterId = this.getEmitter().id;
  34749. serializationObject.borderLimit = this.borderLimit;
  34750. serializationObject.flares = [];
  34751. for (var index = 0; index < this.lensFlares.length; index++) {
  34752. var flare = this.lensFlares[index];
  34753. serializationObject.flares.push({
  34754. size: flare.size,
  34755. position: flare.position,
  34756. color: flare.color.asArray(),
  34757. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34758. });
  34759. }
  34760. return serializationObject;
  34761. };
  34762. return LensFlareSystem;
  34763. })();
  34764. BABYLON.LensFlareSystem = LensFlareSystem;
  34765. })(BABYLON || (BABYLON = {}));
  34766. var BABYLON;
  34767. (function (BABYLON) {
  34768. // We're mainly based on the logic defined into the FreeCamera code
  34769. var DeviceOrientationCamera = (function (_super) {
  34770. __extends(DeviceOrientationCamera, _super);
  34771. function DeviceOrientationCamera(name, position, scene) {
  34772. var _this = this;
  34773. _super.call(this, name, position, scene);
  34774. this._offsetX = null;
  34775. this._offsetY = null;
  34776. this._orientationGamma = 0;
  34777. this._orientationBeta = 0;
  34778. this._initialOrientationGamma = 0;
  34779. this._initialOrientationBeta = 0;
  34780. this.angularSensibility = 10000.0;
  34781. this.moveSensibility = 50.0;
  34782. window.addEventListener("resize", function () {
  34783. _this._initialOrientationGamma = null;
  34784. }, false);
  34785. }
  34786. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34787. var _this = this;
  34788. if (this._attachedCanvas) {
  34789. return;
  34790. }
  34791. this._attachedCanvas = canvas;
  34792. if (!this._orientationChanged) {
  34793. this._orientationChanged = function (evt) {
  34794. if (!_this._initialOrientationGamma) {
  34795. _this._initialOrientationGamma = evt.gamma;
  34796. _this._initialOrientationBeta = evt.beta;
  34797. }
  34798. _this._orientationGamma = evt.gamma;
  34799. _this._orientationBeta = evt.beta;
  34800. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34801. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34802. };
  34803. }
  34804. window.addEventListener("deviceorientation", this._orientationChanged);
  34805. };
  34806. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34807. if (this._attachedCanvas !== canvas) {
  34808. return;
  34809. }
  34810. window.removeEventListener("deviceorientation", this._orientationChanged);
  34811. this._attachedCanvas = null;
  34812. this._orientationGamma = 0;
  34813. this._orientationBeta = 0;
  34814. this._initialOrientationGamma = 0;
  34815. this._initialOrientationBeta = 0;
  34816. };
  34817. DeviceOrientationCamera.prototype._checkInputs = function () {
  34818. if (!this._offsetX) {
  34819. return;
  34820. }
  34821. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34822. var speed = this._computeLocalCameraSpeed();
  34823. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34824. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34825. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34826. _super.prototype._checkInputs.call(this);
  34827. };
  34828. DeviceOrientationCamera.prototype.getTypeName = function () {
  34829. return "DeviceOrientationCamera";
  34830. };
  34831. __decorate([
  34832. BABYLON.serialize()
  34833. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  34834. __decorate([
  34835. BABYLON.serialize()
  34836. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  34837. return DeviceOrientationCamera;
  34838. })(BABYLON.FreeCamera);
  34839. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34840. })(BABYLON || (BABYLON = {}));
  34841. var BABYLON;
  34842. (function (BABYLON) {
  34843. var Analyser = (function () {
  34844. function Analyser(scene) {
  34845. this.SMOOTHING = 0.75;
  34846. this.FFT_SIZE = 512;
  34847. this.BARGRAPHAMPLITUDE = 256;
  34848. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34849. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34850. this._scene = scene;
  34851. this._audioEngine = BABYLON.Engine.audioEngine;
  34852. if (this._audioEngine.canUseWebAudio) {
  34853. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34854. this._webAudioAnalyser.minDecibels = -140;
  34855. this._webAudioAnalyser.maxDecibels = 0;
  34856. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34857. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34858. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34859. }
  34860. }
  34861. Analyser.prototype.getFrequencyBinCount = function () {
  34862. if (this._audioEngine.canUseWebAudio) {
  34863. return this._webAudioAnalyser.frequencyBinCount;
  34864. }
  34865. else {
  34866. return 0;
  34867. }
  34868. };
  34869. Analyser.prototype.getByteFrequencyData = function () {
  34870. if (this._audioEngine.canUseWebAudio) {
  34871. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34872. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34873. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34874. }
  34875. return this._byteFreqs;
  34876. };
  34877. Analyser.prototype.getByteTimeDomainData = function () {
  34878. if (this._audioEngine.canUseWebAudio) {
  34879. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34880. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34881. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34882. }
  34883. return this._byteTime;
  34884. };
  34885. Analyser.prototype.getFloatFrequencyData = function () {
  34886. if (this._audioEngine.canUseWebAudio) {
  34887. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34888. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34889. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34890. }
  34891. return this._floatFreqs;
  34892. };
  34893. Analyser.prototype.drawDebugCanvas = function () {
  34894. var _this = this;
  34895. if (this._audioEngine.canUseWebAudio) {
  34896. if (!this._debugCanvas) {
  34897. this._debugCanvas = document.createElement("canvas");
  34898. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34899. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34900. this._debugCanvas.style.position = "absolute";
  34901. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34902. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34903. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34904. document.body.appendChild(this._debugCanvas);
  34905. this._registerFunc = function () {
  34906. _this.drawDebugCanvas();
  34907. };
  34908. this._scene.registerBeforeRender(this._registerFunc);
  34909. }
  34910. if (this._registerFunc) {
  34911. var workingArray = this.getByteFrequencyData();
  34912. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34913. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34914. // Draw the frequency domain chart.
  34915. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34916. var value = workingArray[i];
  34917. var percent = value / this.BARGRAPHAMPLITUDE;
  34918. var height = this.DEBUGCANVASSIZE.height * percent;
  34919. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34920. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34921. var hue = i / this.getFrequencyBinCount() * 360;
  34922. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34923. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34924. }
  34925. }
  34926. }
  34927. };
  34928. Analyser.prototype.stopDebugCanvas = function () {
  34929. if (this._debugCanvas) {
  34930. this._scene.unregisterBeforeRender(this._registerFunc);
  34931. this._registerFunc = null;
  34932. document.body.removeChild(this._debugCanvas);
  34933. this._debugCanvas = null;
  34934. this._debugCanvasContext = null;
  34935. }
  34936. };
  34937. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34938. if (this._audioEngine.canUseWebAudio) {
  34939. inputAudioNode.connect(this._webAudioAnalyser);
  34940. this._webAudioAnalyser.connect(outputAudioNode);
  34941. }
  34942. };
  34943. Analyser.prototype.dispose = function () {
  34944. if (this._audioEngine.canUseWebAudio) {
  34945. this._webAudioAnalyser.disconnect();
  34946. }
  34947. };
  34948. return Analyser;
  34949. })();
  34950. BABYLON.Analyser = Analyser;
  34951. })(BABYLON || (BABYLON = {}));
  34952. var BABYLON;
  34953. (function (BABYLON) {
  34954. var AudioEngine = (function () {
  34955. function AudioEngine() {
  34956. this._audioContext = null;
  34957. this._audioContextInitialized = false;
  34958. this.canUseWebAudio = false;
  34959. this.WarnedWebAudioUnsupported = false;
  34960. this.unlocked = false;
  34961. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34962. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34963. this.canUseWebAudio = true;
  34964. }
  34965. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34966. this._unlockiOSaudio();
  34967. }
  34968. else {
  34969. this.unlocked = true;
  34970. }
  34971. }
  34972. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34973. get: function () {
  34974. if (!this._audioContextInitialized) {
  34975. this._initializeAudioContext();
  34976. }
  34977. return this._audioContext;
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. AudioEngine.prototype._unlockiOSaudio = function () {
  34983. var _this = this;
  34984. var unlockaudio = function () {
  34985. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34986. var source = _this.audioContext.createBufferSource();
  34987. source.buffer = buffer;
  34988. source.connect(_this.audioContext.destination);
  34989. source.start(0);
  34990. setTimeout(function () {
  34991. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34992. _this.unlocked = true;
  34993. window.removeEventListener('touchend', unlockaudio, false);
  34994. if (_this.onAudioUnlocked) {
  34995. _this.onAudioUnlocked();
  34996. }
  34997. }
  34998. }, 0);
  34999. };
  35000. window.addEventListener('touchend', unlockaudio, false);
  35001. };
  35002. AudioEngine.prototype._initializeAudioContext = function () {
  35003. try {
  35004. if (this.canUseWebAudio) {
  35005. this._audioContext = new AudioContext();
  35006. // create a global volume gain node
  35007. this.masterGain = this._audioContext.createGain();
  35008. this.masterGain.gain.value = 1;
  35009. this.masterGain.connect(this._audioContext.destination);
  35010. this._audioContextInitialized = true;
  35011. }
  35012. }
  35013. catch (e) {
  35014. this.canUseWebAudio = false;
  35015. BABYLON.Tools.Error("Web Audio: " + e.message);
  35016. }
  35017. };
  35018. AudioEngine.prototype.dispose = function () {
  35019. if (this.canUseWebAudio && this._audioContextInitialized) {
  35020. if (this._connectedAnalyser) {
  35021. this._connectedAnalyser.stopDebugCanvas();
  35022. this._connectedAnalyser.dispose();
  35023. this.masterGain.disconnect();
  35024. this.masterGain.connect(this._audioContext.destination);
  35025. this._connectedAnalyser = null;
  35026. }
  35027. this.masterGain.gain.value = 1;
  35028. }
  35029. this.WarnedWebAudioUnsupported = false;
  35030. };
  35031. AudioEngine.prototype.getGlobalVolume = function () {
  35032. if (this.canUseWebAudio && this._audioContextInitialized) {
  35033. return this.masterGain.gain.value;
  35034. }
  35035. else {
  35036. return -1;
  35037. }
  35038. };
  35039. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35040. if (this.canUseWebAudio && this._audioContextInitialized) {
  35041. this.masterGain.gain.value = newVolume;
  35042. }
  35043. };
  35044. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35045. if (this._connectedAnalyser) {
  35046. this._connectedAnalyser.stopDebugCanvas();
  35047. }
  35048. if (this.canUseWebAudio && this._audioContextInitialized) {
  35049. this._connectedAnalyser = analyser;
  35050. this.masterGain.disconnect();
  35051. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35052. }
  35053. };
  35054. return AudioEngine;
  35055. })();
  35056. BABYLON.AudioEngine = AudioEngine;
  35057. })(BABYLON || (BABYLON = {}));
  35058. var BABYLON;
  35059. (function (BABYLON) {
  35060. var Sound = (function () {
  35061. /**
  35062. * Create a sound and attach it to a scene
  35063. * @param name Name of your sound
  35064. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35065. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35066. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35067. */
  35068. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35069. var _this = this;
  35070. this.autoplay = false;
  35071. this.loop = false;
  35072. this.useCustomAttenuation = false;
  35073. this.spatialSound = false;
  35074. this.refDistance = 1;
  35075. this.rolloffFactor = 1;
  35076. this.maxDistance = 100;
  35077. this.distanceModel = "linear";
  35078. this._panningModel = "equalpower";
  35079. this._playbackRate = 1;
  35080. this._streaming = false;
  35081. this._startTime = 0;
  35082. this._startOffset = 0;
  35083. this._position = BABYLON.Vector3.Zero();
  35084. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35085. this._volume = 1;
  35086. this._isLoaded = false;
  35087. this._isReadyToPlay = false;
  35088. this.isPlaying = false;
  35089. this.isPaused = false;
  35090. this._isDirectional = false;
  35091. // Used if you'd like to create a directional sound.
  35092. // If not set, the sound will be omnidirectional
  35093. this._coneInnerAngle = 360;
  35094. this._coneOuterAngle = 360;
  35095. this._coneOuterGain = 0;
  35096. this._isOutputConnected = false;
  35097. this.name = name;
  35098. this._scene = scene;
  35099. this._readyToPlayCallback = readyToPlayCallback;
  35100. // Default custom attenuation function is a linear attenuation
  35101. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35102. if (currentDistance < maxDistance) {
  35103. return currentVolume * (1 - currentDistance / maxDistance);
  35104. }
  35105. else {
  35106. return 0;
  35107. }
  35108. };
  35109. if (options) {
  35110. this.autoplay = options.autoplay || false;
  35111. this.loop = options.loop || false;
  35112. // if volume === 0, we need another way to check this option
  35113. if (options.volume !== undefined) {
  35114. this._volume = options.volume;
  35115. }
  35116. this.spatialSound = options.spatialSound || false;
  35117. this.maxDistance = options.maxDistance || 100;
  35118. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35119. this.rolloffFactor = options.rolloffFactor || 1;
  35120. this.refDistance = options.refDistance || 1;
  35121. this.distanceModel = options.distanceModel || "linear";
  35122. this._playbackRate = options.playbackRate || 1;
  35123. this._streaming = options.streaming || false;
  35124. }
  35125. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35126. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35127. this._soundGain.gain.value = this._volume;
  35128. this._inputAudioNode = this._soundGain;
  35129. this._ouputAudioNode = this._soundGain;
  35130. if (this.spatialSound) {
  35131. this._createSpatialParameters();
  35132. }
  35133. this._scene.mainSoundTrack.AddSound(this);
  35134. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35135. if (urlOrArrayBuffer) {
  35136. // If it's an URL
  35137. if (typeof (urlOrArrayBuffer) === "string") {
  35138. // Loading sound using XHR2
  35139. if (!this._streaming) {
  35140. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35141. }
  35142. else {
  35143. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35144. this._htmlAudioElement.controls = false;
  35145. this._htmlAudioElement.loop = this.loop;
  35146. this._htmlAudioElement.crossOrigin = "anonymous";
  35147. this._htmlAudioElement.preload = "auto";
  35148. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35149. _this._isReadyToPlay = true;
  35150. if (_this.autoplay) {
  35151. _this.play();
  35152. }
  35153. if (_this._readyToPlayCallback) {
  35154. _this._readyToPlayCallback();
  35155. }
  35156. });
  35157. document.body.appendChild(this._htmlAudioElement);
  35158. }
  35159. }
  35160. else {
  35161. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35162. if (urlOrArrayBuffer.byteLength > 0) {
  35163. this._soundLoaded(urlOrArrayBuffer);
  35164. }
  35165. }
  35166. else {
  35167. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35168. }
  35169. }
  35170. }
  35171. }
  35172. else {
  35173. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35174. this._scene.mainSoundTrack.AddSound(this);
  35175. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35176. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35177. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35178. }
  35179. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35180. if (this._readyToPlayCallback) {
  35181. window.setTimeout(function () {
  35182. _this._readyToPlayCallback();
  35183. }, 1000);
  35184. }
  35185. }
  35186. }
  35187. Sound.prototype.dispose = function () {
  35188. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35189. if (this.isPlaying) {
  35190. this.stop();
  35191. }
  35192. this._isReadyToPlay = false;
  35193. if (this.soundTrackId === -1) {
  35194. this._scene.mainSoundTrack.RemoveSound(this);
  35195. }
  35196. else {
  35197. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35198. }
  35199. if (this._soundGain) {
  35200. this._soundGain.disconnect();
  35201. this._soundGain = null;
  35202. }
  35203. if (this._soundPanner) {
  35204. this._soundPanner.disconnect();
  35205. this._soundPanner = null;
  35206. }
  35207. if (this._soundSource) {
  35208. this._soundSource.disconnect();
  35209. this._soundSource = null;
  35210. }
  35211. this._audioBuffer = null;
  35212. if (this._htmlAudioElement) {
  35213. this._htmlAudioElement.pause();
  35214. this._htmlAudioElement.src = "";
  35215. document.body.removeChild(this._htmlAudioElement);
  35216. }
  35217. if (this._connectedMesh) {
  35218. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35219. this._connectedMesh = null;
  35220. }
  35221. }
  35222. };
  35223. Sound.prototype._soundLoaded = function (audioData) {
  35224. var _this = this;
  35225. this._isLoaded = true;
  35226. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35227. _this._audioBuffer = buffer;
  35228. _this._isReadyToPlay = true;
  35229. if (_this.autoplay) {
  35230. _this.play();
  35231. }
  35232. if (_this._readyToPlayCallback) {
  35233. _this._readyToPlayCallback();
  35234. }
  35235. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35236. };
  35237. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35238. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35239. this._audioBuffer = audioBuffer;
  35240. this._isReadyToPlay = true;
  35241. }
  35242. };
  35243. Sound.prototype.updateOptions = function (options) {
  35244. if (options) {
  35245. this.loop = options.loop || this.loop;
  35246. this.maxDistance = options.maxDistance || this.maxDistance;
  35247. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35248. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35249. this.refDistance = options.refDistance || this.refDistance;
  35250. this.distanceModel = options.distanceModel || this.distanceModel;
  35251. this._playbackRate = options.playbackRate || this._playbackRate;
  35252. this._updateSpatialParameters();
  35253. if (this.isPlaying) {
  35254. if (this._streaming) {
  35255. this._htmlAudioElement.playbackRate = this._playbackRate;
  35256. }
  35257. else {
  35258. this._soundSource.playbackRate.value = this._playbackRate;
  35259. }
  35260. }
  35261. }
  35262. };
  35263. Sound.prototype._createSpatialParameters = function () {
  35264. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35265. if (this._scene.headphone) {
  35266. this._panningModel = "HRTF";
  35267. }
  35268. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35269. this._updateSpatialParameters();
  35270. this._soundPanner.connect(this._ouputAudioNode);
  35271. this._inputAudioNode = this._soundPanner;
  35272. }
  35273. };
  35274. Sound.prototype._updateSpatialParameters = function () {
  35275. if (this.spatialSound) {
  35276. if (this.useCustomAttenuation) {
  35277. // Tricks to disable in a way embedded Web Audio attenuation
  35278. this._soundPanner.distanceModel = "linear";
  35279. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35280. this._soundPanner.refDistance = 1;
  35281. this._soundPanner.rolloffFactor = 1;
  35282. this._soundPanner.panningModel = this._panningModel;
  35283. }
  35284. else {
  35285. this._soundPanner.distanceModel = this.distanceModel;
  35286. this._soundPanner.maxDistance = this.maxDistance;
  35287. this._soundPanner.refDistance = this.refDistance;
  35288. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35289. this._soundPanner.panningModel = this._panningModel;
  35290. }
  35291. }
  35292. };
  35293. Sound.prototype.switchPanningModelToHRTF = function () {
  35294. this._panningModel = "HRTF";
  35295. this._switchPanningModel();
  35296. };
  35297. Sound.prototype.switchPanningModelToEqualPower = function () {
  35298. this._panningModel = "equalpower";
  35299. this._switchPanningModel();
  35300. };
  35301. Sound.prototype._switchPanningModel = function () {
  35302. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35303. this._soundPanner.panningModel = this._panningModel;
  35304. }
  35305. };
  35306. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35307. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35308. if (this._isOutputConnected) {
  35309. this._ouputAudioNode.disconnect();
  35310. }
  35311. this._ouputAudioNode.connect(soundTrackAudioNode);
  35312. this._isOutputConnected = true;
  35313. }
  35314. };
  35315. /**
  35316. * Transform this sound into a directional source
  35317. * @param coneInnerAngle Size of the inner cone in degree
  35318. * @param coneOuterAngle Size of the outer cone in degree
  35319. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35320. */
  35321. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35322. if (coneOuterAngle < coneInnerAngle) {
  35323. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35324. return;
  35325. }
  35326. this._coneInnerAngle = coneInnerAngle;
  35327. this._coneOuterAngle = coneOuterAngle;
  35328. this._coneOuterGain = coneOuterGain;
  35329. this._isDirectional = true;
  35330. if (this.isPlaying && this.loop) {
  35331. this.stop();
  35332. this.play();
  35333. }
  35334. };
  35335. Sound.prototype.setPosition = function (newPosition) {
  35336. this._position = newPosition;
  35337. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35338. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35339. }
  35340. };
  35341. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35342. this._localDirection = newLocalDirection;
  35343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35344. this._updateDirection();
  35345. }
  35346. };
  35347. Sound.prototype._updateDirection = function () {
  35348. var mat = this._connectedMesh.getWorldMatrix();
  35349. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35350. direction.normalize();
  35351. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35352. };
  35353. Sound.prototype.updateDistanceFromListener = function () {
  35354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35355. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35356. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35357. }
  35358. };
  35359. Sound.prototype.setAttenuationFunction = function (callback) {
  35360. this._customAttenuationFunction = callback;
  35361. };
  35362. /**
  35363. * Play the sound
  35364. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35365. */
  35366. Sound.prototype.play = function (time) {
  35367. var _this = this;
  35368. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35369. try {
  35370. if (this._startOffset < 0) {
  35371. time = -this._startOffset;
  35372. this._startOffset = 0;
  35373. }
  35374. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35375. if (!this._soundSource || !this._streamingSource) {
  35376. if (this.spatialSound) {
  35377. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35378. if (this._isDirectional) {
  35379. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35380. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35381. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35382. if (this._connectedMesh) {
  35383. this._updateDirection();
  35384. }
  35385. else {
  35386. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35387. }
  35388. }
  35389. }
  35390. }
  35391. if (this._streaming) {
  35392. if (!this._streamingSource) {
  35393. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35394. this._htmlAudioElement.onended = function () { _this._onended(); };
  35395. this._htmlAudioElement.playbackRate = this._playbackRate;
  35396. }
  35397. this._streamingSource.disconnect();
  35398. this._streamingSource.connect(this._inputAudioNode);
  35399. this._htmlAudioElement.play();
  35400. }
  35401. else {
  35402. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35403. this._soundSource.buffer = this._audioBuffer;
  35404. this._soundSource.connect(this._inputAudioNode);
  35405. this._soundSource.loop = this.loop;
  35406. this._soundSource.playbackRate.value = this._playbackRate;
  35407. this._soundSource.onended = function () { _this._onended(); };
  35408. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35409. }
  35410. this._startTime = startTime;
  35411. this.isPlaying = true;
  35412. this.isPaused = false;
  35413. }
  35414. catch (ex) {
  35415. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35416. }
  35417. }
  35418. };
  35419. Sound.prototype._onended = function () {
  35420. this.isPlaying = false;
  35421. if (this.onended) {
  35422. this.onended();
  35423. }
  35424. };
  35425. /**
  35426. * Stop the sound
  35427. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35428. */
  35429. Sound.prototype.stop = function (time) {
  35430. if (this.isPlaying) {
  35431. if (this._streaming) {
  35432. this._htmlAudioElement.pause();
  35433. // Test needed for Firefox or it will generate an Invalid State Error
  35434. if (this._htmlAudioElement.currentTime > 0) {
  35435. this._htmlAudioElement.currentTime = 0;
  35436. }
  35437. }
  35438. else {
  35439. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35440. this._soundSource.stop(stopTime);
  35441. if (!this.isPaused) {
  35442. this._startOffset = 0;
  35443. }
  35444. }
  35445. this.isPlaying = false;
  35446. }
  35447. };
  35448. Sound.prototype.pause = function () {
  35449. if (this.isPlaying) {
  35450. this.isPaused = true;
  35451. if (this._streaming) {
  35452. this._htmlAudioElement.pause();
  35453. }
  35454. else {
  35455. this.stop(0);
  35456. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35457. }
  35458. }
  35459. };
  35460. Sound.prototype.setVolume = function (newVolume, time) {
  35461. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35462. if (time) {
  35463. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35464. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35465. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35466. }
  35467. else {
  35468. this._soundGain.gain.value = newVolume;
  35469. }
  35470. }
  35471. this._volume = newVolume;
  35472. };
  35473. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35474. this._playbackRate = newPlaybackRate;
  35475. if (this.isPlaying) {
  35476. if (this._streaming) {
  35477. this._htmlAudioElement.playbackRate = this._playbackRate;
  35478. }
  35479. else {
  35480. this._soundSource.playbackRate.value = this._playbackRate;
  35481. }
  35482. }
  35483. };
  35484. Sound.prototype.getVolume = function () {
  35485. return this._volume;
  35486. };
  35487. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35488. var _this = this;
  35489. if (this._connectedMesh) {
  35490. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35491. this._registerFunc = null;
  35492. }
  35493. this._connectedMesh = meshToConnectTo;
  35494. if (!this.spatialSound) {
  35495. this.spatialSound = true;
  35496. this._createSpatialParameters();
  35497. if (this.isPlaying && this.loop) {
  35498. this.stop();
  35499. this.play();
  35500. }
  35501. }
  35502. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35503. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35504. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35505. };
  35506. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35507. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35508. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35509. this._updateDirection();
  35510. }
  35511. };
  35512. Sound.prototype.clone = function () {
  35513. var _this = this;
  35514. if (!this._streaming) {
  35515. var setBufferAndRun = function () {
  35516. if (_this._isReadyToPlay) {
  35517. clonedSound._audioBuffer = _this.getAudioBuffer();
  35518. clonedSound._isReadyToPlay = true;
  35519. if (clonedSound.autoplay) {
  35520. clonedSound.play();
  35521. }
  35522. }
  35523. else {
  35524. window.setTimeout(setBufferAndRun, 300);
  35525. }
  35526. };
  35527. var currentOptions = {
  35528. autoplay: this.autoplay, loop: this.loop,
  35529. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35530. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35531. refDistance: this.refDistance, distanceModel: this.distanceModel
  35532. };
  35533. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35534. if (this.useCustomAttenuation) {
  35535. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35536. }
  35537. clonedSound.setPosition(this._position);
  35538. clonedSound.setPlaybackRate(this._playbackRate);
  35539. setBufferAndRun();
  35540. return clonedSound;
  35541. }
  35542. else {
  35543. return null;
  35544. }
  35545. };
  35546. Sound.prototype.getAudioBuffer = function () {
  35547. return this._audioBuffer;
  35548. };
  35549. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35550. var soundName = parsedSound.name;
  35551. var soundUrl;
  35552. if (parsedSound.url) {
  35553. soundUrl = rootUrl + parsedSound.url;
  35554. }
  35555. else {
  35556. soundUrl = rootUrl + soundName;
  35557. }
  35558. var options = {
  35559. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35560. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35561. rolloffFactor: parsedSound.rolloffFactor,
  35562. refDistance: parsedSound.refDistance,
  35563. distanceModel: parsedSound.distanceModel,
  35564. playbackRate: parsedSound.playbackRate
  35565. };
  35566. var newSound;
  35567. if (!sourceSound) {
  35568. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35569. scene._addPendingData(newSound);
  35570. }
  35571. else {
  35572. var setBufferAndRun = function () {
  35573. if (sourceSound._isReadyToPlay) {
  35574. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35575. newSound._isReadyToPlay = true;
  35576. if (newSound.autoplay) {
  35577. newSound.play();
  35578. }
  35579. }
  35580. else {
  35581. window.setTimeout(setBufferAndRun, 300);
  35582. }
  35583. };
  35584. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35585. setBufferAndRun();
  35586. }
  35587. if (parsedSound.position) {
  35588. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35589. newSound.setPosition(soundPosition);
  35590. }
  35591. if (parsedSound.isDirectional) {
  35592. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35593. if (parsedSound.localDirectionToMesh) {
  35594. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35595. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35596. }
  35597. }
  35598. if (parsedSound.connectedMeshId) {
  35599. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35600. if (connectedMesh) {
  35601. newSound.attachToMesh(connectedMesh);
  35602. }
  35603. }
  35604. return newSound;
  35605. };
  35606. return Sound;
  35607. })();
  35608. BABYLON.Sound = Sound;
  35609. })(BABYLON || (BABYLON = {}));
  35610. var BABYLON;
  35611. (function (BABYLON) {
  35612. var SoundTrack = (function () {
  35613. function SoundTrack(scene, options) {
  35614. this.id = -1;
  35615. this._isMainTrack = false;
  35616. this._isInitialized = false;
  35617. this._scene = scene;
  35618. this.soundCollection = new Array();
  35619. this._options = options;
  35620. if (!this._isMainTrack) {
  35621. this._scene.soundTracks.push(this);
  35622. this.id = this._scene.soundTracks.length - 1;
  35623. }
  35624. }
  35625. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35626. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35627. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35628. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35629. if (this._options) {
  35630. if (this._options.volume) {
  35631. this._outputAudioNode.gain.value = this._options.volume;
  35632. }
  35633. if (this._options.mainTrack) {
  35634. this._isMainTrack = this._options.mainTrack;
  35635. }
  35636. }
  35637. this._isInitialized = true;
  35638. }
  35639. };
  35640. SoundTrack.prototype.dispose = function () {
  35641. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35642. if (this._connectedAnalyser) {
  35643. this._connectedAnalyser.stopDebugCanvas();
  35644. }
  35645. while (this.soundCollection.length) {
  35646. this.soundCollection[0].dispose();
  35647. }
  35648. if (this._outputAudioNode) {
  35649. this._outputAudioNode.disconnect();
  35650. }
  35651. this._outputAudioNode = null;
  35652. }
  35653. };
  35654. SoundTrack.prototype.AddSound = function (sound) {
  35655. if (!this._isInitialized) {
  35656. this._initializeSoundTrackAudioGraph();
  35657. }
  35658. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35659. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35660. }
  35661. if (sound.soundTrackId) {
  35662. if (sound.soundTrackId === -1) {
  35663. this._scene.mainSoundTrack.RemoveSound(sound);
  35664. }
  35665. else {
  35666. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35667. }
  35668. }
  35669. this.soundCollection.push(sound);
  35670. sound.soundTrackId = this.id;
  35671. };
  35672. SoundTrack.prototype.RemoveSound = function (sound) {
  35673. var index = this.soundCollection.indexOf(sound);
  35674. if (index !== -1) {
  35675. this.soundCollection.splice(index, 1);
  35676. }
  35677. };
  35678. SoundTrack.prototype.setVolume = function (newVolume) {
  35679. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35680. this._outputAudioNode.gain.value = newVolume;
  35681. }
  35682. };
  35683. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35684. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35685. for (var i = 0; i < this.soundCollection.length; i++) {
  35686. this.soundCollection[i].switchPanningModelToHRTF();
  35687. }
  35688. }
  35689. };
  35690. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35691. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35692. for (var i = 0; i < this.soundCollection.length; i++) {
  35693. this.soundCollection[i].switchPanningModelToEqualPower();
  35694. }
  35695. }
  35696. };
  35697. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35698. if (this._connectedAnalyser) {
  35699. this._connectedAnalyser.stopDebugCanvas();
  35700. }
  35701. this._connectedAnalyser = analyser;
  35702. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35703. this._outputAudioNode.disconnect();
  35704. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35705. }
  35706. };
  35707. return SoundTrack;
  35708. })();
  35709. BABYLON.SoundTrack = SoundTrack;
  35710. })(BABYLON || (BABYLON = {}));
  35711. var BABYLON;
  35712. (function (BABYLON) {
  35713. var DepthRenderer = (function () {
  35714. function DepthRenderer(scene, type) {
  35715. var _this = this;
  35716. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35717. this._viewMatrix = BABYLON.Matrix.Zero();
  35718. this._projectionMatrix = BABYLON.Matrix.Zero();
  35719. this._transformMatrix = BABYLON.Matrix.Zero();
  35720. this._worldViewProjection = BABYLON.Matrix.Zero();
  35721. this._scene = scene;
  35722. var engine = scene.getEngine();
  35723. // Render target
  35724. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35725. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35726. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35727. this._depthMap.refreshRate = 1;
  35728. this._depthMap.renderParticles = false;
  35729. this._depthMap.renderList = null;
  35730. // set default depth value to 1.0 (far away)
  35731. this._depthMap.onClear = function (engine) {
  35732. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35733. };
  35734. // Custom render function
  35735. var renderSubMesh = function (subMesh) {
  35736. var mesh = subMesh.getRenderingMesh();
  35737. var scene = _this._scene;
  35738. var engine = scene.getEngine();
  35739. // Culling
  35740. engine.setState(subMesh.getMaterial().backFaceCulling);
  35741. // Managing instances
  35742. var batch = mesh._getInstancesRenderList(subMesh._id);
  35743. if (batch.mustReturn) {
  35744. return;
  35745. }
  35746. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35747. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35748. engine.enableEffect(_this._effect);
  35749. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35750. var material = subMesh.getMaterial();
  35751. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35752. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35753. // Alpha test
  35754. if (material && material.needAlphaTesting()) {
  35755. var alphaTexture = material.getAlphaTestTexture();
  35756. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35757. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35758. }
  35759. // Bones
  35760. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35761. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35762. }
  35763. // Draw
  35764. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35765. }
  35766. };
  35767. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35768. var index;
  35769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35770. renderSubMesh(opaqueSubMeshes.data[index]);
  35771. }
  35772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35773. renderSubMesh(alphaTestSubMeshes.data[index]);
  35774. }
  35775. };
  35776. }
  35777. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35778. var defines = [];
  35779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35780. var mesh = subMesh.getMesh();
  35781. var scene = mesh.getScene();
  35782. var material = subMesh.getMaterial();
  35783. // Alpha test
  35784. if (material && material.needAlphaTesting()) {
  35785. defines.push("#define ALPHATEST");
  35786. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35787. attribs.push(BABYLON.VertexBuffer.UVKind);
  35788. defines.push("#define UV1");
  35789. }
  35790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35791. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35792. defines.push("#define UV2");
  35793. }
  35794. }
  35795. // Bones
  35796. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35799. if (mesh.numBoneInfluencers > 4) {
  35800. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35801. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35802. }
  35803. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35804. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35805. }
  35806. else {
  35807. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35808. }
  35809. // Instances
  35810. if (useInstances) {
  35811. defines.push("#define INSTANCES");
  35812. attribs.push("world0");
  35813. attribs.push("world1");
  35814. attribs.push("world2");
  35815. attribs.push("world3");
  35816. }
  35817. // Get correct effect
  35818. var join = defines.join("\n");
  35819. if (this._cachedDefines !== join) {
  35820. this._cachedDefines = join;
  35821. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35822. }
  35823. return this._effect.isReady();
  35824. };
  35825. DepthRenderer.prototype.getDepthMap = function () {
  35826. return this._depthMap;
  35827. };
  35828. // Methods
  35829. DepthRenderer.prototype.dispose = function () {
  35830. this._depthMap.dispose();
  35831. };
  35832. return DepthRenderer;
  35833. })();
  35834. BABYLON.DepthRenderer = DepthRenderer;
  35835. })(BABYLON || (BABYLON = {}));
  35836. var BABYLON;
  35837. (function (BABYLON) {
  35838. var SSAORenderingPipeline = (function (_super) {
  35839. __extends(SSAORenderingPipeline, _super);
  35840. /**
  35841. * @constructor
  35842. * @param {string} name - The rendering pipeline name
  35843. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35844. * @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 }
  35845. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35846. */
  35847. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35848. var _this = this;
  35849. _super.call(this, scene.getEngine(), name);
  35850. // Members
  35851. /**
  35852. * The PassPostProcess id in the pipeline that contains the original scene color
  35853. * @type {string}
  35854. */
  35855. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35856. /**
  35857. * The SSAO PostProcess id in the pipeline
  35858. * @type {string}
  35859. */
  35860. this.SSAORenderEffect = "SSAORenderEffect";
  35861. /**
  35862. * The horizontal blur PostProcess id in the pipeline
  35863. * @type {string}
  35864. */
  35865. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35866. /**
  35867. * The vertical blur PostProcess id in the pipeline
  35868. * @type {string}
  35869. */
  35870. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35871. /**
  35872. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35873. * @type {string}
  35874. */
  35875. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35876. /**
  35877. * The output strength of the SSAO post-process. Default value is 1.0.
  35878. * @type {number}
  35879. */
  35880. this.totalStrength = 1.0;
  35881. /**
  35882. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35883. * @type {number}
  35884. */
  35885. this.radius = 0.0001;
  35886. /**
  35887. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35888. * Must not be equal to fallOff and superior to fallOff.
  35889. * Default value is 0.975
  35890. * @type {number}
  35891. */
  35892. this.area = 0.0075;
  35893. /**
  35894. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35895. * Must not be equal to area and inferior to area.
  35896. * Default value is 0.0
  35897. * @type {number}
  35898. */
  35899. this.fallOff = 0.000001;
  35900. /**
  35901. * The base color of the SSAO post-process
  35902. * The final result is "base + ssao" between [0, 1]
  35903. * @type {number}
  35904. */
  35905. this.base = 0.5;
  35906. this._firstUpdate = true;
  35907. this._scene = scene;
  35908. // Set up assets
  35909. this._createRandomTexture();
  35910. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35911. var ssaoRatio = ratio.ssaoRatio || ratio;
  35912. var combineRatio = ratio.combineRatio || ratio;
  35913. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35914. this._createSSAOPostProcess(ssaoRatio);
  35915. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35916. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35917. this._createSSAOCombinePostProcess(combineRatio);
  35918. // Set up pipeline
  35919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35924. // Finish
  35925. scene.postProcessRenderPipelineManager.addPipeline(this);
  35926. if (cameras)
  35927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35928. }
  35929. // Public Methods
  35930. /**
  35931. * Returns the horizontal blur PostProcess
  35932. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35933. */
  35934. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35935. return this._blurHPostProcess;
  35936. };
  35937. /**
  35938. * Returns the vertical blur PostProcess
  35939. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35940. */
  35941. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35942. return this._blurVPostProcess;
  35943. };
  35944. /**
  35945. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35946. */
  35947. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35948. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35949. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35950. this._originalColorPostProcess = undefined;
  35951. this._ssaoPostProcess = undefined;
  35952. this._blurHPostProcess = undefined;
  35953. this._blurVPostProcess = undefined;
  35954. this._ssaoCombinePostProcess = undefined;
  35955. this._randomTexture.dispose();
  35956. if (disableDepthRender)
  35957. this._scene.disableDepthRenderer();
  35958. };
  35959. // Private Methods
  35960. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35961. var _this = this;
  35962. var numSamples = 16;
  35963. var sampleSphere = [
  35964. 0.5381, 0.1856, -0.4319,
  35965. 0.1379, 0.2486, 0.4430,
  35966. 0.3371, 0.5679, -0.0057,
  35967. -0.6999, -0.0451, -0.0019,
  35968. 0.0689, -0.1598, -0.8547,
  35969. 0.0560, 0.0069, -0.1843,
  35970. -0.0146, 0.1402, 0.0762,
  35971. 0.0100, -0.1924, -0.0344,
  35972. -0.3577, -0.5301, -0.4358,
  35973. -0.3169, 0.1063, 0.0158,
  35974. 0.0103, -0.5869, 0.0046,
  35975. -0.0897, -0.4940, 0.3287,
  35976. 0.7119, -0.0154, -0.0918,
  35977. -0.0533, 0.0596, -0.5411,
  35978. 0.0352, -0.0631, 0.5460,
  35979. -0.4776, 0.2847, -0.0271
  35980. ];
  35981. var samplesFactor = 1.0 / numSamples;
  35982. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35983. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35984. "area", "fallOff", "base"
  35985. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35986. this._ssaoPostProcess.onApply = function (effect) {
  35987. if (_this._firstUpdate) {
  35988. effect.setArray3("sampleSphere", sampleSphere);
  35989. effect.setFloat("samplesFactor", samplesFactor);
  35990. effect.setFloat("randTextureTiles", 4.0);
  35991. _this._firstUpdate = false;
  35992. }
  35993. effect.setFloat("totalStrength", _this.totalStrength);
  35994. effect.setFloat("radius", _this.radius);
  35995. effect.setFloat("area", _this.area);
  35996. effect.setFloat("fallOff", _this.fallOff);
  35997. effect.setFloat("base", _this.base);
  35998. effect.setTexture("textureSampler", _this._depthTexture);
  35999. effect.setTexture("randomSampler", _this._randomTexture);
  36000. };
  36001. };
  36002. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36003. var _this = this;
  36004. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36005. this._ssaoCombinePostProcess.onApply = function (effect) {
  36006. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36007. };
  36008. };
  36009. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36010. var size = 512;
  36011. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36012. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36013. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36014. var context = this._randomTexture.getContext();
  36015. var rand = function (min, max) {
  36016. return Math.random() * (max - min) + min;
  36017. };
  36018. var randVector = BABYLON.Vector3.Zero();
  36019. for (var x = 0; x < size; x++) {
  36020. for (var y = 0; y < size; y++) {
  36021. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36022. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36023. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36024. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36025. context.fillRect(x, y, 1, 1);
  36026. }
  36027. }
  36028. this._randomTexture.update(false);
  36029. };
  36030. return SSAORenderingPipeline;
  36031. })(BABYLON.PostProcessRenderPipeline);
  36032. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36033. })(BABYLON || (BABYLON = {}));
  36034. var BABYLON;
  36035. (function (BABYLON) {
  36036. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36037. var VolumetricLightScatteringPostProcess = (function (_super) {
  36038. __extends(VolumetricLightScatteringPostProcess, _super);
  36039. /**
  36040. * @constructor
  36041. * @param {string} name - The post-process name
  36042. * @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)
  36043. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36044. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36045. * @param {number} samples - The post-process quality, default 100
  36046. * @param {number} samplingMode - The post-process filtering mode
  36047. * @param {BABYLON.Engine} engine - The babylon engine
  36048. * @param {boolean} reusable - If the post-process is reusable
  36049. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36050. */
  36051. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36052. var _this = this;
  36053. if (samples === void 0) { samples = 100; }
  36054. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36055. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36056. this._screenCoordinates = BABYLON.Vector2.Zero();
  36057. /**
  36058. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36059. * @type {boolean}
  36060. */
  36061. this.useCustomMeshPosition = false;
  36062. /**
  36063. * If the post-process should inverse the light scattering direction
  36064. * @type {boolean}
  36065. */
  36066. this.invert = true;
  36067. /**
  36068. * Set to true to use the diffuseColor instead of the diffuseTexture
  36069. * @type {boolean}
  36070. */
  36071. this.useDiffuseColor = false;
  36072. /**
  36073. * Array containing the excluded meshes not rendered in the internal pass
  36074. */
  36075. this.excludedMeshes = new Array();
  36076. /**
  36077. * Controls the overall intensity of the post-process
  36078. * @type {number}
  36079. */
  36080. this.exposure = 0.3;
  36081. /**
  36082. * Dissipates each sample's contribution in range [0, 1]
  36083. * @type {number}
  36084. */
  36085. this.decay = 0.96815;
  36086. /**
  36087. * Controls the overall intensity of each sample
  36088. * @type {number}
  36089. */
  36090. this.weight = 0.58767;
  36091. /**
  36092. * Controls the density of each sample
  36093. * @type {number}
  36094. */
  36095. this.density = 0.926;
  36096. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36097. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  36098. // Configure mesh
  36099. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36100. // Configure
  36101. this._createPass(scene, ratio.passRatio || ratio);
  36102. this.onActivate = function (camera) {
  36103. if (!_this.isSupported) {
  36104. _this.dispose(camera);
  36105. }
  36106. _this.onActivate = null;
  36107. };
  36108. this.onApply = function (effect) {
  36109. _this._updateMeshScreenCoordinates(scene);
  36110. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36111. effect.setFloat("exposure", _this.exposure);
  36112. effect.setFloat("decay", _this.decay);
  36113. effect.setFloat("weight", _this.weight);
  36114. effect.setFloat("density", _this.density);
  36115. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36116. };
  36117. }
  36118. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36119. var mesh = subMesh.getMesh();
  36120. var defines = [];
  36121. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36122. var material = subMesh.getMaterial();
  36123. var needUV = false;
  36124. // Render this.mesh as default
  36125. if (mesh === this.mesh) {
  36126. if (this.useDiffuseColor) {
  36127. defines.push("#define DIFFUSE_COLOR_RENDER");
  36128. }
  36129. else if (material) {
  36130. if (material.diffuseTexture !== undefined) {
  36131. defines.push("#define BASIC_RENDER");
  36132. }
  36133. else {
  36134. defines.push("#define DIFFUSE_COLOR_RENDER");
  36135. }
  36136. }
  36137. defines.push("#define NEED_UV");
  36138. needUV = true;
  36139. }
  36140. // Alpha test
  36141. if (material) {
  36142. if (material.needAlphaTesting()) {
  36143. defines.push("#define ALPHATEST");
  36144. }
  36145. if (material.opacityTexture !== undefined) {
  36146. defines.push("#define OPACITY");
  36147. if (material.opacityTexture.getAlphaFromRGB) {
  36148. defines.push("#define OPACITYRGB");
  36149. }
  36150. if (!needUV) {
  36151. defines.push("#define NEED_UV");
  36152. }
  36153. }
  36154. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36155. attribs.push(BABYLON.VertexBuffer.UVKind);
  36156. defines.push("#define UV1");
  36157. }
  36158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36160. defines.push("#define UV2");
  36161. }
  36162. }
  36163. // Bones
  36164. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36167. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36168. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36169. }
  36170. else {
  36171. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36172. }
  36173. // Instances
  36174. if (useInstances) {
  36175. defines.push("#define INSTANCES");
  36176. attribs.push("world0");
  36177. attribs.push("world1");
  36178. attribs.push("world2");
  36179. attribs.push("world3");
  36180. }
  36181. // Get correct effect
  36182. var join = defines.join("\n");
  36183. if (this._cachedDefines !== join) {
  36184. this._cachedDefines = join;
  36185. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36186. }
  36187. return this._volumetricLightScatteringPass.isReady();
  36188. };
  36189. /**
  36190. * Sets the new light position for light scattering effect
  36191. * @param {BABYLON.Vector3} The new custom light position
  36192. */
  36193. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36194. this._customMeshPosition = position;
  36195. };
  36196. /**
  36197. * Returns the light position for light scattering effect
  36198. * @return {BABYLON.Vector3} The custom light position
  36199. */
  36200. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36201. return this._customMeshPosition;
  36202. };
  36203. /**
  36204. * Disposes the internal assets and detaches the post-process from the camera
  36205. */
  36206. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36207. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36208. if (rttIndex !== -1) {
  36209. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36210. }
  36211. this._volumetricLightScatteringRTT.dispose();
  36212. _super.prototype.dispose.call(this, camera);
  36213. };
  36214. /**
  36215. * Returns the render target texture used by the post-process
  36216. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36217. */
  36218. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36219. return this._volumetricLightScatteringRTT;
  36220. };
  36221. // Private methods
  36222. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36223. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36224. return true;
  36225. }
  36226. return false;
  36227. };
  36228. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36229. var _this = this;
  36230. var engine = scene.getEngine();
  36231. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36232. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36233. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36234. this._volumetricLightScatteringRTT.renderList = null;
  36235. this._volumetricLightScatteringRTT.renderParticles = false;
  36236. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36237. // Custom render function for submeshes
  36238. var renderSubMesh = function (subMesh) {
  36239. var mesh = subMesh.getRenderingMesh();
  36240. if (_this._meshExcluded(mesh)) {
  36241. return;
  36242. }
  36243. var scene = mesh.getScene();
  36244. var engine = scene.getEngine();
  36245. // Culling
  36246. engine.setState(subMesh.getMaterial().backFaceCulling);
  36247. // Managing instances
  36248. var batch = mesh._getInstancesRenderList(subMesh._id);
  36249. if (batch.mustReturn) {
  36250. return;
  36251. }
  36252. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36253. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36254. engine.enableEffect(_this._volumetricLightScatteringPass);
  36255. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36256. var material = subMesh.getMaterial();
  36257. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36258. // Alpha test
  36259. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36260. var alphaTexture = material.getAlphaTestTexture();
  36261. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36262. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36263. }
  36264. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36265. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36266. if (alphaTexture) {
  36267. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36268. }
  36269. }
  36270. if (material.opacityTexture !== undefined) {
  36271. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36272. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36273. }
  36274. }
  36275. // Bones
  36276. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36277. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36278. }
  36279. // Draw
  36280. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36281. }
  36282. };
  36283. // Render target texture callbacks
  36284. var savedSceneClearColor;
  36285. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36286. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36287. savedSceneClearColor = scene.clearColor;
  36288. scene.clearColor = sceneClearColor;
  36289. };
  36290. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36291. scene.clearColor = savedSceneClearColor;
  36292. };
  36293. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36294. var engine = scene.getEngine();
  36295. var index;
  36296. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36297. renderSubMesh(opaqueSubMeshes.data[index]);
  36298. }
  36299. engine.setAlphaTesting(true);
  36300. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36301. renderSubMesh(alphaTestSubMeshes.data[index]);
  36302. }
  36303. engine.setAlphaTesting(false);
  36304. if (transparentSubMeshes.length) {
  36305. // Sort sub meshes
  36306. for (index = 0; index < transparentSubMeshes.length; index++) {
  36307. var submesh = transparentSubMeshes.data[index];
  36308. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36309. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36310. }
  36311. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36312. sortedArray.sort(function (a, b) {
  36313. // Alpha index first
  36314. if (a._alphaIndex > b._alphaIndex) {
  36315. return 1;
  36316. }
  36317. if (a._alphaIndex < b._alphaIndex) {
  36318. return -1;
  36319. }
  36320. // Then distance to camera
  36321. if (a._distanceToCamera < b._distanceToCamera) {
  36322. return 1;
  36323. }
  36324. if (a._distanceToCamera > b._distanceToCamera) {
  36325. return -1;
  36326. }
  36327. return 0;
  36328. });
  36329. // Render sub meshes
  36330. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36331. for (index = 0; index < sortedArray.length; index++) {
  36332. renderSubMesh(sortedArray[index]);
  36333. }
  36334. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36335. }
  36336. };
  36337. };
  36338. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36339. var transform = scene.getTransformMatrix();
  36340. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36341. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36342. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36343. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36344. if (this.invert)
  36345. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36346. };
  36347. // Static methods
  36348. /**
  36349. * Creates a default mesh for the Volumeric Light Scattering post-process
  36350. * @param {string} The mesh name
  36351. * @param {BABYLON.Scene} The scene where to create the mesh
  36352. * @return {BABYLON.Mesh} the default mesh
  36353. */
  36354. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36355. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36356. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36357. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36358. return mesh;
  36359. };
  36360. return VolumetricLightScatteringPostProcess;
  36361. })(BABYLON.PostProcess);
  36362. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36363. })(BABYLON || (BABYLON = {}));
  36364. // BABYLON.JS Chromatic Aberration GLSL Shader
  36365. // Author: Olivier Guyot
  36366. // Separates very slightly R, G and B colors on the edges of the screen
  36367. // Inspired by Francois Tarlier & Martins Upitis
  36368. var BABYLON;
  36369. (function (BABYLON) {
  36370. var LensRenderingPipeline = (function (_super) {
  36371. __extends(LensRenderingPipeline, _super);
  36372. /**
  36373. * @constructor
  36374. *
  36375. * Effect parameters are as follow:
  36376. * {
  36377. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36378. * edge_blur: number; // from 0 to x (1 for realism)
  36379. * distortion: number; // from 0 to x (1 for realism)
  36380. * grain_amount: number; // from 0 to 1
  36381. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36382. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36383. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36384. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36385. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36386. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36387. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36388. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36389. * }
  36390. * Note: if an effect parameter is unset, effect is disabled
  36391. *
  36392. * @param {string} name - The rendering pipeline name
  36393. * @param {object} parameters - An object containing all parameters (see above)
  36394. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36395. * @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)
  36396. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36397. */
  36398. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36399. var _this = this;
  36400. if (ratio === void 0) { ratio = 1.0; }
  36401. _super.call(this, scene.getEngine(), name);
  36402. // Lens effects can be of the following:
  36403. // - chromatic aberration (slight shift of RGB colors)
  36404. // - blur on the edge of the lens
  36405. // - lens distortion
  36406. // - depth-of-field blur & highlights enhancing
  36407. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36408. // - grain effect (noise or custom texture)
  36409. // Two additional texture samplers are needed:
  36410. // - depth map (for depth-of-field)
  36411. // - grain texture
  36412. /**
  36413. * The chromatic aberration PostProcess id in the pipeline
  36414. * @type {string}
  36415. */
  36416. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36417. /**
  36418. * The highlights enhancing PostProcess id in the pipeline
  36419. * @type {string}
  36420. */
  36421. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36422. /**
  36423. * The depth-of-field PostProcess id in the pipeline
  36424. * @type {string}
  36425. */
  36426. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36427. this._scene = scene;
  36428. // Fetch texture samplers
  36429. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36430. if (parameters.grain_texture) {
  36431. this._grainTexture = parameters.grain_texture;
  36432. }
  36433. else {
  36434. this._createGrainTexture();
  36435. }
  36436. // save parameters
  36437. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36438. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36439. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36440. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36441. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36442. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36443. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36444. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36445. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36446. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36447. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36448. // Create effects
  36449. this._createChromaticAberrationPostProcess(ratio);
  36450. this._createHighlightsPostProcess(ratio);
  36451. this._createDepthOfFieldPostProcess(ratio / 4);
  36452. // Set up pipeline
  36453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36454. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36455. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36456. if (this._highlightsGain === -1) {
  36457. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36458. }
  36459. // Finish
  36460. scene.postProcessRenderPipelineManager.addPipeline(this);
  36461. if (cameras) {
  36462. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36463. }
  36464. }
  36465. // public methods (self explanatory)
  36466. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36467. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36468. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36469. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36470. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36471. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36472. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36473. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36474. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36475. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36476. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36477. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36478. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36479. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36480. };
  36481. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36482. this._highlightsPostProcess.updateEffect();
  36483. };
  36484. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36485. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36486. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36487. this._highlightsGain = amount;
  36488. };
  36489. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36490. if (this._highlightsGain === -1) {
  36491. this._highlightsGain = 1.0;
  36492. }
  36493. this._highlightsThreshold = amount;
  36494. };
  36495. LensRenderingPipeline.prototype.disableHighlights = function () {
  36496. this._highlightsGain = -1;
  36497. };
  36498. /**
  36499. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36500. */
  36501. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36502. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36503. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36504. this._chromaticAberrationPostProcess = undefined;
  36505. this._highlightsPostProcess = undefined;
  36506. this._depthOfFieldPostProcess = undefined;
  36507. this._grainTexture.dispose();
  36508. if (disableDepthRender)
  36509. this._scene.disableDepthRenderer();
  36510. };
  36511. // colors shifting and distortion
  36512. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36513. var _this = this;
  36514. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36515. [], // samplers
  36516. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36517. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36518. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36519. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36520. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36521. };
  36522. };
  36523. // highlights enhancing
  36524. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36525. var _this = this;
  36526. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36527. [], // samplers
  36528. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36529. this._highlightsPostProcess.onApply = function (effect) {
  36530. effect.setFloat('gain', _this._highlightsGain);
  36531. effect.setFloat('threshold', _this._highlightsThreshold);
  36532. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36533. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36534. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36535. };
  36536. };
  36537. // colors shifting and distortion
  36538. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36539. var _this = this;
  36540. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36541. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36542. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36543. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36544. this._depthOfFieldPostProcess.onApply = function (effect) {
  36545. effect.setTexture("depthSampler", _this._depthTexture);
  36546. effect.setTexture("grainSampler", _this._grainTexture);
  36547. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36548. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36549. effect.setFloat('grain_amount', _this._grainAmount);
  36550. effect.setBool('blur_noise', _this._blurNoise);
  36551. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36552. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36553. effect.setFloat('distortion', _this._distortion);
  36554. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36555. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36556. effect.setFloat('aperture', _this._dofAperture);
  36557. effect.setFloat('darken', _this._dofDarken);
  36558. effect.setFloat('edge_blur', _this._edgeBlur);
  36559. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36560. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36561. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36562. };
  36563. };
  36564. // creates a black and white random noise texture, 512x512
  36565. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36566. var size = 512;
  36567. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36568. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36569. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36570. var context = this._grainTexture.getContext();
  36571. var rand = function (min, max) {
  36572. return Math.random() * (max - min) + min;
  36573. };
  36574. var value;
  36575. for (var x = 0; x < size; x++) {
  36576. for (var y = 0; y < size; y++) {
  36577. value = Math.floor(rand(0.42, 0.58) * 255);
  36578. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36579. context.fillRect(x, y, 1, 1);
  36580. }
  36581. }
  36582. this._grainTexture.update(false);
  36583. };
  36584. return LensRenderingPipeline;
  36585. })(BABYLON.PostProcessRenderPipeline);
  36586. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36587. })(BABYLON || (BABYLON = {}));
  36588. //
  36589. // This post-process allows the modification of rendered colors by using
  36590. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36591. //
  36592. // The object needs to be provided an url to a texture containing the color
  36593. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36594. // Use an image editing software to tweak the LUT to match your needs.
  36595. //
  36596. // For an example of a color LUT, see here:
  36597. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36598. // For explanations on color grading, see here:
  36599. // http://udn.epicgames.com/Three/ColorGrading.html
  36600. //
  36601. var BABYLON;
  36602. (function (BABYLON) {
  36603. var ColorCorrectionPostProcess = (function (_super) {
  36604. __extends(ColorCorrectionPostProcess, _super);
  36605. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36606. var _this = this;
  36607. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36608. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36609. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36610. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36611. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36612. this.onApply = function (effect) {
  36613. effect.setTexture("colorTable", _this._colorTableTexture);
  36614. };
  36615. }
  36616. return ColorCorrectionPostProcess;
  36617. })(BABYLON.PostProcess);
  36618. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36619. })(BABYLON || (BABYLON = {}));
  36620. var BABYLON;
  36621. (function (BABYLON) {
  36622. var HDRRenderingPipeline = (function (_super) {
  36623. __extends(HDRRenderingPipeline, _super);
  36624. /**
  36625. * @constructor
  36626. * @param {string} name - The rendering pipeline name
  36627. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36628. * @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)
  36629. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36630. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36631. */
  36632. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36633. var _this = this;
  36634. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36635. _super.call(this, scene.getEngine(), name);
  36636. /**
  36637. * Public members
  36638. */
  36639. // Gaussian Blur
  36640. /**
  36641. * Gaussian blur coefficient
  36642. * @type {number}
  36643. */
  36644. this.gaussCoeff = 0.3;
  36645. /**
  36646. * Gaussian blur mean
  36647. * @type {number}
  36648. */
  36649. this.gaussMean = 1.0;
  36650. /**
  36651. * Gaussian blur standard deviation
  36652. * @type {number}
  36653. */
  36654. this.gaussStandDev = 0.8;
  36655. /**
  36656. * Gaussian blur multiplier. Multiplies the blur effect
  36657. * @type {number}
  36658. */
  36659. this.gaussMultiplier = 4.0;
  36660. // HDR
  36661. /**
  36662. * Exposure, controls the overall intensity of the pipeline
  36663. * @type {number}
  36664. */
  36665. this.exposure = 1.0;
  36666. /**
  36667. * Minimum luminance that the post-process can output. Luminance is >= 0
  36668. * @type {number}
  36669. */
  36670. this.minimumLuminance = 1.0;
  36671. /**
  36672. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36673. * @type {number}
  36674. */
  36675. this.maximumLuminance = 1e20;
  36676. /**
  36677. * Increase rate for luminance: eye adaptation speed to dark
  36678. * @type {number}
  36679. */
  36680. this.luminanceIncreaserate = 0.5;
  36681. /**
  36682. * Decrease rate for luminance: eye adaptation speed to bright
  36683. * @type {number}
  36684. */
  36685. this.luminanceDecreaseRate = 0.5;
  36686. // Bright pass
  36687. /**
  36688. * Minimum luminance needed to compute HDR
  36689. * @type {number}
  36690. */
  36691. this.brightThreshold = 0.8;
  36692. this._needUpdate = true;
  36693. this._scene = scene;
  36694. // Bright pass
  36695. this._createBrightPassPostProcess(scene, ratio);
  36696. // Down sample X4
  36697. this._createDownSampleX4PostProcess(scene, ratio);
  36698. // Create gaussian blur post-processes
  36699. this._createGaussianBlurPostProcess(scene, ratio);
  36700. // Texture adder
  36701. this._createTextureAdderPostProcess(scene, ratio);
  36702. // Luminance generator
  36703. this._createLuminanceGeneratorPostProcess(scene);
  36704. // HDR
  36705. this._createHDRPostProcess(scene, ratio);
  36706. // Pass postprocess
  36707. if (originalPostProcess === null) {
  36708. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36709. }
  36710. else {
  36711. this._originalPostProcess = originalPostProcess;
  36712. }
  36713. // Configure pipeline
  36714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36718. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36720. var addDownSamplerPostProcess = function (id) {
  36721. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36722. };
  36723. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36724. addDownSamplerPostProcess(i);
  36725. }
  36726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36727. // Finish
  36728. scene.postProcessRenderPipelineManager.addPipeline(this);
  36729. if (cameras !== null) {
  36730. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36731. }
  36732. this.update();
  36733. }
  36734. /**
  36735. * Tells the pipeline to update its post-processes
  36736. */
  36737. HDRRenderingPipeline.prototype.update = function () {
  36738. this._needUpdate = true;
  36739. };
  36740. /**
  36741. * Returns the current calculated luminance
  36742. */
  36743. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36744. return this._hdrCurrentLuminance;
  36745. };
  36746. /**
  36747. * Returns the currently drawn luminance
  36748. */
  36749. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36750. return this._hdrOutputLuminance;
  36751. };
  36752. /**
  36753. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36754. */
  36755. HDRRenderingPipeline.prototype.dispose = function () {
  36756. this._originalPostProcess = undefined;
  36757. this._brightPassPostProcess = undefined;
  36758. this._downSampleX4PostProcess = undefined;
  36759. this._guassianBlurHPostProcess = undefined;
  36760. this._guassianBlurVPostProcess = undefined;
  36761. this._textureAdderPostProcess = undefined;
  36762. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36763. this._downSamplePostProcesses[i] = undefined;
  36764. }
  36765. this._hdrPostProcess = undefined;
  36766. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36767. };
  36768. /**
  36769. * Creates the HDR post-process and computes the luminance adaptation
  36770. */
  36771. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36772. var _this = this;
  36773. var hdrLastLuminance = 0.0;
  36774. this._hdrOutputLuminance = -1.0;
  36775. this._hdrCurrentLuminance = 1.0;
  36776. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36777. this._hdrPostProcess.onApply = function (effect) {
  36778. if (_this._hdrOutputLuminance < 0.0) {
  36779. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36780. }
  36781. else {
  36782. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36783. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36784. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36785. }
  36786. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36787. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36788. }
  36789. else {
  36790. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36791. }
  36792. }
  36793. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36794. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36795. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36796. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36797. effect.setFloat("exposure", _this.exposure);
  36798. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36799. _this._needUpdate = false;
  36800. };
  36801. };
  36802. /**
  36803. * Texture Adder post-process
  36804. */
  36805. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36806. var _this = this;
  36807. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36808. this._textureAdderPostProcess.onApply = function (effect) {
  36809. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36810. };
  36811. };
  36812. /**
  36813. * Down sample X4 post-process
  36814. */
  36815. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36816. var _this = this;
  36817. var downSampleX4Offsets = new Array(32);
  36818. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36819. this._downSampleX4PostProcess.onApply = function (effect) {
  36820. if (_this._needUpdate) {
  36821. var id = 0;
  36822. for (var i = -2; i < 2; i++) {
  36823. for (var j = -2; j < 2; j++) {
  36824. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36825. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36826. id += 2;
  36827. }
  36828. }
  36829. }
  36830. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36831. };
  36832. };
  36833. /**
  36834. * Bright pass post-process
  36835. */
  36836. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36837. var _this = this;
  36838. var brightOffsets = new Array(8);
  36839. var brightPassCallback = function (effect) {
  36840. if (_this._needUpdate) {
  36841. var sU = (1.0 / _this._brightPassPostProcess.width);
  36842. var sV = (1.0 / _this._brightPassPostProcess.height);
  36843. brightOffsets[0] = -0.5 * sU;
  36844. brightOffsets[1] = 0.5 * sV;
  36845. brightOffsets[2] = 0.5 * sU;
  36846. brightOffsets[3] = 0.5 * sV;
  36847. brightOffsets[4] = -0.5 * sU;
  36848. brightOffsets[5] = -0.5 * sV;
  36849. brightOffsets[6] = 0.5 * sU;
  36850. brightOffsets[7] = -0.5 * sV;
  36851. }
  36852. effect.setArray2("dsOffsets", brightOffsets);
  36853. effect.setFloat("brightThreshold", _this.brightThreshold);
  36854. };
  36855. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36856. this._brightPassPostProcess.onApply = brightPassCallback;
  36857. };
  36858. /**
  36859. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36860. */
  36861. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36862. var _this = this;
  36863. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36864. var luminanceOffsets = new Array(8);
  36865. var downSampleOffsets = new Array(18);
  36866. var halfDestPixelSize;
  36867. this._downSamplePostProcesses = new Array(lumSteps);
  36868. // Utils for luminance
  36869. var luminanceUpdateSourceOffsets = function (width, height) {
  36870. var sU = (1.0 / width);
  36871. var sV = (1.0 / height);
  36872. luminanceOffsets[0] = -0.5 * sU;
  36873. luminanceOffsets[1] = 0.5 * sV;
  36874. luminanceOffsets[2] = 0.5 * sU;
  36875. luminanceOffsets[3] = 0.5 * sV;
  36876. luminanceOffsets[4] = -0.5 * sU;
  36877. luminanceOffsets[5] = -0.5 * sV;
  36878. luminanceOffsets[6] = 0.5 * sU;
  36879. luminanceOffsets[7] = -0.5 * sV;
  36880. };
  36881. var luminanceUpdateDestOffsets = function (width, height) {
  36882. var id = 0;
  36883. for (var x = -1; x < 2; x++) {
  36884. for (var y = -1; y < 2; y++) {
  36885. downSampleOffsets[id] = (x) / width;
  36886. downSampleOffsets[id + 1] = (y) / height;
  36887. id += 2;
  36888. }
  36889. }
  36890. };
  36891. // Luminance callback
  36892. var luminanceCallback = function (effect) {
  36893. if (_this._needUpdate) {
  36894. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36895. }
  36896. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36897. effect.setArray2("lumOffsets", luminanceOffsets);
  36898. };
  36899. // Down sample callbacks
  36900. var downSampleCallback = function (indice) {
  36901. var i = indice;
  36902. return function (effect) {
  36903. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36904. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36905. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36906. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36907. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36908. effect.setArray2("dsOffsets", downSampleOffsets);
  36909. };
  36910. };
  36911. var downSampleAfterRenderCallback = function (effect) {
  36912. // Unpack result
  36913. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36914. 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);
  36915. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36916. };
  36917. // Create luminance post-process
  36918. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36919. 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);
  36920. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36921. // Create down sample post-processes
  36922. for (var i = lumSteps - 2; i >= 0; i--) {
  36923. var length = Math.pow(3, i);
  36924. ratio = { width: length, height: length };
  36925. var defines = "#define DOWN_SAMPLE\n";
  36926. if (i === 0) {
  36927. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36928. }
  36929. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36930. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36931. if (i === 0) {
  36932. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36933. }
  36934. }
  36935. };
  36936. /**
  36937. * Gaussian blur post-processes. Horizontal and Vertical
  36938. */
  36939. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36940. var _this = this;
  36941. var blurOffsetsW = new Array(9);
  36942. var blurOffsetsH = new Array(9);
  36943. var blurWeights = new Array(9);
  36944. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36945. // Utils for gaussian blur
  36946. var calculateBlurOffsets = function (height) {
  36947. var lastOutputDimensions = {
  36948. width: scene.getEngine().getRenderWidth(),
  36949. height: scene.getEngine().getRenderHeight()
  36950. };
  36951. for (var i = 0; i < 9; i++) {
  36952. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36953. if (height) {
  36954. blurOffsetsH[i] = value;
  36955. }
  36956. else {
  36957. blurOffsetsW[i] = value;
  36958. }
  36959. }
  36960. };
  36961. var calculateWeights = function () {
  36962. var x = 0.0;
  36963. for (var i = 0; i < 9; i++) {
  36964. x = (i - 4.0) / 4.0;
  36965. 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));
  36966. }
  36967. };
  36968. // Callback
  36969. var gaussianBlurCallback = function (height) {
  36970. return function (effect) {
  36971. if (_this._needUpdate) {
  36972. calculateWeights();
  36973. calculateBlurOffsets(height);
  36974. }
  36975. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36976. effect.setArray("blurWeights", blurWeights);
  36977. effect.setFloat("multiplier", _this.gaussMultiplier);
  36978. };
  36979. };
  36980. // Create horizontal gaussian blur post-processes
  36981. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36982. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36983. // Create vertical gaussian blur post-process
  36984. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36985. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36986. };
  36987. // Luminance generator
  36988. HDRRenderingPipeline.LUM_STEPS = 6;
  36989. return HDRRenderingPipeline;
  36990. })(BABYLON.PostProcessRenderPipeline);
  36991. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36992. })(BABYLON || (BABYLON = {}));
  36993. var BABYLON;
  36994. (function (BABYLON) {
  36995. var FaceAdjacencies = (function () {
  36996. function FaceAdjacencies() {
  36997. this.edges = new Array();
  36998. this.edgesConnectedCount = 0;
  36999. }
  37000. return FaceAdjacencies;
  37001. })();
  37002. var EdgesRenderer = (function () {
  37003. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37004. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37005. if (epsilon === void 0) { epsilon = 0.95; }
  37006. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37007. this.edgesWidthScalerForOrthographic = 1000.0;
  37008. this.edgesWidthScalerForPerspective = 50.0;
  37009. this._linesPositions = new Array();
  37010. this._linesNormals = new Array();
  37011. this._linesIndices = new Array();
  37012. this._buffers = new Array();
  37013. this._checkVerticesInsteadOfIndices = false;
  37014. this._source = source;
  37015. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37016. this._epsilon = epsilon;
  37017. this._prepareRessources();
  37018. this._generateEdgesLines();
  37019. }
  37020. EdgesRenderer.prototype._prepareRessources = function () {
  37021. if (this._lineShader) {
  37022. return;
  37023. }
  37024. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37025. attributes: ["position", "normal"],
  37026. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37027. });
  37028. this._lineShader.disableDepthWrite = true;
  37029. this._lineShader.backFaceCulling = false;
  37030. };
  37031. EdgesRenderer.prototype.dispose = function () {
  37032. this._vb0.dispose();
  37033. this._vb1.dispose();
  37034. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37035. this._lineShader.dispose();
  37036. };
  37037. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37038. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37039. return 0;
  37040. }
  37041. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37042. return 1;
  37043. }
  37044. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37045. return 2;
  37046. }
  37047. return -1;
  37048. };
  37049. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37050. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37051. return 0;
  37052. }
  37053. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37054. return 1;
  37055. }
  37056. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37057. return 2;
  37058. }
  37059. return -1;
  37060. };
  37061. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37062. var needToCreateLine;
  37063. if (edge === undefined) {
  37064. needToCreateLine = true;
  37065. }
  37066. else {
  37067. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37068. needToCreateLine = dotProduct < this._epsilon;
  37069. }
  37070. if (needToCreateLine) {
  37071. var offset = this._linesPositions.length / 3;
  37072. var normal = p0.subtract(p1);
  37073. normal.normalize();
  37074. // Positions
  37075. this._linesPositions.push(p0.x);
  37076. this._linesPositions.push(p0.y);
  37077. this._linesPositions.push(p0.z);
  37078. this._linesPositions.push(p0.x);
  37079. this._linesPositions.push(p0.y);
  37080. this._linesPositions.push(p0.z);
  37081. this._linesPositions.push(p1.x);
  37082. this._linesPositions.push(p1.y);
  37083. this._linesPositions.push(p1.z);
  37084. this._linesPositions.push(p1.x);
  37085. this._linesPositions.push(p1.y);
  37086. this._linesPositions.push(p1.z);
  37087. // Normals
  37088. this._linesNormals.push(p1.x);
  37089. this._linesNormals.push(p1.y);
  37090. this._linesNormals.push(p1.z);
  37091. this._linesNormals.push(-1);
  37092. this._linesNormals.push(p1.x);
  37093. this._linesNormals.push(p1.y);
  37094. this._linesNormals.push(p1.z);
  37095. this._linesNormals.push(1);
  37096. this._linesNormals.push(p0.x);
  37097. this._linesNormals.push(p0.y);
  37098. this._linesNormals.push(p0.z);
  37099. this._linesNormals.push(-1);
  37100. this._linesNormals.push(p0.x);
  37101. this._linesNormals.push(p0.y);
  37102. this._linesNormals.push(p0.z);
  37103. this._linesNormals.push(1);
  37104. // Indices
  37105. this._linesIndices.push(offset);
  37106. this._linesIndices.push(offset + 1);
  37107. this._linesIndices.push(offset + 2);
  37108. this._linesIndices.push(offset);
  37109. this._linesIndices.push(offset + 2);
  37110. this._linesIndices.push(offset + 3);
  37111. }
  37112. };
  37113. EdgesRenderer.prototype._generateEdgesLines = function () {
  37114. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37115. var indices = this._source.getIndices();
  37116. // First let's find adjacencies
  37117. var adjacencies = new Array();
  37118. var faceNormals = new Array();
  37119. var index;
  37120. var faceAdjacencies;
  37121. // Prepare faces
  37122. for (index = 0; index < indices.length; index += 3) {
  37123. faceAdjacencies = new FaceAdjacencies();
  37124. var p0Index = indices[index];
  37125. var p1Index = indices[index + 1];
  37126. var p2Index = indices[index + 2];
  37127. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37128. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37129. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37130. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37131. faceNormal.normalize();
  37132. faceNormals.push(faceNormal);
  37133. adjacencies.push(faceAdjacencies);
  37134. }
  37135. // Scan
  37136. for (index = 0; index < adjacencies.length; index++) {
  37137. faceAdjacencies = adjacencies[index];
  37138. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37139. var otherFaceAdjacencies = adjacencies[otherIndex];
  37140. if (faceAdjacencies.edgesConnectedCount === 3) {
  37141. break;
  37142. }
  37143. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37144. continue;
  37145. }
  37146. var otherP0 = indices[otherIndex * 3];
  37147. var otherP1 = indices[otherIndex * 3 + 1];
  37148. var otherP2 = indices[otherIndex * 3 + 2];
  37149. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37150. var otherEdgeIndex;
  37151. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37152. continue;
  37153. }
  37154. switch (edgeIndex) {
  37155. case 0:
  37156. if (this._checkVerticesInsteadOfIndices) {
  37157. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37158. }
  37159. else {
  37160. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37161. }
  37162. break;
  37163. case 1:
  37164. if (this._checkVerticesInsteadOfIndices) {
  37165. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37166. }
  37167. else {
  37168. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37169. }
  37170. break;
  37171. case 2:
  37172. if (this._checkVerticesInsteadOfIndices) {
  37173. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37174. }
  37175. else {
  37176. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37177. }
  37178. break;
  37179. }
  37180. if (otherEdgeIndex === -1) {
  37181. continue;
  37182. }
  37183. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37184. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37185. faceAdjacencies.edgesConnectedCount++;
  37186. otherFaceAdjacencies.edgesConnectedCount++;
  37187. if (faceAdjacencies.edgesConnectedCount === 3) {
  37188. break;
  37189. }
  37190. }
  37191. }
  37192. }
  37193. // Create lines
  37194. for (index = 0; index < adjacencies.length; index++) {
  37195. // 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
  37196. var current = adjacencies[index];
  37197. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37198. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37199. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37200. }
  37201. // Merge into a single mesh
  37202. var engine = this._source.getScene().getEngine();
  37203. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37204. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37205. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37206. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37207. this._ib = engine.createIndexBuffer(this._linesIndices);
  37208. this._indicesCount = this._linesIndices.length;
  37209. };
  37210. EdgesRenderer.prototype.render = function () {
  37211. if (!this._lineShader.isReady()) {
  37212. return;
  37213. }
  37214. var scene = this._source.getScene();
  37215. var engine = scene.getEngine();
  37216. this._lineShader._preBind();
  37217. // VBOs
  37218. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37219. scene.resetCachedMaterial();
  37220. this._lineShader.setColor4("color", this._source.edgesColor);
  37221. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37222. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37223. }
  37224. else {
  37225. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37226. }
  37227. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37228. this._lineShader.bind(this._source.getWorldMatrix());
  37229. // Draw order
  37230. engine.draw(true, 0, this._indicesCount);
  37231. this._lineShader.unbind();
  37232. engine.setDepthWrite(true);
  37233. };
  37234. return EdgesRenderer;
  37235. })();
  37236. BABYLON.EdgesRenderer = EdgesRenderer;
  37237. })(BABYLON || (BABYLON = {}));
  37238. var BABYLON;
  37239. (function (BABYLON) {
  37240. (function (TonemappingOperator) {
  37241. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37242. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37243. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37244. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37245. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37246. var TonemappingOperator = BABYLON.TonemappingOperator;
  37247. ;
  37248. var TonemapPostProcess = (function (_super) {
  37249. __extends(TonemapPostProcess, _super);
  37250. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37251. var _this = this;
  37252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37253. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37254. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37255. this._operator = _operator;
  37256. this.exposureAdjustment = exposureAdjustment;
  37257. var defines = "#define ";
  37258. if (this._operator === TonemappingOperator.Hable)
  37259. defines += "HABLE_TONEMAPPING";
  37260. else if (this._operator === TonemappingOperator.Reinhard)
  37261. defines += "REINHARD_TONEMAPPING";
  37262. else if (this._operator === TonemappingOperator.HejiDawson)
  37263. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37264. else if (this._operator === TonemappingOperator.Photographic)
  37265. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37266. //sadly a second call to create the effect.
  37267. this.updateEffect(defines);
  37268. this.onApply = function (effect) {
  37269. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37270. };
  37271. }
  37272. return TonemapPostProcess;
  37273. })(BABYLON.PostProcess);
  37274. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37275. })(BABYLON || (BABYLON = {}));
  37276. var BABYLON;
  37277. (function (BABYLON) {
  37278. var ReflectionProbe = (function () {
  37279. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37280. var _this = this;
  37281. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37282. this.name = name;
  37283. this._viewMatrix = BABYLON.Matrix.Identity();
  37284. this._target = BABYLON.Vector3.Zero();
  37285. this._add = BABYLON.Vector3.Zero();
  37286. this.position = BABYLON.Vector3.Zero();
  37287. this._scene = scene;
  37288. this._scene.reflectionProbes.push(this);
  37289. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37290. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37291. switch (faceIndex) {
  37292. case 0:
  37293. _this._add.copyFromFloats(1, 0, 0);
  37294. break;
  37295. case 1:
  37296. _this._add.copyFromFloats(-1, 0, 0);
  37297. break;
  37298. case 2:
  37299. _this._add.copyFromFloats(0, -1, 0);
  37300. break;
  37301. case 3:
  37302. _this._add.copyFromFloats(0, 1, 0);
  37303. break;
  37304. case 4:
  37305. _this._add.copyFromFloats(0, 0, 1);
  37306. break;
  37307. case 5:
  37308. _this._add.copyFromFloats(0, 0, -1);
  37309. break;
  37310. }
  37311. if (_this._attachedMesh) {
  37312. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37313. }
  37314. _this.position.addToRef(_this._add, _this._target);
  37315. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37316. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37317. };
  37318. this._renderTargetTexture.onAfterUnbind = function () {
  37319. scene.updateTransformMatrix(true);
  37320. };
  37321. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37322. }
  37323. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37324. get: function () {
  37325. return this._renderTargetTexture.refreshRate;
  37326. },
  37327. set: function (value) {
  37328. this._renderTargetTexture.refreshRate = value;
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. ReflectionProbe.prototype.getScene = function () {
  37334. return this._scene;
  37335. };
  37336. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37337. get: function () {
  37338. return this._renderTargetTexture;
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37344. get: function () {
  37345. return this._renderTargetTexture.renderList;
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37351. this._attachedMesh = mesh;
  37352. };
  37353. ReflectionProbe.prototype.dispose = function () {
  37354. var index = this._scene.reflectionProbes.indexOf(this);
  37355. if (index !== -1) {
  37356. // Remove from the scene if found
  37357. this._scene.reflectionProbes.splice(index, 1);
  37358. }
  37359. if (this._renderTargetTexture) {
  37360. this._renderTargetTexture.dispose();
  37361. this._renderTargetTexture = null;
  37362. }
  37363. };
  37364. return ReflectionProbe;
  37365. })();
  37366. BABYLON.ReflectionProbe = ReflectionProbe;
  37367. })(BABYLON || (BABYLON = {}));
  37368. var BABYLON;
  37369. (function (BABYLON) {
  37370. var SolidParticle = (function () {
  37371. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37372. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37373. this.position = BABYLON.Vector3.Zero(); // position
  37374. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37375. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37376. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37377. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37378. this.alive = true; // alive
  37379. this.idx = particleIndex;
  37380. this._pos = positionIndex;
  37381. this._model = model;
  37382. this.shapeId = shapeId;
  37383. this.idxInShape = idxInShape;
  37384. }
  37385. return SolidParticle;
  37386. })();
  37387. BABYLON.SolidParticle = SolidParticle;
  37388. var ModelShape = (function () {
  37389. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37390. this.shapeID = id;
  37391. this._shape = shape;
  37392. this._shapeUV = shapeUV;
  37393. this._positionFunction = posFunction;
  37394. this._vertexFunction = vtxFunction;
  37395. }
  37396. return ModelShape;
  37397. })();
  37398. BABYLON.ModelShape = ModelShape;
  37399. })(BABYLON || (BABYLON = {}));
  37400. var BABYLON;
  37401. (function (BABYLON) {
  37402. /**
  37403. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37404. */
  37405. var SolidParticleSystem = (function () {
  37406. /**
  37407. * Creates a SPS (Solid Particle System) object.
  37408. * @param name the SPS name, this will be the underlying mesh name
  37409. * @param scene the scene in which the SPS is added
  37410. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37411. */
  37412. function SolidParticleSystem(name, scene, options) {
  37413. // public members
  37414. /**
  37415. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37416. * Example : var p = SPS.particles[i];
  37417. */
  37418. this.particles = new Array();
  37419. /**
  37420. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37421. */
  37422. this.nbParticles = 0;
  37423. /**
  37424. * If the particles must ever face the camera (default false). Useful for planar particles.
  37425. */
  37426. this.billboard = false;
  37427. /**
  37428. * This a counter ofr your own usage. It's not set by any SPS functions.
  37429. */
  37430. this.counter = 0;
  37431. /**
  37432. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37433. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37434. */
  37435. this.vars = {};
  37436. this._positions = new Array();
  37437. this._indices = new Array();
  37438. this._normals = new Array();
  37439. this._colors = new Array();
  37440. this._uvs = new Array();
  37441. this._index = 0; // indices index
  37442. this._updatable = true;
  37443. this._pickable = false;
  37444. this._isVisibilityBoxLocked = false;
  37445. this._alwaysVisible = false;
  37446. this._shapeCounter = 0;
  37447. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37448. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37449. this._computeParticleColor = true;
  37450. this._computeParticleTexture = true;
  37451. this._computeParticleRotation = true;
  37452. this._computeParticleVertex = false;
  37453. this._computeBoundingBox = false;
  37454. this._cam_axisZ = BABYLON.Vector3.Zero();
  37455. this._cam_axisY = BABYLON.Vector3.Zero();
  37456. this._cam_axisX = BABYLON.Vector3.Zero();
  37457. this._axisX = BABYLON.Axis.X;
  37458. this._axisY = BABYLON.Axis.Y;
  37459. this._axisZ = BABYLON.Axis.Z;
  37460. this._fakeCamPos = BABYLON.Vector3.Zero();
  37461. this._rotMatrix = new BABYLON.Matrix();
  37462. this._invertMatrix = new BABYLON.Matrix();
  37463. this._rotated = BABYLON.Vector3.Zero();
  37464. this._quaternion = new BABYLON.Quaternion();
  37465. this._vertex = BABYLON.Vector3.Zero();
  37466. this._normal = BABYLON.Vector3.Zero();
  37467. this._yaw = 0.0;
  37468. this._pitch = 0.0;
  37469. this._roll = 0.0;
  37470. this._halfroll = 0.0;
  37471. this._halfpitch = 0.0;
  37472. this._halfyaw = 0.0;
  37473. this._sinRoll = 0.0;
  37474. this._cosRoll = 0.0;
  37475. this._sinPitch = 0.0;
  37476. this._cosPitch = 0.0;
  37477. this._sinYaw = 0.0;
  37478. this._cosYaw = 0.0;
  37479. this._w = 0.0;
  37480. this._minimum = BABYLON.Tmp.Vector3[0];
  37481. this._maximum = BABYLON.Tmp.Vector3[1];
  37482. this.name = name;
  37483. this._scene = scene;
  37484. this._camera = scene.activeCamera;
  37485. this._pickable = options ? options.isPickable : false;
  37486. if (options && options.updatable) {
  37487. this._updatable = options.updatable;
  37488. }
  37489. else {
  37490. this._updatable = true;
  37491. }
  37492. if (this._pickable) {
  37493. this.pickedParticles = [];
  37494. }
  37495. }
  37496. /**
  37497. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37498. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37499. */
  37500. SolidParticleSystem.prototype.buildMesh = function () {
  37501. if (this.nbParticles === 0) {
  37502. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37503. this.addShape(triangle, 1);
  37504. triangle.dispose();
  37505. }
  37506. this._positions32 = new Float32Array(this._positions);
  37507. this._uvs32 = new Float32Array(this._uvs);
  37508. this._colors32 = new Float32Array(this._colors);
  37509. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37510. this._normals32 = new Float32Array(this._normals);
  37511. this._fixedNormal32 = new Float32Array(this._normals);
  37512. var vertexData = new BABYLON.VertexData();
  37513. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37514. vertexData.indices = this._indices;
  37515. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37516. if (this._uvs32) {
  37517. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37518. ;
  37519. }
  37520. if (this._colors32) {
  37521. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37522. }
  37523. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37524. vertexData.applyToMesh(mesh, this._updatable);
  37525. this.mesh = mesh;
  37526. this.mesh.isPickable = this._pickable;
  37527. // free memory
  37528. this._positions = null;
  37529. this._normals = null;
  37530. this._uvs = null;
  37531. this._colors = null;
  37532. if (!this._updatable) {
  37533. this.particles.length = 0;
  37534. }
  37535. return mesh;
  37536. };
  37537. /**
  37538. * Digests the mesh and generates as many solid particles in the system as wanted.
  37539. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37540. * Thus the particles generated from digest() have their property "positiion" yet set.
  37541. * @param mesh the mesh to be digested
  37542. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37543. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37544. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37545. */
  37546. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37547. var size = (options && options.facetNb) || 1;
  37548. var number = (options && options.number);
  37549. var delta = (options && options.delta) || 0;
  37550. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37551. var meshInd = mesh.getIndices();
  37552. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37553. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37554. var f = 0; // facet counter
  37555. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37556. // compute size from number
  37557. if (number) {
  37558. number = (number > totalFacets) ? totalFacets : number;
  37559. size = Math.round(totalFacets / number);
  37560. delta = 0;
  37561. }
  37562. else {
  37563. size = (size > totalFacets) ? totalFacets : size;
  37564. }
  37565. var facetPos = []; // submesh positions
  37566. var facetInd = []; // submesh indices
  37567. var facetUV = []; // submesh UV
  37568. var facetCol = []; // submesh colors
  37569. var barycenter = BABYLON.Tmp.Vector3[0];
  37570. var rand;
  37571. var sizeO = size;
  37572. while (f < totalFacets) {
  37573. size = sizeO + Math.floor((1 + delta) * Math.random());
  37574. if (f > totalFacets - size) {
  37575. size = totalFacets - f;
  37576. }
  37577. // reset temp arrays
  37578. facetPos.length = 0;
  37579. facetInd.length = 0;
  37580. facetUV.length = 0;
  37581. facetCol.length = 0;
  37582. // iterate over "size" facets
  37583. var fi = 0;
  37584. for (var j = f * 3; j < (f + size) * 3; j++) {
  37585. facetInd.push(fi);
  37586. var i = meshInd[j];
  37587. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37588. if (meshUV) {
  37589. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37590. }
  37591. if (meshCol) {
  37592. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37593. }
  37594. fi++;
  37595. }
  37596. // create a model shape for each single particle
  37597. var idx = this.nbParticles;
  37598. var shape = this._posToShape(facetPos);
  37599. var shapeUV = this._uvsToShapeUV(facetUV);
  37600. // compute the barycenter of the shape
  37601. var v;
  37602. for (v = 0; v < shape.length; v++) {
  37603. barycenter.addInPlace(shape[v]);
  37604. }
  37605. barycenter.scaleInPlace(1 / shape.length);
  37606. // shift the shape from its barycenter to the origin
  37607. for (v = 0; v < shape.length; v++) {
  37608. shape[v].subtractInPlace(barycenter);
  37609. }
  37610. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37611. // add the particle in the SPS
  37612. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37613. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37614. // initialize the particle position
  37615. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37616. this._index += shape.length;
  37617. idx++;
  37618. this.nbParticles++;
  37619. this._shapeCounter++;
  37620. f += size;
  37621. }
  37622. };
  37623. //reset copy
  37624. SolidParticleSystem.prototype._resetCopy = function () {
  37625. this._copy.position.x = 0;
  37626. this._copy.position.y = 0;
  37627. this._copy.position.z = 0;
  37628. this._copy.rotation.x = 0;
  37629. this._copy.rotation.y = 0;
  37630. this._copy.rotation.z = 0;
  37631. this._copy.quaternion = null;
  37632. this._copy.scale.x = 1;
  37633. this._copy.scale.y = 1;
  37634. this._copy.scale.z = 1;
  37635. this._copy.uvs.x = 0;
  37636. this._copy.uvs.y = 0;
  37637. this._copy.uvs.z = 1;
  37638. this._copy.uvs.w = 1;
  37639. this._copy.color = null;
  37640. };
  37641. // _meshBuilder : inserts the shape model in the global SPS mesh
  37642. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37643. var i;
  37644. var u = 0;
  37645. var c = 0;
  37646. this._resetCopy();
  37647. if (options && options.positionFunction) {
  37648. options.positionFunction(this._copy, idx, idxInShape);
  37649. }
  37650. if (this._copy.quaternion) {
  37651. this._quaternion.x = this._copy.quaternion.x;
  37652. this._quaternion.y = this._copy.quaternion.y;
  37653. this._quaternion.z = this._copy.quaternion.z;
  37654. this._quaternion.w = this._copy.quaternion.w;
  37655. }
  37656. else {
  37657. this._yaw = this._copy.rotation.y;
  37658. this._pitch = this._copy.rotation.x;
  37659. this._roll = this._copy.rotation.z;
  37660. this._quaternionRotationYPR();
  37661. }
  37662. this._quaternionToRotationMatrix();
  37663. for (i = 0; i < shape.length; i++) {
  37664. this._vertex.x = shape[i].x;
  37665. this._vertex.y = shape[i].y;
  37666. this._vertex.z = shape[i].z;
  37667. if (options && options.vertexFunction) {
  37668. options.vertexFunction(this._copy, this._vertex, i);
  37669. }
  37670. this._vertex.x *= this._copy.scale.x;
  37671. this._vertex.y *= this._copy.scale.y;
  37672. this._vertex.z *= this._copy.scale.z;
  37673. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37674. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37675. if (meshUV) {
  37676. 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);
  37677. u += 2;
  37678. }
  37679. if (this._copy.color) {
  37680. this._color = this._copy.color;
  37681. }
  37682. else if (meshCol && meshCol[c]) {
  37683. this._color.r = meshCol[c];
  37684. this._color.g = meshCol[c + 1];
  37685. this._color.b = meshCol[c + 2];
  37686. this._color.a = meshCol[c + 3];
  37687. }
  37688. else {
  37689. this._color.r = 1;
  37690. this._color.g = 1;
  37691. this._color.b = 1;
  37692. this._color.a = 1;
  37693. }
  37694. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37695. c += 4;
  37696. }
  37697. for (i = 0; i < meshInd.length; i++) {
  37698. indices.push(p + meshInd[i]);
  37699. }
  37700. if (this._pickable) {
  37701. var nbfaces = meshInd.length / 3;
  37702. for (i = 0; i < nbfaces; i++) {
  37703. this.pickedParticles.push({ idx: idx, faceId: i });
  37704. }
  37705. }
  37706. };
  37707. // returns a shape array from positions array
  37708. SolidParticleSystem.prototype._posToShape = function (positions) {
  37709. var shape = [];
  37710. for (var i = 0; i < positions.length; i += 3) {
  37711. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37712. }
  37713. return shape;
  37714. };
  37715. // returns a shapeUV array from a Vector4 uvs
  37716. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37717. var shapeUV = [];
  37718. if (uvs) {
  37719. for (var i = 0; i < uvs.length; i++)
  37720. shapeUV.push(uvs[i]);
  37721. }
  37722. return shapeUV;
  37723. };
  37724. // adds a new particle object in the particles array
  37725. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37726. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37727. };
  37728. /**
  37729. * Adds some particles to the SPS from the model shape.
  37730. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37731. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37732. * @param nb the number of particles to be created from this model
  37733. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37734. */
  37735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37737. var meshInd = mesh.getIndices();
  37738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37740. var shape = this._posToShape(meshPos);
  37741. var shapeUV = this._uvsToShapeUV(meshUV);
  37742. var posfunc = options ? options.positionFunction : null;
  37743. var vtxfunc = options ? options.vertexFunction : null;
  37744. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37745. // particles
  37746. var idx = this.nbParticles;
  37747. for (var i = 0; i < nb; i++) {
  37748. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37749. if (this._updatable) {
  37750. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37751. }
  37752. this._index += shape.length;
  37753. idx++;
  37754. }
  37755. this.nbParticles += nb;
  37756. this._shapeCounter++;
  37757. return this._shapeCounter - 1;
  37758. };
  37759. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37760. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37761. this._resetCopy();
  37762. if (particle._model._positionFunction) {
  37763. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37764. }
  37765. if (this._copy.quaternion) {
  37766. this._quaternion.x = this._copy.quaternion.x;
  37767. this._quaternion.y = this._copy.quaternion.y;
  37768. this._quaternion.z = this._copy.quaternion.z;
  37769. this._quaternion.w = this._copy.quaternion.w;
  37770. }
  37771. else {
  37772. this._yaw = this._copy.rotation.y;
  37773. this._pitch = this._copy.rotation.x;
  37774. this._roll = this._copy.rotation.z;
  37775. this._quaternionRotationYPR();
  37776. }
  37777. this._quaternionToRotationMatrix();
  37778. this._shape = particle._model._shape;
  37779. for (var pt = 0; pt < this._shape.length; pt++) {
  37780. this._vertex.x = this._shape[pt].x;
  37781. this._vertex.y = this._shape[pt].y;
  37782. this._vertex.z = this._shape[pt].z;
  37783. if (particle._model._vertexFunction) {
  37784. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37785. }
  37786. this._vertex.x *= this._copy.scale.x;
  37787. this._vertex.y *= this._copy.scale.y;
  37788. this._vertex.z *= this._copy.scale.z;
  37789. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37790. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37791. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37792. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37793. }
  37794. particle.position.x = 0;
  37795. particle.position.y = 0;
  37796. particle.position.z = 0;
  37797. particle.rotation.x = 0;
  37798. particle.rotation.y = 0;
  37799. particle.rotation.z = 0;
  37800. particle.quaternion = null;
  37801. particle.scale.x = 1;
  37802. particle.scale.y = 1;
  37803. particle.scale.z = 1;
  37804. };
  37805. /**
  37806. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37807. */
  37808. SolidParticleSystem.prototype.rebuildMesh = function () {
  37809. for (var p = 0; p < this.particles.length; p++) {
  37810. this._rebuildParticle(this.particles[p]);
  37811. }
  37812. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37813. };
  37814. /**
  37815. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37816. * This method calls updateParticle() for each particles of the SPS.
  37817. * For an animated SPS, it is usually called within the render loop.
  37818. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37819. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37820. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37821. */
  37822. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37823. if (start === void 0) { start = 0; }
  37824. if (end === void 0) { end = this.nbParticles - 1; }
  37825. if (update === void 0) { update = true; }
  37826. if (!this._updatable) {
  37827. return;
  37828. }
  37829. // custom beforeUpdate
  37830. this.beforeUpdateParticles(start, end, update);
  37831. this._cam_axisX.x = 1;
  37832. this._cam_axisX.y = 0;
  37833. this._cam_axisX.z = 0;
  37834. this._cam_axisY.x = 0;
  37835. this._cam_axisY.y = 1;
  37836. this._cam_axisY.z = 0;
  37837. this._cam_axisZ.x = 0;
  37838. this._cam_axisZ.y = 0;
  37839. this._cam_axisZ.z = 1;
  37840. // if the particles will always face the camera
  37841. if (this.billboard) {
  37842. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37843. this._yaw = this.mesh.rotation.y;
  37844. this._pitch = this.mesh.rotation.x;
  37845. this._roll = this.mesh.rotation.z;
  37846. this._quaternionRotationYPR();
  37847. this._quaternionToRotationMatrix();
  37848. this._rotMatrix.invertToRef(this._invertMatrix);
  37849. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37850. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37851. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37852. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37853. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37854. this._cam_axisY.normalize();
  37855. this._cam_axisX.normalize();
  37856. this._cam_axisZ.normalize();
  37857. }
  37858. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37859. var idx = 0;
  37860. var index = 0;
  37861. var colidx = 0;
  37862. var colorIndex = 0;
  37863. var uvidx = 0;
  37864. var uvIndex = 0;
  37865. if (this._computeBoundingBox) {
  37866. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37867. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37868. }
  37869. // particle loop
  37870. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37871. for (var p = start; p <= end; p++) {
  37872. this._particle = this.particles[p];
  37873. this._shape = this._particle._model._shape;
  37874. this._shapeUV = this._particle._model._shapeUV;
  37875. // call to custom user function to update the particle properties
  37876. this.updateParticle(this._particle);
  37877. // particle rotation matrix
  37878. if (this.billboard) {
  37879. this._particle.rotation.x = 0.0;
  37880. this._particle.rotation.y = 0.0;
  37881. }
  37882. if (this._computeParticleRotation) {
  37883. if (this._particle.quaternion) {
  37884. this._quaternion.x = this._particle.quaternion.x;
  37885. this._quaternion.y = this._particle.quaternion.y;
  37886. this._quaternion.z = this._particle.quaternion.z;
  37887. this._quaternion.w = this._particle.quaternion.w;
  37888. }
  37889. else {
  37890. this._yaw = this._particle.rotation.y;
  37891. this._pitch = this._particle.rotation.x;
  37892. this._roll = this._particle.rotation.z;
  37893. this._quaternionRotationYPR();
  37894. }
  37895. this._quaternionToRotationMatrix();
  37896. }
  37897. for (var pt = 0; pt < this._shape.length; pt++) {
  37898. idx = index + pt * 3;
  37899. colidx = colorIndex + pt * 4;
  37900. uvidx = uvIndex + pt * 2;
  37901. this._vertex.x = this._shape[pt].x;
  37902. this._vertex.y = this._shape[pt].y;
  37903. this._vertex.z = this._shape[pt].z;
  37904. if (this._computeParticleVertex) {
  37905. this.updateParticleVertex(this._particle, this._vertex, pt);
  37906. }
  37907. // positions
  37908. this._vertex.x *= this._particle.scale.x;
  37909. this._vertex.y *= this._particle.scale.y;
  37910. this._vertex.z *= this._particle.scale.z;
  37911. 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];
  37912. 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;
  37913. 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;
  37914. 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;
  37915. 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;
  37916. 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;
  37917. 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;
  37918. if (this._computeBoundingBox) {
  37919. if (this._positions32[idx] < this._minimum.x) {
  37920. this._minimum.x = this._positions32[idx];
  37921. }
  37922. if (this._positions32[idx] > this._maximum.x) {
  37923. this._maximum.x = this._positions32[idx];
  37924. }
  37925. if (this._positions32[idx + 1] < this._minimum.y) {
  37926. this._minimum.y = this._positions32[idx + 1];
  37927. }
  37928. if (this._positions32[idx + 1] > this._maximum.y) {
  37929. this._maximum.y = this._positions32[idx + 1];
  37930. }
  37931. if (this._positions32[idx + 2] < this._minimum.z) {
  37932. this._minimum.z = this._positions32[idx + 2];
  37933. }
  37934. if (this._positions32[idx + 2] > this._maximum.z) {
  37935. this._maximum.z = this._positions32[idx + 2];
  37936. }
  37937. }
  37938. // normals : if the particles can't be morphed then just rotate the normals
  37939. if (!this._computeParticleVertex && !this.billboard) {
  37940. this._normal.x = this._fixedNormal32[idx];
  37941. this._normal.y = this._fixedNormal32[idx + 1];
  37942. this._normal.z = this._fixedNormal32[idx + 2];
  37943. 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];
  37944. 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;
  37945. 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;
  37946. 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;
  37947. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37948. 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;
  37949. 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;
  37950. }
  37951. if (this._computeParticleColor) {
  37952. this._colors32[colidx] = this._particle.color.r;
  37953. this._colors32[colidx + 1] = this._particle.color.g;
  37954. this._colors32[colidx + 2] = this._particle.color.b;
  37955. this._colors32[colidx + 3] = this._particle.color.a;
  37956. }
  37957. if (this._computeParticleTexture) {
  37958. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37959. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37960. }
  37961. }
  37962. index = idx + 3;
  37963. colorIndex = colidx + 4;
  37964. uvIndex = uvidx + 2;
  37965. }
  37966. if (update) {
  37967. if (this._computeParticleColor) {
  37968. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37969. }
  37970. if (this._computeParticleTexture) {
  37971. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37972. }
  37973. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37974. if (!this.mesh.areNormalsFrozen) {
  37975. if (this._computeParticleVertex || this.billboard) {
  37976. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37977. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37978. for (var i = 0; i < this._normals32.length; i++) {
  37979. this._fixedNormal32[i] = this._normals32[i];
  37980. }
  37981. }
  37982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37983. }
  37984. }
  37985. if (this._computeBoundingBox) {
  37986. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37987. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37988. }
  37989. this.afterUpdateParticles(start, end, update);
  37990. };
  37991. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37992. this._halfroll = this._roll * 0.5;
  37993. this._halfpitch = this._pitch * 0.5;
  37994. this._halfyaw = this._yaw * 0.5;
  37995. this._sinRoll = Math.sin(this._halfroll);
  37996. this._cosRoll = Math.cos(this._halfroll);
  37997. this._sinPitch = Math.sin(this._halfpitch);
  37998. this._cosPitch = Math.cos(this._halfpitch);
  37999. this._sinYaw = Math.sin(this._halfyaw);
  38000. this._cosYaw = Math.cos(this._halfyaw);
  38001. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38002. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38003. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38004. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38005. };
  38006. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38007. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38008. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38009. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38010. this._rotMatrix.m[3] = 0;
  38011. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38012. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38013. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38014. this._rotMatrix.m[7] = 0;
  38015. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38016. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38017. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38018. this._rotMatrix.m[11] = 0;
  38019. this._rotMatrix.m[12] = 0;
  38020. this._rotMatrix.m[13] = 0;
  38021. this._rotMatrix.m[14] = 0;
  38022. this._rotMatrix.m[15] = 1.0;
  38023. };
  38024. /**
  38025. * Disposes the SPS
  38026. */
  38027. SolidParticleSystem.prototype.dispose = function () {
  38028. this.mesh.dispose();
  38029. this.vars = null;
  38030. // drop references to internal big arrays for the GC
  38031. this._positions = null;
  38032. this._indices = null;
  38033. this._normals = null;
  38034. this._uvs = null;
  38035. this._colors = null;
  38036. this._positions32 = null;
  38037. this._normals32 = null;
  38038. this._fixedNormal32 = null;
  38039. this._uvs32 = null;
  38040. this._colors32 = null;
  38041. this.pickedParticles = null;
  38042. };
  38043. /**
  38044. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38045. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38046. */
  38047. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38048. if (!this._isVisibilityBoxLocked) {
  38049. this.mesh.refreshBoundingInfo();
  38050. }
  38051. };
  38052. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38053. * @param size the size (float) of the visibility box
  38054. * note : this doesn't lock the SPS mesh bounding box.
  38055. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38056. */
  38057. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38058. var vis = size / 2;
  38059. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38060. };
  38061. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38062. // getter and setter
  38063. /**
  38064. * True if the SPS is set as always visible
  38065. */
  38066. get: function () {
  38067. return this._alwaysVisible;
  38068. },
  38069. /**
  38070. * Sets the SPS as always visible or not
  38071. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38072. */
  38073. set: function (val) {
  38074. this._alwaysVisible = val;
  38075. this.mesh.alwaysSelectAsActiveMesh = val;
  38076. },
  38077. enumerable: true,
  38078. configurable: true
  38079. });
  38080. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38081. /**
  38082. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38083. */
  38084. get: function () {
  38085. return this._isVisibilityBoxLocked;
  38086. },
  38087. /**
  38088. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38089. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38090. */
  38091. set: function (val) {
  38092. this._isVisibilityBoxLocked = val;
  38093. this.mesh.getBoundingInfo().isLocked = val;
  38094. },
  38095. enumerable: true,
  38096. configurable: true
  38097. });
  38098. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38099. // getters
  38100. get: function () {
  38101. return this._computeParticleRotation;
  38102. },
  38103. // Optimizer setters
  38104. /**
  38105. * Tells to setParticles() to compute the particle rotations or not.
  38106. * Default value : true. The SPS is faster when it's set to false.
  38107. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38108. */
  38109. set: function (val) {
  38110. this._computeParticleRotation = val;
  38111. },
  38112. enumerable: true,
  38113. configurable: true
  38114. });
  38115. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38116. get: function () {
  38117. return this._computeParticleColor;
  38118. },
  38119. /**
  38120. * Tells to setParticles() to compute the particle colors or not.
  38121. * Default value : true. The SPS is faster when it's set to false.
  38122. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38123. */
  38124. set: function (val) {
  38125. this._computeParticleColor = val;
  38126. },
  38127. enumerable: true,
  38128. configurable: true
  38129. });
  38130. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38131. get: function () {
  38132. return this._computeParticleTexture;
  38133. },
  38134. /**
  38135. * Tells to setParticles() to compute the particle textures or not.
  38136. * Default value : true. The SPS is faster when it's set to false.
  38137. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38138. */
  38139. set: function (val) {
  38140. this._computeParticleTexture = val;
  38141. },
  38142. enumerable: true,
  38143. configurable: true
  38144. });
  38145. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38146. get: function () {
  38147. return this._computeParticleVertex;
  38148. },
  38149. /**
  38150. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38151. * Default value : false. The SPS is faster when it's set to false.
  38152. * Note : the particle custom vertex positions aren't stored values.
  38153. */
  38154. set: function (val) {
  38155. this._computeParticleVertex = val;
  38156. },
  38157. enumerable: true,
  38158. configurable: true
  38159. });
  38160. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38161. get: function () {
  38162. return this._computeBoundingBox;
  38163. },
  38164. /**
  38165. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38166. */
  38167. set: function (val) {
  38168. this._computeBoundingBox = val;
  38169. },
  38170. enumerable: true,
  38171. configurable: true
  38172. });
  38173. // =======================================================================
  38174. // Particle behavior logic
  38175. // these following methods may be overwritten by the user to fit his needs
  38176. /**
  38177. * This function does nothing. It may be overwritten to set all the particles first values.
  38178. * The SPS doesn't call this function, you may have to call it by your own.
  38179. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38180. */
  38181. SolidParticleSystem.prototype.initParticles = function () {
  38182. };
  38183. /**
  38184. * This function does nothing. It may be overwritten to recycle a particle.
  38185. * The SPS doesn't call this function, you may have to call it by your own.
  38186. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38187. */
  38188. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38189. return particle;
  38190. };
  38191. /**
  38192. * Updates a particle : this function should be overwritten by the user.
  38193. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38194. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38195. * ex : just set a particle position or velocity and recycle conditions
  38196. */
  38197. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38198. return particle;
  38199. };
  38200. /**
  38201. * Updates a vertex of a particle : it can be overwritten by the user.
  38202. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38203. * @param particle the current particle
  38204. * @param vertex the current index of the current particle
  38205. * @param pt the index of the current vertex in the particle shape
  38206. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38207. * ex : just set a vertex particle position
  38208. */
  38209. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38210. return vertex;
  38211. };
  38212. /**
  38213. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38214. * This does nothing and may be overwritten by the user.
  38215. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38216. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38217. * @param update the boolean update value actually passed to setParticles()
  38218. */
  38219. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38220. };
  38221. /**
  38222. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38223. * This will be passed three parameters.
  38224. * This does nothing and may be overwritten by the user.
  38225. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38226. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38227. * @param update the boolean update value actually passed to setParticles()
  38228. */
  38229. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38230. };
  38231. return SolidParticleSystem;
  38232. })();
  38233. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38234. })(BABYLON || (BABYLON = {}));
  38235. var BABYLON;
  38236. (function (BABYLON) {
  38237. // We're mainly based on the logic defined into the FreeCamera code
  38238. var UniversalCamera = (function (_super) {
  38239. __extends(UniversalCamera, _super);
  38240. function UniversalCamera(name, position, scene) {
  38241. var _this = this;
  38242. _super.call(this, name, position, scene);
  38243. this.gamepadAngularSensibility = 200;
  38244. this.gamepadMoveSensibility = 40;
  38245. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38246. }
  38247. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38248. // Only the first gamepad can control the camera
  38249. if (gamepad.index === 0) {
  38250. this.gamepad = gamepad;
  38251. }
  38252. };
  38253. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38254. _super.prototype.attachControl.call(this, canvas, false);
  38255. };
  38256. UniversalCamera.prototype.detachControl = function (canvas) {
  38257. _super.prototype.detachControl.call(this, canvas);
  38258. };
  38259. UniversalCamera.prototype._checkInputs = function () {
  38260. if (this.gamepad) {
  38261. var LSValues = this.gamepad.leftStick;
  38262. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38263. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38264. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38265. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38266. var RSValues = this.gamepad.rightStick;
  38267. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38268. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38269. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38270. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38271. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38272. var speed = this._computeLocalCameraSpeed() * 50.0;
  38273. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38274. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38275. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38276. }
  38277. _super.prototype._checkInputs.call(this);
  38278. };
  38279. UniversalCamera.prototype.dispose = function () {
  38280. this._gamepads.dispose();
  38281. _super.prototype.dispose.call(this);
  38282. };
  38283. UniversalCamera.prototype.getTypeName = function () {
  38284. return "UniversalCamera";
  38285. };
  38286. __decorate([
  38287. BABYLON.serialize()
  38288. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38289. __decorate([
  38290. BABYLON.serialize()
  38291. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38292. return UniversalCamera;
  38293. })(BABYLON.TouchCamera);
  38294. BABYLON.UniversalCamera = UniversalCamera;
  38295. })(BABYLON || (BABYLON = {}));
  38296. var BABYLON;
  38297. (function (BABYLON) {
  38298. var Gamepads = (function () {
  38299. function Gamepads(ongamedpadconnected) {
  38300. var _this = this;
  38301. this.babylonGamepads = [];
  38302. this.oneGamepadConnected = false;
  38303. this.isMonitoring = false;
  38304. this.gamepadEventSupported = 'GamepadEvent' in window;
  38305. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38306. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38307. this._callbackGamepadConnected = ongamedpadconnected;
  38308. if (this.gamepadSupportAvailable) {
  38309. // Checking if the gamepad connected event is supported (like in Firefox)
  38310. if (this.gamepadEventSupported) {
  38311. window.addEventListener('gamepadconnected', function (evt) {
  38312. _this._onGamepadConnected(evt);
  38313. }, false);
  38314. window.addEventListener('gamepaddisconnected', function (evt) {
  38315. _this._onGamepadDisconnected(evt);
  38316. }, false);
  38317. }
  38318. else {
  38319. this._startMonitoringGamepads();
  38320. }
  38321. }
  38322. }
  38323. Gamepads.prototype.dispose = function () {
  38324. if (Gamepads.gamepadDOMInfo) {
  38325. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38326. }
  38327. };
  38328. Gamepads.prototype._onGamepadConnected = function (evt) {
  38329. var newGamepad = this._addNewGamepad(evt.gamepad);
  38330. if (this._callbackGamepadConnected)
  38331. this._callbackGamepadConnected(newGamepad);
  38332. this._startMonitoringGamepads();
  38333. };
  38334. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38335. if (!this.oneGamepadConnected) {
  38336. this.oneGamepadConnected = true;
  38337. if (Gamepads.gamepadDOMInfo) {
  38338. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38339. Gamepads.gamepadDOMInfo = null;
  38340. }
  38341. }
  38342. var newGamepad;
  38343. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38344. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38345. }
  38346. else {
  38347. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38348. }
  38349. this.babylonGamepads.push(newGamepad);
  38350. return newGamepad;
  38351. };
  38352. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38353. // Remove the gamepad from the list of gamepads to monitor.
  38354. for (var i in this.babylonGamepads) {
  38355. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38356. this.babylonGamepads.splice(+i, 1);
  38357. break;
  38358. }
  38359. }
  38360. // If no gamepads are left, stop the polling loop.
  38361. if (this.babylonGamepads.length == 0) {
  38362. this._stopMonitoringGamepads();
  38363. }
  38364. };
  38365. Gamepads.prototype._startMonitoringGamepads = function () {
  38366. if (!this.isMonitoring) {
  38367. this.isMonitoring = true;
  38368. this._checkGamepadsStatus();
  38369. }
  38370. };
  38371. Gamepads.prototype._stopMonitoringGamepads = function () {
  38372. this.isMonitoring = false;
  38373. };
  38374. Gamepads.prototype._checkGamepadsStatus = function () {
  38375. var _this = this;
  38376. // updating gamepad objects
  38377. this._updateGamepadObjects();
  38378. for (var i in this.babylonGamepads) {
  38379. this.babylonGamepads[i].update();
  38380. }
  38381. if (this.isMonitoring) {
  38382. if (window.requestAnimationFrame) {
  38383. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38384. }
  38385. else if (window.mozRequestAnimationFrame) {
  38386. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38387. }
  38388. else if (window.webkitRequestAnimationFrame) {
  38389. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38390. }
  38391. }
  38392. };
  38393. // This function is called only on Chrome, which does not yet support
  38394. // connection/disconnection events, but requires you to monitor
  38395. // an array for changes.
  38396. Gamepads.prototype._updateGamepadObjects = function () {
  38397. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38398. for (var i = 0; i < gamepads.length; i++) {
  38399. if (gamepads[i]) {
  38400. if (!(gamepads[i].index in this.babylonGamepads)) {
  38401. var newGamepad = this._addNewGamepad(gamepads[i]);
  38402. if (this._callbackGamepadConnected) {
  38403. this._callbackGamepadConnected(newGamepad);
  38404. }
  38405. }
  38406. else {
  38407. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38408. }
  38409. }
  38410. }
  38411. };
  38412. return Gamepads;
  38413. })();
  38414. BABYLON.Gamepads = Gamepads;
  38415. var StickValues = (function () {
  38416. function StickValues(x, y) {
  38417. this.x = x;
  38418. this.y = y;
  38419. }
  38420. return StickValues;
  38421. })();
  38422. BABYLON.StickValues = StickValues;
  38423. var Gamepad = (function () {
  38424. function Gamepad(id, index, browserGamepad) {
  38425. this.id = id;
  38426. this.index = index;
  38427. this.browserGamepad = browserGamepad;
  38428. if (this.browserGamepad.axes.length >= 2) {
  38429. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38430. }
  38431. if (this.browserGamepad.axes.length >= 4) {
  38432. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38433. }
  38434. }
  38435. Gamepad.prototype.onleftstickchanged = function (callback) {
  38436. this._onleftstickchanged = callback;
  38437. };
  38438. Gamepad.prototype.onrightstickchanged = function (callback) {
  38439. this._onrightstickchanged = callback;
  38440. };
  38441. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38442. get: function () {
  38443. return this._leftStick;
  38444. },
  38445. set: function (newValues) {
  38446. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38447. this._onleftstickchanged(newValues);
  38448. }
  38449. this._leftStick = newValues;
  38450. },
  38451. enumerable: true,
  38452. configurable: true
  38453. });
  38454. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38455. get: function () {
  38456. return this._rightStick;
  38457. },
  38458. set: function (newValues) {
  38459. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38460. this._onrightstickchanged(newValues);
  38461. }
  38462. this._rightStick = newValues;
  38463. },
  38464. enumerable: true,
  38465. configurable: true
  38466. });
  38467. Gamepad.prototype.update = function () {
  38468. if (this._leftStick) {
  38469. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38470. }
  38471. if (this._rightStick) {
  38472. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38473. }
  38474. };
  38475. return Gamepad;
  38476. })();
  38477. BABYLON.Gamepad = Gamepad;
  38478. var GenericPad = (function (_super) {
  38479. __extends(GenericPad, _super);
  38480. function GenericPad(id, index, gamepad) {
  38481. _super.call(this, id, index, gamepad);
  38482. this.id = id;
  38483. this.index = index;
  38484. this.gamepad = gamepad;
  38485. this._buttons = new Array(gamepad.buttons.length);
  38486. }
  38487. GenericPad.prototype.onbuttondown = function (callback) {
  38488. this._onbuttondown = callback;
  38489. };
  38490. GenericPad.prototype.onbuttonup = function (callback) {
  38491. this._onbuttonup = callback;
  38492. };
  38493. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38494. if (newValue !== currentValue) {
  38495. if (this._onbuttondown && newValue === 1) {
  38496. this._onbuttondown(buttonIndex);
  38497. }
  38498. if (this._onbuttonup && newValue === 0) {
  38499. this._onbuttonup(buttonIndex);
  38500. }
  38501. }
  38502. return newValue;
  38503. };
  38504. GenericPad.prototype.update = function () {
  38505. _super.prototype.update.call(this);
  38506. for (var index = 0; index < this._buttons.length; index++) {
  38507. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38508. }
  38509. };
  38510. return GenericPad;
  38511. })(Gamepad);
  38512. BABYLON.GenericPad = GenericPad;
  38513. (function (Xbox360Button) {
  38514. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38515. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38516. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38517. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38518. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38519. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38520. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38521. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38522. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38523. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38524. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38525. var Xbox360Button = BABYLON.Xbox360Button;
  38526. (function (Xbox360Dpad) {
  38527. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38528. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38529. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38530. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38531. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38532. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38533. var Xbox360Pad = (function (_super) {
  38534. __extends(Xbox360Pad, _super);
  38535. function Xbox360Pad() {
  38536. _super.apply(this, arguments);
  38537. this._leftTrigger = 0;
  38538. this._rightTrigger = 0;
  38539. this._buttonA = 0;
  38540. this._buttonB = 0;
  38541. this._buttonX = 0;
  38542. this._buttonY = 0;
  38543. this._buttonBack = 0;
  38544. this._buttonStart = 0;
  38545. this._buttonLB = 0;
  38546. this._buttonRB = 0;
  38547. this._buttonLeftStick = 0;
  38548. this._buttonRightStick = 0;
  38549. this._dPadUp = 0;
  38550. this._dPadDown = 0;
  38551. this._dPadLeft = 0;
  38552. this._dPadRight = 0;
  38553. }
  38554. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38555. this._onlefttriggerchanged = callback;
  38556. };
  38557. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38558. this._onrighttriggerchanged = callback;
  38559. };
  38560. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38561. get: function () {
  38562. return this._leftTrigger;
  38563. },
  38564. set: function (newValue) {
  38565. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38566. this._onlefttriggerchanged(newValue);
  38567. }
  38568. this._leftTrigger = newValue;
  38569. },
  38570. enumerable: true,
  38571. configurable: true
  38572. });
  38573. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38574. get: function () {
  38575. return this._rightTrigger;
  38576. },
  38577. set: function (newValue) {
  38578. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38579. this._onrighttriggerchanged(newValue);
  38580. }
  38581. this._rightTrigger = newValue;
  38582. },
  38583. enumerable: true,
  38584. configurable: true
  38585. });
  38586. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38587. this._onbuttondown = callback;
  38588. };
  38589. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38590. this._onbuttonup = callback;
  38591. };
  38592. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38593. this._ondpaddown = callback;
  38594. };
  38595. Xbox360Pad.prototype.ondpadup = function (callback) {
  38596. this._ondpadup = callback;
  38597. };
  38598. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38599. if (newValue !== currentValue) {
  38600. if (this._onbuttondown && newValue === 1) {
  38601. this._onbuttondown(buttonType);
  38602. }
  38603. if (this._onbuttonup && newValue === 0) {
  38604. this._onbuttonup(buttonType);
  38605. }
  38606. }
  38607. return newValue;
  38608. };
  38609. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38610. if (newValue !== currentValue) {
  38611. if (this._ondpaddown && newValue === 1) {
  38612. this._ondpaddown(buttonType);
  38613. }
  38614. if (this._ondpadup && newValue === 0) {
  38615. this._ondpadup(buttonType);
  38616. }
  38617. }
  38618. return newValue;
  38619. };
  38620. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38621. get: function () {
  38622. return this._buttonA;
  38623. },
  38624. set: function (value) {
  38625. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38626. },
  38627. enumerable: true,
  38628. configurable: true
  38629. });
  38630. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38631. get: function () {
  38632. return this._buttonB;
  38633. },
  38634. set: function (value) {
  38635. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38641. get: function () {
  38642. return this._buttonX;
  38643. },
  38644. set: function (value) {
  38645. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38646. },
  38647. enumerable: true,
  38648. configurable: true
  38649. });
  38650. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38651. get: function () {
  38652. return this._buttonY;
  38653. },
  38654. set: function (value) {
  38655. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38656. },
  38657. enumerable: true,
  38658. configurable: true
  38659. });
  38660. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38661. get: function () {
  38662. return this._buttonStart;
  38663. },
  38664. set: function (value) {
  38665. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38666. },
  38667. enumerable: true,
  38668. configurable: true
  38669. });
  38670. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38671. get: function () {
  38672. return this._buttonBack;
  38673. },
  38674. set: function (value) {
  38675. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38676. },
  38677. enumerable: true,
  38678. configurable: true
  38679. });
  38680. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38681. get: function () {
  38682. return this._buttonLB;
  38683. },
  38684. set: function (value) {
  38685. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38686. },
  38687. enumerable: true,
  38688. configurable: true
  38689. });
  38690. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38691. get: function () {
  38692. return this._buttonRB;
  38693. },
  38694. set: function (value) {
  38695. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38696. },
  38697. enumerable: true,
  38698. configurable: true
  38699. });
  38700. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38701. get: function () {
  38702. return this._buttonLeftStick;
  38703. },
  38704. set: function (value) {
  38705. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38706. },
  38707. enumerable: true,
  38708. configurable: true
  38709. });
  38710. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38711. get: function () {
  38712. return this._buttonRightStick;
  38713. },
  38714. set: function (value) {
  38715. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38721. get: function () {
  38722. return this._dPadUp;
  38723. },
  38724. set: function (value) {
  38725. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38726. },
  38727. enumerable: true,
  38728. configurable: true
  38729. });
  38730. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38731. get: function () {
  38732. return this._dPadDown;
  38733. },
  38734. set: function (value) {
  38735. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38736. },
  38737. enumerable: true,
  38738. configurable: true
  38739. });
  38740. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38741. get: function () {
  38742. return this._dPadLeft;
  38743. },
  38744. set: function (value) {
  38745. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38746. },
  38747. enumerable: true,
  38748. configurable: true
  38749. });
  38750. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38751. get: function () {
  38752. return this._dPadRight;
  38753. },
  38754. set: function (value) {
  38755. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38756. },
  38757. enumerable: true,
  38758. configurable: true
  38759. });
  38760. Xbox360Pad.prototype.update = function () {
  38761. _super.prototype.update.call(this);
  38762. this.buttonA = this.browserGamepad.buttons[0].value;
  38763. this.buttonB = this.browserGamepad.buttons[1].value;
  38764. this.buttonX = this.browserGamepad.buttons[2].value;
  38765. this.buttonY = this.browserGamepad.buttons[3].value;
  38766. this.buttonLB = this.browserGamepad.buttons[4].value;
  38767. this.buttonRB = this.browserGamepad.buttons[5].value;
  38768. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38769. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38770. this.buttonBack = this.browserGamepad.buttons[8].value;
  38771. this.buttonStart = this.browserGamepad.buttons[9].value;
  38772. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38773. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38774. this.dPadUp = this.browserGamepad.buttons[12].value;
  38775. this.dPadDown = this.browserGamepad.buttons[13].value;
  38776. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38777. this.dPadRight = this.browserGamepad.buttons[15].value;
  38778. };
  38779. return Xbox360Pad;
  38780. })(Gamepad);
  38781. BABYLON.Xbox360Pad = Xbox360Pad;
  38782. })(BABYLON || (BABYLON = {}));
  38783. var BABYLON;
  38784. (function (BABYLON) {
  38785. // We're mainly based on the logic defined into the FreeCamera code
  38786. var GamepadCamera = (function (_super) {
  38787. __extends(GamepadCamera, _super);
  38788. function GamepadCamera(name, position, scene) {
  38789. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38790. _super.call(this, name, position, scene);
  38791. }
  38792. GamepadCamera.prototype.getTypeName = function () {
  38793. return "GamepadCamera";
  38794. };
  38795. return GamepadCamera;
  38796. })(BABYLON.UniversalCamera);
  38797. BABYLON.GamepadCamera = GamepadCamera;
  38798. })(BABYLON || (BABYLON = {}));
  38799. var BABYLON;
  38800. (function (BABYLON) {
  38801. var AnaglyphFreeCamera = (function (_super) {
  38802. __extends(AnaglyphFreeCamera, _super);
  38803. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38804. _super.call(this, name, position, scene);
  38805. this.interaxialDistance = interaxialDistance;
  38806. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38807. }
  38808. AnaglyphFreeCamera.prototype.getTypeName = function () {
  38809. return "AnaglyphFreeCamera";
  38810. };
  38811. return AnaglyphFreeCamera;
  38812. })(BABYLON.FreeCamera);
  38813. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38814. var AnaglyphArcRotateCamera = (function (_super) {
  38815. __extends(AnaglyphArcRotateCamera, _super);
  38816. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38817. _super.call(this, name, alpha, beta, radius, target, scene);
  38818. this.interaxialDistance = interaxialDistance;
  38819. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38820. }
  38821. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  38822. return "AnaglyphArcRotateCamera";
  38823. };
  38824. return AnaglyphArcRotateCamera;
  38825. })(BABYLON.ArcRotateCamera);
  38826. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38827. var AnaglyphGamepadCamera = (function (_super) {
  38828. __extends(AnaglyphGamepadCamera, _super);
  38829. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38830. _super.call(this, name, position, scene);
  38831. this.interaxialDistance = interaxialDistance;
  38832. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38833. }
  38834. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  38835. return "AnaglyphGamepadCamera";
  38836. };
  38837. return AnaglyphGamepadCamera;
  38838. })(BABYLON.GamepadCamera);
  38839. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38840. var AnaglyphUniversalCamera = (function (_super) {
  38841. __extends(AnaglyphUniversalCamera, _super);
  38842. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  38843. _super.call(this, name, position, scene);
  38844. this.interaxialDistance = interaxialDistance;
  38845. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38846. }
  38847. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  38848. return "AnaglyphUniversalCamera";
  38849. };
  38850. return AnaglyphUniversalCamera;
  38851. })(BABYLON.UniversalCamera);
  38852. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  38853. var StereoscopicFreeCamera = (function (_super) {
  38854. __extends(StereoscopicFreeCamera, _super);
  38855. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38856. _super.call(this, name, position, scene);
  38857. this.interaxialDistance = interaxialDistance;
  38858. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38859. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38860. }
  38861. StereoscopicFreeCamera.prototype.getTypeName = function () {
  38862. return "StereoscopicFreeCamera";
  38863. };
  38864. return StereoscopicFreeCamera;
  38865. })(BABYLON.FreeCamera);
  38866. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38867. var StereoscopicArcRotateCamera = (function (_super) {
  38868. __extends(StereoscopicArcRotateCamera, _super);
  38869. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  38870. _super.call(this, name, alpha, beta, radius, target, scene);
  38871. this.interaxialDistance = interaxialDistance;
  38872. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38873. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38874. }
  38875. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  38876. return "StereoscopicArcRotateCamera";
  38877. };
  38878. return StereoscopicArcRotateCamera;
  38879. })(BABYLON.ArcRotateCamera);
  38880. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38881. var StereoscopicGamepadCamera = (function (_super) {
  38882. __extends(StereoscopicGamepadCamera, _super);
  38883. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38884. _super.call(this, name, position, scene);
  38885. this.interaxialDistance = interaxialDistance;
  38886. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38887. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38888. }
  38889. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  38890. return "StereoscopicGamepadCamera";
  38891. };
  38892. return StereoscopicGamepadCamera;
  38893. })(BABYLON.GamepadCamera);
  38894. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38895. var StereoscopicUniversalCamera = (function (_super) {
  38896. __extends(StereoscopicUniversalCamera, _super);
  38897. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38898. _super.call(this, name, position, scene);
  38899. this.interaxialDistance = interaxialDistance;
  38900. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38901. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38902. }
  38903. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  38904. return "StereoscopicUniversalCamera";
  38905. };
  38906. return StereoscopicUniversalCamera;
  38907. })(BABYLON.UniversalCamera);
  38908. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  38909. })(BABYLON || (BABYLON = {}));
  38910. var BABYLON;
  38911. (function (BABYLON) {
  38912. var Internals;
  38913. (function (Internals) {
  38914. var PMREMGenerator = (function () {
  38915. function PMREMGenerator() {
  38916. }
  38917. return PMREMGenerator;
  38918. })();
  38919. Internals.PMREMGenerator = PMREMGenerator;
  38920. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38921. })(BABYLON || (BABYLON = {}));
  38922. var BABYLON;
  38923. (function (BABYLON) {
  38924. var Internals;
  38925. (function (Internals) {
  38926. var FileFaceOrientation = (function () {
  38927. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38928. this.name = name;
  38929. this.worldAxisForNormal = worldAxisForNormal;
  38930. this.worldAxisForFileX = worldAxisForFileX;
  38931. this.worldAxisForFileY = worldAxisForFileY;
  38932. }
  38933. return FileFaceOrientation;
  38934. })();
  38935. ;
  38936. var CubeMapToSphericalPolynomialTools = (function () {
  38937. function CubeMapToSphericalPolynomialTools() {
  38938. }
  38939. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38940. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38941. var totalSolidAngle = 0.0;
  38942. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38943. var du = 2.0 / cubeInfo.size;
  38944. var dv = du;
  38945. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38946. var minUV = du * 0.5 - 1.0;
  38947. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38948. var fileFace = this.FileFaces[faceIndex];
  38949. var dataArray = cubeInfo[fileFace.name];
  38950. var v = minUV;
  38951. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38952. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38953. // Because SP is still linear, so summation is fine in that basis.
  38954. for (var y = 0; y < cubeInfo.size; y++) {
  38955. var u = minUV;
  38956. for (var x = 0; x < cubeInfo.size; x++) {
  38957. // World direction (not normalised)
  38958. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38959. worldDirection.normalize();
  38960. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38961. if (1) {
  38962. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38963. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38964. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38965. var color = new BABYLON.Color3(r, g, b);
  38966. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38967. }
  38968. else {
  38969. if (faceIndex == 0) {
  38970. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38971. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38972. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38973. }
  38974. else if (faceIndex == 1) {
  38975. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38976. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38977. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38978. }
  38979. else if (faceIndex == 2) {
  38980. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38981. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38982. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38983. }
  38984. else if (faceIndex == 3) {
  38985. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38986. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38987. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38988. }
  38989. else if (faceIndex == 4) {
  38990. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38991. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38992. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38993. }
  38994. else if (faceIndex == 5) {
  38995. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38996. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38997. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38998. }
  38999. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  39000. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  39001. }
  39002. totalSolidAngle += deltaSolidAngle;
  39003. u += du;
  39004. }
  39005. v += dv;
  39006. }
  39007. }
  39008. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  39009. var correction = correctSolidAngle / totalSolidAngle;
  39010. sphericalHarmonics.scale(correction);
  39011. // Additionally scale by pi -- audit needed
  39012. sphericalHarmonics.scale(1.0 / Math.PI);
  39013. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  39014. };
  39015. CubeMapToSphericalPolynomialTools.FileFaces = [
  39016. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  39017. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  39018. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  39019. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  39020. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  39021. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  39022. ];
  39023. return CubeMapToSphericalPolynomialTools;
  39024. })();
  39025. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  39026. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39027. })(BABYLON || (BABYLON = {}));
  39028. var BABYLON;
  39029. (function (BABYLON) {
  39030. var Internals;
  39031. (function (Internals) {
  39032. var PanoramaToCubeMapTools = (function () {
  39033. function PanoramaToCubeMapTools() {
  39034. }
  39035. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  39036. if (!float32Array) {
  39037. throw "ConvertPanoramaToCubemap: input cannot be null";
  39038. }
  39039. if (float32Array.length != inputWidth * inputHeight * 3) {
  39040. throw "ConvertPanoramaToCubemap: input size is wrong";
  39041. }
  39042. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  39043. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  39044. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  39045. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  39046. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  39047. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  39048. return {
  39049. front: textureFront,
  39050. back: textureBack,
  39051. left: textureLeft,
  39052. right: textureRight,
  39053. up: textureUp,
  39054. down: textureDown,
  39055. size: size
  39056. };
  39057. };
  39058. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  39059. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  39060. var textureArray = new Float32Array(buffer);
  39061. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  39062. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  39063. var dy = 1 / texSize;
  39064. var fy = 0;
  39065. for (var y = 0; y < texSize; y++) {
  39066. var xv1 = faceData[0];
  39067. var xv2 = faceData[2];
  39068. for (var x = 0; x < texSize; x++) {
  39069. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  39070. v.normalize();
  39071. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  39072. // 3 channels per pixels
  39073. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  39074. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  39075. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  39076. xv1 = xv1.add(rotDX1);
  39077. xv2 = xv2.add(rotDX2);
  39078. }
  39079. fy += dy;
  39080. }
  39081. return textureArray;
  39082. };
  39083. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  39084. var theta = Math.atan2(vDir.z, vDir.x);
  39085. var phi = Math.acos(vDir.y);
  39086. while (theta < -Math.PI)
  39087. theta += 2 * Math.PI;
  39088. while (theta > Math.PI)
  39089. theta -= 2 * Math.PI;
  39090. var dx = theta / Math.PI;
  39091. var dy = phi / Math.PI;
  39092. // recenter.
  39093. dx = dx * 0.5 + 0.5;
  39094. var px = Math.round(dx * inputWidth);
  39095. if (px < 0)
  39096. px = 0;
  39097. else if (px >= inputWidth)
  39098. px = inputWidth - 1;
  39099. var py = Math.round(dy * inputHeight);
  39100. if (py < 0)
  39101. py = 0;
  39102. else if (py >= inputHeight)
  39103. py = inputHeight - 1;
  39104. var inputY = (inputHeight - py - 1);
  39105. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  39106. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  39107. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  39108. return {
  39109. r: r,
  39110. g: g,
  39111. b: b
  39112. };
  39113. };
  39114. PanoramaToCubeMapTools.FACE_FRONT = [
  39115. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39116. new BABYLON.Vector3(1.0, -1.0, -1.0),
  39117. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  39118. new BABYLON.Vector3(1.0, 1.0, -1.0)
  39119. ];
  39120. PanoramaToCubeMapTools.FACE_BACK = [
  39121. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39122. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39123. new BABYLON.Vector3(1.0, 1.0, 1.0),
  39124. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  39125. ];
  39126. PanoramaToCubeMapTools.FACE_LEFT = [
  39127. new BABYLON.Vector3(1.0, -1.0, -1.0),
  39128. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39129. new BABYLON.Vector3(1.0, 1.0, -1.0),
  39130. new BABYLON.Vector3(1.0, 1.0, 1.0)
  39131. ];
  39132. PanoramaToCubeMapTools.FACE_RIGHT = [
  39133. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39134. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39135. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  39136. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  39137. ];
  39138. PanoramaToCubeMapTools.FACE_UP = [
  39139. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  39140. new BABYLON.Vector3(1.0, 1.0, -1.0),
  39141. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  39142. new BABYLON.Vector3(1.0, 1.0, 1.0)
  39143. ];
  39144. PanoramaToCubeMapTools.FACE_DOWN = [
  39145. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  39146. new BABYLON.Vector3(1.0, -1.0, 1.0),
  39147. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  39148. new BABYLON.Vector3(1.0, -1.0, -1.0)
  39149. ];
  39150. return PanoramaToCubeMapTools;
  39151. })();
  39152. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  39153. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39154. })(BABYLON || (BABYLON = {}));
  39155. var BABYLON;
  39156. (function (BABYLON) {
  39157. var Internals;
  39158. (function (Internals) {
  39159. ;
  39160. var HDRTools = (function () {
  39161. function HDRTools() {
  39162. }
  39163. HDRTools.Ldexp = function (mantissa, exponent) {
  39164. if (exponent > 1023) {
  39165. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  39166. }
  39167. if (exponent < -1074) {
  39168. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  39169. }
  39170. return mantissa * Math.pow(2, exponent);
  39171. };
  39172. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  39173. if (exponent > 0) {
  39174. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  39175. float32array[index + 0] = red * exponent;
  39176. float32array[index + 1] = green * exponent;
  39177. float32array[index + 2] = blue * exponent;
  39178. }
  39179. else {
  39180. float32array[index + 0] = 0;
  39181. float32array[index + 1] = 0;
  39182. float32array[index + 2] = 0;
  39183. }
  39184. };
  39185. HDRTools.readStringLine = function (uint8array, startIndex) {
  39186. var line = "";
  39187. var character = "";
  39188. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  39189. character = String.fromCharCode(uint8array[i]);
  39190. if (character == "\n") {
  39191. break;
  39192. }
  39193. line += character;
  39194. }
  39195. return line;
  39196. };
  39197. /* minimal header reading. modify if you want to parse more information */
  39198. HDRTools.RGBE_ReadHeader = function (uint8array) {
  39199. var height = 0;
  39200. var width = 0;
  39201. var line = this.readStringLine(uint8array, 0);
  39202. if (line[0] != '#' || line[1] != '?') {
  39203. throw "Bad HDR Format.";
  39204. }
  39205. var endOfHeader = false;
  39206. var findFormat = false;
  39207. var lineIndex = 0;
  39208. do {
  39209. lineIndex += (line.length + 1);
  39210. line = this.readStringLine(uint8array, lineIndex);
  39211. if (line == "FORMAT=32-bit_rle_rgbe") {
  39212. findFormat = true;
  39213. }
  39214. else if (line.length == 0) {
  39215. endOfHeader = true;
  39216. }
  39217. } while (!endOfHeader);
  39218. if (!findFormat) {
  39219. throw "HDR Bad header format, unsupported FORMAT";
  39220. }
  39221. lineIndex += (line.length + 1);
  39222. line = this.readStringLine(uint8array, lineIndex);
  39223. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  39224. var match = sizeRegexp.exec(line);
  39225. // TODO. Support +Y and -X if needed.
  39226. if (match.length < 3) {
  39227. throw "HDR Bad header format, no size";
  39228. }
  39229. width = parseInt(match[2]);
  39230. height = parseInt(match[1]);
  39231. if (width < 8 || width > 0x7fff) {
  39232. throw "HDR Bad header format, unsupported size";
  39233. }
  39234. lineIndex += (line.length + 1);
  39235. return {
  39236. height: height,
  39237. width: width,
  39238. dataPosition: lineIndex
  39239. };
  39240. };
  39241. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  39242. var uint8array = new Uint8Array(buffer);
  39243. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  39244. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  39245. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  39246. return cubeMapData;
  39247. };
  39248. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  39249. // Keep for multi format supports.
  39250. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  39251. };
  39252. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  39253. var num_scanlines = hdrInfo.height;
  39254. var scanline_width = hdrInfo.width;
  39255. var a, b, c, d, count;
  39256. var dataIndex = hdrInfo.dataPosition;
  39257. var index = 0, endIndex = 0, i = 0;
  39258. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  39259. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  39260. // 3 channels of 4 bytes per pixel in float.
  39261. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  39262. var resultArray = new Float32Array(resultBuffer);
  39263. // read in each successive scanline
  39264. while (num_scanlines > 0) {
  39265. a = uint8array[dataIndex++];
  39266. b = uint8array[dataIndex++];
  39267. c = uint8array[dataIndex++];
  39268. d = uint8array[dataIndex++];
  39269. if (a != 2 || b != 2 || (c & 0x80)) {
  39270. // this file is not run length encoded
  39271. throw "HDR Bad header format, not RLE";
  39272. }
  39273. if (((c << 8) | d) != scanline_width) {
  39274. throw "HDR Bad header format, wrong scan line width";
  39275. }
  39276. index = 0;
  39277. // read each of the four channels for the scanline into the buffer
  39278. for (i = 0; i < 4; i++) {
  39279. endIndex = (i + 1) * scanline_width;
  39280. while (index < endIndex) {
  39281. a = uint8array[dataIndex++];
  39282. b = uint8array[dataIndex++];
  39283. if (a > 128) {
  39284. // a run of the same value
  39285. count = a - 128;
  39286. if ((count == 0) || (count > endIndex - index)) {
  39287. throw "HDR Bad Format, bad scanline data (run)";
  39288. }
  39289. while (count-- > 0) {
  39290. scanLineArray[index++] = b;
  39291. }
  39292. }
  39293. else {
  39294. // a non-run
  39295. count = a;
  39296. if ((count == 0) || (count > endIndex - index)) {
  39297. throw "HDR Bad Format, bad scanline data (non-run)";
  39298. }
  39299. scanLineArray[index++] = b;
  39300. if (--count > 0) {
  39301. for (var j = 0; j < count; j++) {
  39302. scanLineArray[index++] = uint8array[dataIndex++];
  39303. }
  39304. }
  39305. }
  39306. }
  39307. }
  39308. // now convert data from buffer into floats
  39309. for (i = 0; i < scanline_width; i++) {
  39310. a = scanLineArray[i];
  39311. b = scanLineArray[i + scanline_width];
  39312. c = scanLineArray[i + 2 * scanline_width];
  39313. d = scanLineArray[i + 3 * scanline_width];
  39314. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  39315. }
  39316. num_scanlines--;
  39317. }
  39318. return resultArray;
  39319. };
  39320. return HDRTools;
  39321. })();
  39322. Internals.HDRTools = HDRTools;
  39323. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39324. })(BABYLON || (BABYLON = {}));
  39325. var BABYLON;
  39326. (function (BABYLON) {
  39327. var HDRCubeTexture = (function (_super) {
  39328. __extends(HDRCubeTexture, _super);
  39329. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace) {
  39330. if (noMipmap === void 0) { noMipmap = false; }
  39331. if (generateHarmonics === void 0) { generateHarmonics = true; }
  39332. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  39333. _super.call(this, scene);
  39334. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  39335. this._useInGammaSpace = false;
  39336. this._generateHarmonics = true;
  39337. this.sphericalPolynomial = null;
  39338. this.name = url;
  39339. this.url = url;
  39340. this._noMipmap = noMipmap;
  39341. this.hasAlpha = false;
  39342. this._size = size;
  39343. this._useInGammaSpace = useInGammaSpace;
  39344. if (!url) {
  39345. return;
  39346. }
  39347. this._texture = this._getFromCache(url, noMipmap);
  39348. if (!this._texture) {
  39349. if (!scene.useDelayedTextureLoading) {
  39350. this.loadTexture();
  39351. }
  39352. else {
  39353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39354. }
  39355. }
  39356. this.isCube = true;
  39357. this._textureMatrix = BABYLON.Matrix.Identity();
  39358. }
  39359. HDRCubeTexture.prototype.loadTexture = function () {
  39360. var _this = this;
  39361. var callback = function (buffer) {
  39362. // Extract the raw linear data.
  39363. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  39364. // Generate harmonics if needed.
  39365. if (_this._generateHarmonics) {
  39366. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  39367. }
  39368. var results = [];
  39369. var byteArray = null;
  39370. // Create uintarray fallback.
  39371. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  39372. // 3 channels of 1 bytes per pixel in bytes.
  39373. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  39374. byteArray = new Uint8Array(byteBuffer);
  39375. }
  39376. // Push each faces.
  39377. for (var j = 0; j < 6; j++) {
  39378. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  39379. // If special cases.
  39380. if (_this._useInGammaSpace || byteArray) {
  39381. for (var i = 0; i < _this._size * _this._size; i++) {
  39382. // Put in gamma space if requested.
  39383. if (_this._useInGammaSpace) {
  39384. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  39385. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  39386. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  39387. }
  39388. // Convert to int texture for fallback.
  39389. if (byteArray) {
  39390. // R
  39391. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  39392. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  39393. // G
  39394. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  39395. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  39396. // B
  39397. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  39398. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  39399. }
  39400. }
  39401. }
  39402. results.push(dataFace);
  39403. }
  39404. return results;
  39405. };
  39406. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  39407. };
  39408. HDRCubeTexture.prototype.clone = function () {
  39409. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace);
  39410. // Base texture
  39411. newTexture.level = this.level;
  39412. newTexture.wrapU = this.wrapU;
  39413. newTexture.wrapV = this.wrapV;
  39414. newTexture.coordinatesIndex = this.coordinatesIndex;
  39415. newTexture.coordinatesMode = this.coordinatesMode;
  39416. return newTexture;
  39417. };
  39418. // Methods
  39419. HDRCubeTexture.prototype.delayLoad = function () {
  39420. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39421. return;
  39422. }
  39423. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39424. this._texture = this._getFromCache(this.url, this._noMipmap);
  39425. if (!this._texture) {
  39426. this.loadTexture();
  39427. }
  39428. };
  39429. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  39430. return this._textureMatrix;
  39431. };
  39432. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39433. var texture = null;
  39434. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39435. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace);
  39436. texture.name = parsedTexture.name;
  39437. texture.hasAlpha = parsedTexture.hasAlpha;
  39438. texture.level = parsedTexture.level;
  39439. texture.coordinatesMode = parsedTexture.coordinatesMode;
  39440. }
  39441. return texture;
  39442. };
  39443. HDRCubeTexture.prototype.serialize = function () {
  39444. if (!this.name) {
  39445. return null;
  39446. }
  39447. var serializationObject = {};
  39448. serializationObject.name = this.name;
  39449. serializationObject.hasAlpha = this.hasAlpha;
  39450. serializationObject.isCube = true;
  39451. serializationObject.level = this.level;
  39452. serializationObject.size = this._size;
  39453. serializationObject.coordinatesMode = this.coordinatesMode;
  39454. serializationObject.useInGammaSpace = this._useInGammaSpace;
  39455. serializationObject.generateHarmonics = this._generateHarmonics;
  39456. return serializationObject;
  39457. };
  39458. HDRCubeTexture._facesMapping = [
  39459. "left",
  39460. "down",
  39461. "front",
  39462. "right",
  39463. "up",
  39464. "back"
  39465. ];
  39466. return HDRCubeTexture;
  39467. })(BABYLON.BaseTexture);
  39468. BABYLON.HDRCubeTexture = HDRCubeTexture;
  39469. })(BABYLON || (BABYLON = {}));
  39470. 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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\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#include<fresnelFunction>\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#endif\r\n\r\n#include<reflectionFunction>\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#include<bumpFragmentFunctions>\r\n#include<clipPlaneFragmentDeclaration>\r\n#include<logDepthDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\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#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\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\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#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\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#ifdef REFLECTIONOVERALPHA\r\n\talpha = clamp(alpha + dot(reflectionColor, 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 + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, 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#include<logDepthFragment>\r\n#include<fogFragment>\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#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<pointCloudVertexDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<logDepthDeclaration>\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\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#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n#include<pointCloudVertex>\r\n#include<logDepthVertex>\r\n\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\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 vec2 scale;\r\nuniform vec2 offset;\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\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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#include<fresnelFunction>\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#include<clipPlaneFragmentDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\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#include<fogFragment>\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#include<bonesDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\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\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\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\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\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\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","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#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\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#include<fogVertexDeclaration>\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}"};
  39471. 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){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2;var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.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=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,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=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,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,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},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),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),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=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=o.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,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],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/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),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-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*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+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],c=this.m[8],y=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],d=t.m[1],g=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],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],S=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*S,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*S,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,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]=c,x.m[12]=y,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,c,y,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]=c,z.m[11]=y,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,\ni.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){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 s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,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,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=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(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},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,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var c=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;var p=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,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-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=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  39472. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#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","bonesVertex":"#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\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","bumpFragmentFunctions":"#ifdef BUMP\r\n\tvarying vec2 vBumpUV;\r\n\tuniform vec2 vBumpInfos;\r\n\tuniform sampler2D bumpSampler;\r\n\r\n\t// Thanks to http://www.thetenthplanet.de/archives/1180\r\n\tmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n\t{\r\n\t\t// get edge vectors of the pixel triangle\r\n\t\tvec3 dp1 = dFdx(p);\r\n\t\tvec3 dp2 = dFdy(p);\r\n\t\tvec2 duv1 = dFdx(uv);\r\n\t\tvec2 duv2 = dFdy(uv);\r\n\r\n\t\t// solve the linear system\r\n\t\tvec3 dp2perp = cross(dp2, normal);\r\n\t\tvec3 dp1perp = cross(normal, dp1);\r\n\t\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\t\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t\t// construct a scale-invariant frame \r\n\t\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\t\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n\t}\r\n\r\n\tvec3 perturbNormal(vec3 viewDir)\r\n\t{\r\n\t\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\t\tmap = map * 255. / 127. - 128. / 127.;\r\n\t\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\t\treturn normalize(TBN * map);\r\n\t}\r\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t{\r\n\t\tdiscard;\r\n\t}\r\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\r\n\tvarying float fClipDistance;\r\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\r\n\tuniform vec4 vClipPlane;\r\n\tvarying float fClipDistance;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#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","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","fresnelFunction":"#ifdef FRESNEL\r\n\tfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n\t{\r\n\t\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\t\treturn clamp(fresnelTerm, 0., 1.);\r\n\t}\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// 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\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","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\r\n\tuniform float logarithmicDepthConstant;\r\n\tvarying float vFragmentDepth;\r\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif","pointCloudVertex":"#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\r\n\tuniform float pointSize;\r\n#endif","reflectionFunction":"vec3 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}","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\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\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  39473. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  39474. module.exports = BABYLON;
  39475. };