babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. return Color4;
  270. })();
  271. BABYLON.Color4 = Color4;
  272. var Vector2 = (function () {
  273. function Vector2(x, y) {
  274. this.x = x;
  275. this.y = y;
  276. }
  277. Vector2.prototype.toString = function () {
  278. return "{X: " + this.x + " Y:" + this.y + "}";
  279. };
  280. // Operators
  281. Vector2.prototype.toArray = function (array, index) {
  282. if (index === void 0) { index = 0; }
  283. array[index] = this.x;
  284. array[index + 1] = this.y;
  285. return this;
  286. };
  287. Vector2.prototype.asArray = function () {
  288. var result = [];
  289. this.toArray(result, 0);
  290. return result;
  291. };
  292. Vector2.prototype.copyFrom = function (source) {
  293. this.x = source.x;
  294. this.y = source.y;
  295. return this;
  296. };
  297. Vector2.prototype.copyFromFloats = function (x, y) {
  298. this.x = x;
  299. this.y = y;
  300. return this;
  301. };
  302. Vector2.prototype.add = function (otherVector) {
  303. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  304. };
  305. Vector2.prototype.addVector3 = function (otherVector) {
  306. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  307. };
  308. Vector2.prototype.subtract = function (otherVector) {
  309. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  310. };
  311. Vector2.prototype.subtractInPlace = function (otherVector) {
  312. this.x -= otherVector.x;
  313. this.y -= otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.multiplyInPlace = function (otherVector) {
  317. this.x *= otherVector.x;
  318. this.y *= otherVector.y;
  319. return this;
  320. };
  321. Vector2.prototype.multiply = function (otherVector) {
  322. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  323. };
  324. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  325. result.x = this.x * otherVector.x;
  326. result.y = this.y * otherVector.y;
  327. return this;
  328. };
  329. Vector2.prototype.multiplyByFloats = function (x, y) {
  330. return new Vector2(this.x * x, this.y * y);
  331. };
  332. Vector2.prototype.divide = function (otherVector) {
  333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  334. };
  335. Vector2.prototype.divideToRef = function (otherVector, result) {
  336. result.x = this.x / otherVector.x;
  337. result.y = this.y / otherVector.y;
  338. return this;
  339. };
  340. Vector2.prototype.negate = function () {
  341. return new Vector2(-this.x, -this.y);
  342. };
  343. Vector2.prototype.scaleInPlace = function (scale) {
  344. this.x *= scale;
  345. this.y *= scale;
  346. return this;
  347. };
  348. Vector2.prototype.scale = function (scale) {
  349. return new Vector2(this.x * scale, this.y * scale);
  350. };
  351. Vector2.prototype.equals = function (otherVector) {
  352. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  353. };
  354. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  355. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  356. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  357. };
  358. // Properties
  359. Vector2.prototype.length = function () {
  360. return Math.sqrt(this.x * this.x + this.y * this.y);
  361. };
  362. Vector2.prototype.lengthSquared = function () {
  363. return (this.x * this.x + this.y * this.y);
  364. };
  365. // Methods
  366. Vector2.prototype.normalize = function () {
  367. var len = this.length();
  368. if (len === 0)
  369. return this;
  370. var num = 1.0 / len;
  371. this.x *= num;
  372. this.y *= num;
  373. return this;
  374. };
  375. Vector2.prototype.clone = function () {
  376. return new Vector2(this.x, this.y);
  377. };
  378. // Statics
  379. Vector2.Zero = function () {
  380. return new Vector2(0, 0);
  381. };
  382. Vector2.FromArray = function (array, offset) {
  383. if (offset === void 0) { offset = 0; }
  384. return new Vector2(array[offset], array[offset + 1]);
  385. };
  386. Vector2.FromArrayToRef = function (array, offset, result) {
  387. result.x = array[offset];
  388. result.y = array[offset + 1];
  389. };
  390. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  391. var squared = amount * amount;
  392. var cubed = amount * squared;
  393. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  394. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  395. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  396. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  397. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  398. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  399. return new Vector2(x, y);
  400. };
  401. Vector2.Clamp = function (value, min, max) {
  402. var x = value.x;
  403. x = (x > max.x) ? max.x : x;
  404. x = (x < min.x) ? min.x : x;
  405. var y = value.y;
  406. y = (y > max.y) ? max.y : y;
  407. y = (y < min.y) ? min.y : y;
  408. return new Vector2(x, y);
  409. };
  410. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  411. var squared = amount * amount;
  412. var cubed = amount * squared;
  413. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  414. var part2 = (-2.0 * cubed) + (3.0 * squared);
  415. var part3 = (cubed - (2.0 * squared)) + amount;
  416. var part4 = cubed - squared;
  417. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  418. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  419. return new Vector2(x, y);
  420. };
  421. Vector2.Lerp = function (start, end, amount) {
  422. var x = start.x + ((end.x - start.x) * amount);
  423. var y = start.y + ((end.y - start.y) * amount);
  424. return new Vector2(x, y);
  425. };
  426. Vector2.Dot = function (left, right) {
  427. return left.x * right.x + left.y * right.y;
  428. };
  429. Vector2.Normalize = function (vector) {
  430. var newVector = vector.clone();
  431. newVector.normalize();
  432. return newVector;
  433. };
  434. Vector2.Minimize = function (left, right) {
  435. var x = (left.x < right.x) ? left.x : right.x;
  436. var y = (left.y < right.y) ? left.y : right.y;
  437. return new Vector2(x, y);
  438. };
  439. Vector2.Maximize = function (left, right) {
  440. var x = (left.x > right.x) ? left.x : right.x;
  441. var y = (left.y > right.y) ? left.y : right.y;
  442. return new Vector2(x, y);
  443. };
  444. Vector2.Transform = function (vector, transformation) {
  445. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  446. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  447. return new Vector2(x, y);
  448. };
  449. Vector2.Distance = function (value1, value2) {
  450. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  451. };
  452. Vector2.DistanceSquared = function (value1, value2) {
  453. var x = value1.x - value2.x;
  454. var y = value1.y - value2.y;
  455. return (x * x) + (y * y);
  456. };
  457. return Vector2;
  458. })();
  459. BABYLON.Vector2 = Vector2;
  460. var Vector3 = (function () {
  461. function Vector3(x, y, z) {
  462. this.x = x;
  463. this.y = y;
  464. this.z = z;
  465. }
  466. Vector3.prototype.toString = function () {
  467. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  468. };
  469. // Operators
  470. Vector3.prototype.asArray = function () {
  471. var result = [];
  472. this.toArray(result, 0);
  473. return result;
  474. };
  475. Vector3.prototype.toArray = function (array, index) {
  476. if (index === void 0) { index = 0; }
  477. array[index] = this.x;
  478. array[index + 1] = this.y;
  479. array[index + 2] = this.z;
  480. return this;
  481. };
  482. Vector3.prototype.toQuaternion = function () {
  483. var result = new Quaternion(0, 0, 0, 1);
  484. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  485. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  486. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  487. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  488. var cosy = Math.cos(this.y * 0.5);
  489. var siny = Math.sin(this.y * 0.5);
  490. result.x = coszMinusx * siny;
  491. result.y = -sinzMinusx * siny;
  492. result.z = sinxPlusz * cosy;
  493. result.w = cosxPlusz * cosy;
  494. return result;
  495. };
  496. Vector3.prototype.addInPlace = function (otherVector) {
  497. this.x += otherVector.x;
  498. this.y += otherVector.y;
  499. this.z += otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.add = function (otherVector) {
  503. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  504. };
  505. Vector3.prototype.addToRef = function (otherVector, result) {
  506. result.x = this.x + otherVector.x;
  507. result.y = this.y + otherVector.y;
  508. result.z = this.z + otherVector.z;
  509. return this;
  510. };
  511. Vector3.prototype.subtractInPlace = function (otherVector) {
  512. this.x -= otherVector.x;
  513. this.y -= otherVector.y;
  514. this.z -= otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.subtract = function (otherVector) {
  518. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  519. };
  520. Vector3.prototype.subtractToRef = 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.subtractFromFloats = function (x, y, z) {
  527. return new Vector3(this.x - x, this.y - y, this.z - z);
  528. };
  529. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  530. result.x = this.x - x;
  531. result.y = this.y - y;
  532. result.z = this.z - z;
  533. return this;
  534. };
  535. Vector3.prototype.negate = function () {
  536. return new Vector3(-this.x, -this.y, -this.z);
  537. };
  538. Vector3.prototype.scaleInPlace = function (scale) {
  539. this.x *= scale;
  540. this.y *= scale;
  541. this.z *= scale;
  542. return this;
  543. };
  544. Vector3.prototype.scale = function (scale) {
  545. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  546. };
  547. Vector3.prototype.scaleToRef = function (scale, result) {
  548. result.x = this.x * scale;
  549. result.y = this.y * scale;
  550. result.z = this.z * scale;
  551. };
  552. Vector3.prototype.equals = function (otherVector) {
  553. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  554. };
  555. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  556. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  557. 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);
  558. };
  559. Vector3.prototype.equalsToFloats = function (x, y, z) {
  560. return this.x === x && this.y === y && this.z === z;
  561. };
  562. Vector3.prototype.multiplyInPlace = function (otherVector) {
  563. this.x *= otherVector.x;
  564. this.y *= otherVector.y;
  565. this.z *= otherVector.z;
  566. return this;
  567. };
  568. Vector3.prototype.multiply = function (otherVector) {
  569. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  570. };
  571. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  572. result.x = this.x * otherVector.x;
  573. result.y = this.y * otherVector.y;
  574. result.z = this.z * otherVector.z;
  575. return this;
  576. };
  577. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  578. return new Vector3(this.x * x, this.y * y, this.z * z);
  579. };
  580. Vector3.prototype.divide = function (otherVector) {
  581. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  582. };
  583. Vector3.prototype.divideToRef = function (otherVector, result) {
  584. result.x = this.x / otherVector.x;
  585. result.y = this.y / otherVector.y;
  586. result.z = this.z / otherVector.z;
  587. return this;
  588. };
  589. Vector3.prototype.MinimizeInPlace = function (other) {
  590. if (other.x < this.x)
  591. this.x = other.x;
  592. if (other.y < this.y)
  593. this.y = other.y;
  594. if (other.z < this.z)
  595. this.z = other.z;
  596. return this;
  597. };
  598. Vector3.prototype.MaximizeInPlace = function (other) {
  599. if (other.x > this.x)
  600. this.x = other.x;
  601. if (other.y > this.y)
  602. this.y = other.y;
  603. if (other.z > this.z)
  604. this.z = other.z;
  605. return this;
  606. };
  607. // Properties
  608. Vector3.prototype.length = function () {
  609. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  610. };
  611. Vector3.prototype.lengthSquared = function () {
  612. return (this.x * this.x + this.y * this.y + this.z * this.z);
  613. };
  614. // Methods
  615. Vector3.prototype.normalize = function () {
  616. var len = this.length();
  617. if (len === 0 || len === 1.0)
  618. return this;
  619. var num = 1.0 / len;
  620. this.x *= num;
  621. this.y *= num;
  622. this.z *= num;
  623. return this;
  624. };
  625. Vector3.prototype.clone = function () {
  626. return new Vector3(this.x, this.y, this.z);
  627. };
  628. Vector3.prototype.copyFrom = function (source) {
  629. this.x = source.x;
  630. this.y = source.y;
  631. this.z = source.z;
  632. return this;
  633. };
  634. Vector3.prototype.copyFromFloats = function (x, y, z) {
  635. this.x = x;
  636. this.y = y;
  637. this.z = z;
  638. return this;
  639. };
  640. // Statics
  641. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  642. var d0 = Vector3.Dot(vector0, axis) - size;
  643. var d1 = Vector3.Dot(vector1, axis) - size;
  644. var s = d0 / (d0 - d1);
  645. return s;
  646. };
  647. Vector3.FromArray = function (array, offset) {
  648. if (!offset) {
  649. offset = 0;
  650. }
  651. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  652. };
  653. Vector3.FromFloatArray = function (array, offset) {
  654. if (!offset) {
  655. offset = 0;
  656. }
  657. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  658. };
  659. Vector3.FromArrayToRef = function (array, offset, result) {
  660. result.x = array[offset];
  661. result.y = array[offset + 1];
  662. result.z = array[offset + 2];
  663. };
  664. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  665. result.x = array[offset];
  666. result.y = array[offset + 1];
  667. result.z = array[offset + 2];
  668. };
  669. Vector3.FromFloatsToRef = function (x, y, z, result) {
  670. result.x = x;
  671. result.y = y;
  672. result.z = z;
  673. };
  674. Vector3.Zero = function () {
  675. return new Vector3(0, 0, 0);
  676. };
  677. Vector3.Up = function () {
  678. return new Vector3(0, 1.0, 0);
  679. };
  680. Vector3.TransformCoordinates = function (vector, transformation) {
  681. var result = Vector3.Zero();
  682. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  683. return result;
  684. };
  685. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  686. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  687. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  688. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  689. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  690. result.x = x / w;
  691. result.y = y / w;
  692. result.z = z / w;
  693. };
  694. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  695. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  696. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  697. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  698. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  699. result.x = rx / rw;
  700. result.y = ry / rw;
  701. result.z = rz / rw;
  702. };
  703. Vector3.TransformNormal = function (vector, transformation) {
  704. var result = Vector3.Zero();
  705. Vector3.TransformNormalToRef(vector, transformation, result);
  706. return result;
  707. };
  708. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  709. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  710. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  711. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  712. };
  713. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  714. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  715. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  716. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  717. };
  718. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  719. var squared = amount * amount;
  720. var cubed = amount * squared;
  721. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  722. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  723. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  724. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  725. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  726. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  727. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  728. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  729. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Clamp = function (value, min, max) {
  733. var x = value.x;
  734. x = (x > max.x) ? max.x : x;
  735. x = (x < min.x) ? min.x : x;
  736. var y = value.y;
  737. y = (y > max.y) ? max.y : y;
  738. y = (y < min.y) ? min.y : y;
  739. var z = value.z;
  740. z = (z > max.z) ? max.z : z;
  741. z = (z < min.z) ? min.z : z;
  742. return new Vector3(x, y, z);
  743. };
  744. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  745. var squared = amount * amount;
  746. var cubed = amount * squared;
  747. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  748. var part2 = (-2.0 * cubed) + (3.0 * squared);
  749. var part3 = (cubed - (2.0 * squared)) + amount;
  750. var part4 = cubed - squared;
  751. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  752. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  753. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  754. return new Vector3(x, y, z);
  755. };
  756. Vector3.Lerp = function (start, end, amount) {
  757. var x = start.x + ((end.x - start.x) * amount);
  758. var y = start.y + ((end.y - start.y) * amount);
  759. var z = start.z + ((end.z - start.z) * amount);
  760. return new Vector3(x, y, z);
  761. };
  762. Vector3.Dot = function (left, right) {
  763. return (left.x * right.x + left.y * right.y + left.z * right.z);
  764. };
  765. Vector3.Cross = function (left, right) {
  766. var result = Vector3.Zero();
  767. Vector3.CrossToRef(left, right, result);
  768. return result;
  769. };
  770. Vector3.CrossToRef = function (left, right, result) {
  771. result.x = left.y * right.z - left.z * right.y;
  772. result.y = left.z * right.x - left.x * right.z;
  773. result.z = left.x * right.y - left.y * right.x;
  774. };
  775. Vector3.Normalize = function (vector) {
  776. var result = Vector3.Zero();
  777. Vector3.NormalizeToRef(vector, result);
  778. return result;
  779. };
  780. Vector3.NormalizeToRef = function (vector, result) {
  781. result.copyFrom(vector);
  782. result.normalize();
  783. };
  784. Vector3.Project = function (vector, world, transform, viewport) {
  785. var cw = viewport.width;
  786. var ch = viewport.height;
  787. var cx = viewport.x;
  788. var cy = viewport.y;
  789. 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);
  790. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  791. return Vector3.TransformCoordinates(vector, finalMatrix);
  792. };
  793. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  794. var matrix = world.multiply(transform);
  795. matrix.invert();
  796. source.x = source.x / viewportWidth * 2 - 1;
  797. source.y = -(source.y / viewportHeight * 2 - 1);
  798. var vector = Vector3.TransformCoordinates(source, matrix);
  799. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  800. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  801. vector = vector.scale(1.0 / num);
  802. }
  803. return vector;
  804. };
  805. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  806. var matrix = world.multiply(view).multiply(projection);
  807. matrix.invert();
  808. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  809. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  810. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  811. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  812. vector = vector.scale(1.0 / num);
  813. }
  814. return vector;
  815. };
  816. Vector3.Minimize = function (left, right) {
  817. var min = left.clone();
  818. min.MinimizeInPlace(right);
  819. return min;
  820. };
  821. Vector3.Maximize = function (left, right) {
  822. var max = left.clone();
  823. max.MaximizeInPlace(right);
  824. return max;
  825. };
  826. Vector3.Distance = function (value1, value2) {
  827. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  828. };
  829. Vector3.DistanceSquared = function (value1, value2) {
  830. var x = value1.x - value2.x;
  831. var y = value1.y - value2.y;
  832. var z = value1.z - value2.z;
  833. return (x * x) + (y * y) + (z * z);
  834. };
  835. Vector3.Center = function (value1, value2) {
  836. var center = value1.add(value2);
  837. center.scaleInPlace(0.5);
  838. return center;
  839. };
  840. /**
  841. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  843. * to something in order to rotate it from its local system to the given target system.
  844. */
  845. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  846. var rotation = Vector3.Zero();
  847. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  848. return rotation;
  849. };
  850. /**
  851. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  852. */
  853. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  854. var u = Vector3.Normalize(axis1);
  855. var w = Vector3.Normalize(axis3);
  856. // world axis
  857. var X = Axis.X;
  858. var Y = Axis.Y;
  859. // equation unknowns and vars
  860. var yaw = 0.0;
  861. var pitch = 0.0;
  862. var roll = 0.0;
  863. var x = 0.0;
  864. var y = 0.0;
  865. var z = 0.0;
  866. var t = 0.0;
  867. var sign = -1.0;
  868. var nbRevert = 0;
  869. var cross;
  870. var dot = 0.0;
  871. // step 1 : rotation around w
  872. // Rv3(u) = u1, and u1 belongs to plane xOz
  873. // Rv3(w) = w1 = w invariant
  874. var u1;
  875. var v1;
  876. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  877. z = 1.0;
  878. }
  879. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  880. x = 1.0;
  881. }
  882. else {
  883. t = w.z / w.x;
  884. x = -t * Math.sqrt(1 / (1 + t * t));
  885. z = Math.sqrt(1 / (1 + t * t));
  886. }
  887. u1 = new Vector3(x, y, z);
  888. u1.normalize();
  889. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  890. v1.normalize();
  891. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  892. cross.normalize();
  893. if (Vector3.Dot(w, cross) < 0) {
  894. sign = 1.0;
  895. }
  896. dot = Vector3.Dot(u, u1);
  897. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  898. roll = Math.acos(dot) * sign;
  899. if (Vector3.Dot(u1, X) < 0) {
  900. roll = Math.PI + roll;
  901. u1 = u1.scaleInPlace(-1);
  902. v1 = v1.scaleInPlace(-1);
  903. nbRevert++;
  904. }
  905. // step 2 : rotate around u1
  906. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  907. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  908. var w2;
  909. var v2;
  910. x = 0.0;
  911. y = 0.0;
  912. z = 0.0;
  913. sign = -1;
  914. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  915. x = 1.0;
  916. }
  917. else {
  918. t = u1.z / u1.x;
  919. x = -t * Math.sqrt(1 / (1 + t * t));
  920. z = Math.sqrt(1 / (1 + t * t));
  921. }
  922. w2 = new Vector3(x, y, z);
  923. w2.normalize();
  924. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  925. v2.normalize();
  926. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  927. cross.normalize();
  928. if (Vector3.Dot(u1, cross) < 0) {
  929. sign = 1.0;
  930. }
  931. dot = Vector3.Dot(w, w2);
  932. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  933. pitch = Math.acos(dot) * sign;
  934. if (Vector3.Dot(v2, Y) < 0) {
  935. pitch = Math.PI + pitch;
  936. v2 = v2.scaleInPlace(-1);
  937. w2 = w2.scaleInPlace(-1);
  938. nbRevert++;
  939. }
  940. // step 3 : rotate around v2
  941. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  942. sign = -1;
  943. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(cross, Y) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u1, X);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  951. if (dot < 0 && nbRevert < 2) {
  952. yaw = Math.PI + yaw;
  953. }
  954. ref.x = pitch;
  955. ref.y = yaw;
  956. ref.z = roll;
  957. };
  958. return Vector3;
  959. })();
  960. BABYLON.Vector3 = Vector3;
  961. //Vector4 class created for EulerAngle class conversion to Quaternion
  962. var Vector4 = (function () {
  963. function Vector4(x, y, z, w) {
  964. this.x = x;
  965. this.y = y;
  966. this.z = z;
  967. this.w = w;
  968. }
  969. Vector4.prototype.toString = function () {
  970. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  971. };
  972. // Operators
  973. Vector4.prototype.asArray = function () {
  974. var result = [];
  975. this.toArray(result, 0);
  976. return result;
  977. };
  978. Vector4.prototype.toArray = function (array, index) {
  979. if (index === undefined) {
  980. index = 0;
  981. }
  982. array[index] = this.x;
  983. array[index + 1] = this.y;
  984. array[index + 2] = this.z;
  985. array[index + 3] = this.w;
  986. return this;
  987. };
  988. Vector4.prototype.addInPlace = function (otherVector) {
  989. this.x += otherVector.x;
  990. this.y += otherVector.y;
  991. this.z += otherVector.z;
  992. this.w += otherVector.w;
  993. return this;
  994. };
  995. Vector4.prototype.add = function (otherVector) {
  996. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  997. };
  998. Vector4.prototype.addToRef = function (otherVector, result) {
  999. result.x = this.x + otherVector.x;
  1000. result.y = this.y + otherVector.y;
  1001. result.z = this.z + otherVector.z;
  1002. result.w = this.w + otherVector.w;
  1003. return this;
  1004. };
  1005. Vector4.prototype.subtractInPlace = function (otherVector) {
  1006. this.x -= otherVector.x;
  1007. this.y -= otherVector.y;
  1008. this.z -= otherVector.z;
  1009. this.w -= otherVector.w;
  1010. return this;
  1011. };
  1012. Vector4.prototype.subtract = function (otherVector) {
  1013. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1014. };
  1015. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1016. result.x = this.x - otherVector.x;
  1017. result.y = this.y - otherVector.y;
  1018. result.z = this.z - otherVector.z;
  1019. result.w = this.w - otherVector.w;
  1020. return this;
  1021. };
  1022. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1023. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1024. };
  1025. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1026. result.x = this.x - x;
  1027. result.y = this.y - y;
  1028. result.z = this.z - z;
  1029. result.w = this.w - w;
  1030. return this;
  1031. };
  1032. Vector4.prototype.negate = function () {
  1033. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1034. };
  1035. Vector4.prototype.scaleInPlace = function (scale) {
  1036. this.x *= scale;
  1037. this.y *= scale;
  1038. this.z *= scale;
  1039. this.w *= scale;
  1040. return this;
  1041. };
  1042. Vector4.prototype.scale = function (scale) {
  1043. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1044. };
  1045. Vector4.prototype.scaleToRef = function (scale, result) {
  1046. result.x = this.x * scale;
  1047. result.y = this.y * scale;
  1048. result.z = this.z * scale;
  1049. result.w = this.w * scale;
  1050. };
  1051. Vector4.prototype.equals = function (otherVector) {
  1052. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1053. };
  1054. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1055. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1056. return otherVector
  1057. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1059. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1060. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1061. };
  1062. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1063. return this.x === x && this.y === y && this.z === z && this.w === w;
  1064. };
  1065. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1066. this.x *= otherVector.x;
  1067. this.y *= otherVector.y;
  1068. this.z *= otherVector.z;
  1069. this.w *= otherVector.w;
  1070. return this;
  1071. };
  1072. Vector4.prototype.multiply = function (otherVector) {
  1073. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1074. };
  1075. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1076. result.x = this.x * otherVector.x;
  1077. result.y = this.y * otherVector.y;
  1078. result.z = this.z * otherVector.z;
  1079. result.w = this.w * otherVector.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1083. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1084. };
  1085. Vector4.prototype.divide = 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.divideToRef = 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.MinimizeInPlace = function (other) {
  1096. if (other.x < this.x)
  1097. this.x = other.x;
  1098. if (other.y < this.y)
  1099. this.y = other.y;
  1100. if (other.z < this.z)
  1101. this.z = other.z;
  1102. if (other.w < this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. Vector4.prototype.MaximizeInPlace = function (other) {
  1107. if (other.x > this.x)
  1108. this.x = other.x;
  1109. if (other.y > this.y)
  1110. this.y = other.y;
  1111. if (other.z > this.z)
  1112. this.z = other.z;
  1113. if (other.w > this.w)
  1114. this.w = other.w;
  1115. return this;
  1116. };
  1117. // Properties
  1118. Vector4.prototype.length = function () {
  1119. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1120. };
  1121. Vector4.prototype.lengthSquared = function () {
  1122. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1123. };
  1124. // Methods
  1125. Vector4.prototype.normalize = function () {
  1126. var len = this.length();
  1127. if (len === 0)
  1128. return this;
  1129. var num = 1.0 / len;
  1130. this.x *= num;
  1131. this.y *= num;
  1132. this.z *= num;
  1133. this.w *= num;
  1134. return this;
  1135. };
  1136. Vector4.prototype.clone = function () {
  1137. return new Vector4(this.x, this.y, this.z, this.w);
  1138. };
  1139. Vector4.prototype.copyFrom = function (source) {
  1140. this.x = source.x;
  1141. this.y = source.y;
  1142. this.z = source.z;
  1143. this.w = source.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1147. this.x = x;
  1148. this.y = y;
  1149. this.z = z;
  1150. this.w = w;
  1151. return this;
  1152. };
  1153. // Statics
  1154. Vector4.FromArray = function (array, offset) {
  1155. if (!offset) {
  1156. offset = 0;
  1157. }
  1158. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1159. };
  1160. Vector4.FromArrayToRef = function (array, offset, result) {
  1161. result.x = array[offset];
  1162. result.y = array[offset + 1];
  1163. result.z = array[offset + 2];
  1164. result.w = array[offset + 3];
  1165. };
  1166. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1167. result.x = array[offset];
  1168. result.y = array[offset + 1];
  1169. result.z = array[offset + 2];
  1170. result.w = array[offset + 3];
  1171. };
  1172. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1173. result.x = x;
  1174. result.y = y;
  1175. result.z = z;
  1176. result.w = w;
  1177. };
  1178. Vector4.Zero = function () {
  1179. return new Vector4(0, 0, 0, 0);
  1180. };
  1181. Vector4.Normalize = function (vector) {
  1182. var result = Vector4.Zero();
  1183. Vector4.NormalizeToRef(vector, result);
  1184. return result;
  1185. };
  1186. Vector4.NormalizeToRef = function (vector, result) {
  1187. result.copyFrom(vector);
  1188. result.normalize();
  1189. };
  1190. Vector4.Minimize = function (left, right) {
  1191. var min = left.clone();
  1192. min.MinimizeInPlace(right);
  1193. return min;
  1194. };
  1195. Vector4.Maximize = function (left, right) {
  1196. var max = left.clone();
  1197. max.MaximizeInPlace(right);
  1198. return max;
  1199. };
  1200. Vector4.Distance = function (value1, value2) {
  1201. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1202. };
  1203. Vector4.DistanceSquared = function (value1, value2) {
  1204. var x = value1.x - value2.x;
  1205. var y = value1.y - value2.y;
  1206. var z = value1.z - value2.z;
  1207. var w = value1.w - value2.w;
  1208. return (x * x) + (y * y) + (z * z) + (w * w);
  1209. };
  1210. Vector4.Center = function (value1, value2) {
  1211. var center = value1.add(value2);
  1212. center.scaleInPlace(0.5);
  1213. return center;
  1214. };
  1215. return Vector4;
  1216. })();
  1217. BABYLON.Vector4 = Vector4;
  1218. var Quaternion = (function () {
  1219. function Quaternion(x, y, z, w) {
  1220. if (x === void 0) { x = 0; }
  1221. if (y === void 0) { y = 0; }
  1222. if (z === void 0) { z = 0; }
  1223. if (w === void 0) { w = 1; }
  1224. this.x = x;
  1225. this.y = y;
  1226. this.z = z;
  1227. this.w = w;
  1228. }
  1229. Quaternion.prototype.toString = function () {
  1230. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1231. };
  1232. Quaternion.prototype.asArray = function () {
  1233. return [this.x, this.y, this.z, this.w];
  1234. };
  1235. Quaternion.prototype.equals = function (otherQuaternion) {
  1236. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1237. };
  1238. Quaternion.prototype.clone = function () {
  1239. return new Quaternion(this.x, this.y, this.z, this.w);
  1240. };
  1241. Quaternion.prototype.copyFrom = function (other) {
  1242. this.x = other.x;
  1243. this.y = other.y;
  1244. this.z = other.z;
  1245. this.w = other.w;
  1246. return this;
  1247. };
  1248. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1249. this.x = x;
  1250. this.y = y;
  1251. this.z = z;
  1252. this.w = w;
  1253. return this;
  1254. };
  1255. Quaternion.prototype.add = function (other) {
  1256. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1257. };
  1258. Quaternion.prototype.subtract = function (other) {
  1259. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1260. };
  1261. Quaternion.prototype.scale = function (value) {
  1262. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1263. };
  1264. Quaternion.prototype.multiply = function (q1) {
  1265. var result = new Quaternion(0, 0, 0, 1.0);
  1266. this.multiplyToRef(q1, result);
  1267. return result;
  1268. };
  1269. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1270. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1271. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1272. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1273. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1274. result.copyFromFloats(x, y, z, w);
  1275. return this;
  1276. };
  1277. Quaternion.prototype.multiplyInPlace = function (q1) {
  1278. this.multiplyToRef(q1, this);
  1279. return this;
  1280. };
  1281. Quaternion.prototype.length = function () {
  1282. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1283. };
  1284. Quaternion.prototype.normalize = function () {
  1285. var length = 1.0 / this.length();
  1286. this.x *= length;
  1287. this.y *= length;
  1288. this.z *= length;
  1289. this.w *= length;
  1290. return this;
  1291. };
  1292. Quaternion.prototype.toEulerAngles = function () {
  1293. var result = Vector3.Zero();
  1294. this.toEulerAnglesToRef(result);
  1295. return result;
  1296. };
  1297. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1298. //result is an EulerAngles in the in the z-x-z convention
  1299. var qx = this.x;
  1300. var qy = this.y;
  1301. var qz = this.z;
  1302. var qw = this.w;
  1303. var qxy = qx * qy;
  1304. var qxz = qx * qz;
  1305. var qwy = qw * qy;
  1306. var qwz = qw * qz;
  1307. var qwx = qw * qx;
  1308. var qyz = qy * qz;
  1309. var sqx = qx * qx;
  1310. var sqy = qy * qy;
  1311. var determinant = sqx + sqy;
  1312. if (determinant !== 0.000 && determinant !== 1.000) {
  1313. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1314. result.y = Math.acos(1 - 2 * determinant);
  1315. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1316. }
  1317. else {
  1318. if (determinant === 0.0) {
  1319. result.x = 0.0;
  1320. result.y = 0.0;
  1321. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1322. }
  1323. else {
  1324. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1325. result.y = Math.PI;
  1326. result.z = 0.0;
  1327. }
  1328. }
  1329. return this;
  1330. };
  1331. Quaternion.prototype.toRotationMatrix = function (result) {
  1332. var xx = this.x * this.x;
  1333. var yy = this.y * this.y;
  1334. var zz = this.z * this.z;
  1335. var xy = this.x * this.y;
  1336. var zw = this.z * this.w;
  1337. var zx = this.z * this.x;
  1338. var yw = this.y * this.w;
  1339. var yz = this.y * this.z;
  1340. var xw = this.x * this.w;
  1341. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1342. result.m[1] = 2.0 * (xy + zw);
  1343. result.m[2] = 2.0 * (zx - yw);
  1344. result.m[3] = 0;
  1345. result.m[4] = 2.0 * (xy - zw);
  1346. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1347. result.m[6] = 2.0 * (yz + xw);
  1348. result.m[7] = 0;
  1349. result.m[8] = 2.0 * (zx + yw);
  1350. result.m[9] = 2.0 * (yz - xw);
  1351. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1352. result.m[11] = 0;
  1353. result.m[12] = 0;
  1354. result.m[13] = 0;
  1355. result.m[14] = 0;
  1356. result.m[15] = 1.0;
  1357. return this;
  1358. };
  1359. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1360. Quaternion.FromRotationMatrixToRef(matrix, this);
  1361. return this;
  1362. };
  1363. // Statics
  1364. Quaternion.FromRotationMatrix = function (matrix) {
  1365. var result = new Quaternion();
  1366. Quaternion.FromRotationMatrixToRef(matrix, result);
  1367. return result;
  1368. };
  1369. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1370. var data = matrix.m;
  1371. var m11 = data[0], m12 = data[4], m13 = data[8];
  1372. var m21 = data[1], m22 = data[5], m23 = data[9];
  1373. var m31 = data[2], m32 = data[6], m33 = data[10];
  1374. var trace = m11 + m22 + m33;
  1375. var s;
  1376. if (trace > 0) {
  1377. s = 0.5 / Math.sqrt(trace + 1.0);
  1378. result.w = 0.25 / s;
  1379. result.x = (m32 - m23) * s;
  1380. result.y = (m13 - m31) * s;
  1381. result.z = (m21 - m12) * s;
  1382. }
  1383. else if (m11 > m22 && m11 > m33) {
  1384. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1385. result.w = (m32 - m23) / s;
  1386. result.x = 0.25 * s;
  1387. result.y = (m12 + m21) / s;
  1388. result.z = (m13 + m31) / s;
  1389. }
  1390. else if (m22 > m33) {
  1391. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1392. result.w = (m13 - m31) / s;
  1393. result.x = (m12 + m21) / s;
  1394. result.y = 0.25 * s;
  1395. result.z = (m23 + m32) / s;
  1396. }
  1397. else {
  1398. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1399. result.w = (m21 - m12) / s;
  1400. result.x = (m13 + m31) / s;
  1401. result.y = (m23 + m32) / s;
  1402. result.z = 0.25 * s;
  1403. }
  1404. };
  1405. Quaternion.Inverse = function (q) {
  1406. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1407. };
  1408. Quaternion.Identity = function () {
  1409. return new Quaternion(0, 0, 0, 1);
  1410. };
  1411. Quaternion.RotationAxis = function (axis, angle) {
  1412. var result = new Quaternion();
  1413. var sin = Math.sin(angle / 2);
  1414. axis.normalize();
  1415. result.w = Math.cos(angle / 2);
  1416. result.x = axis.x * sin;
  1417. result.y = axis.y * sin;
  1418. result.z = axis.z * sin;
  1419. return result;
  1420. };
  1421. Quaternion.FromArray = function (array, offset) {
  1422. if (!offset) {
  1423. offset = 0;
  1424. }
  1425. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1426. };
  1427. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1428. var result = new Quaternion();
  1429. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1430. return result;
  1431. };
  1432. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1433. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1434. var halfRoll = roll * 0.5;
  1435. var halfPitch = pitch * 0.5;
  1436. var halfYaw = yaw * 0.5;
  1437. var sinRoll = Math.sin(halfRoll);
  1438. var cosRoll = Math.cos(halfRoll);
  1439. var sinPitch = Math.sin(halfPitch);
  1440. var cosPitch = Math.cos(halfPitch);
  1441. var sinYaw = Math.sin(halfYaw);
  1442. var cosYaw = Math.cos(halfYaw);
  1443. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1444. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1445. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1446. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1447. };
  1448. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1449. var result = new Quaternion();
  1450. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1451. return result;
  1452. };
  1453. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1454. // Produces a quaternion from Euler angles in the z-x-z orientation
  1455. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1456. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1457. var halfBeta = beta * 0.5;
  1458. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1459. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1460. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1461. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1462. };
  1463. Quaternion.Slerp = function (left, right, amount) {
  1464. var num2;
  1465. var num3;
  1466. var num = amount;
  1467. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1468. var flag = false;
  1469. if (num4 < 0) {
  1470. flag = true;
  1471. num4 = -num4;
  1472. }
  1473. if (num4 > 0.999999) {
  1474. num3 = 1 - num;
  1475. num2 = flag ? -num : num;
  1476. }
  1477. else {
  1478. var num5 = Math.acos(num4);
  1479. var num6 = (1.0 / Math.sin(num5));
  1480. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1481. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1482. }
  1483. 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));
  1484. };
  1485. return Quaternion;
  1486. })();
  1487. BABYLON.Quaternion = Quaternion;
  1488. var Matrix = (function () {
  1489. function Matrix() {
  1490. this.m = new Float32Array(16);
  1491. }
  1492. // Properties
  1493. Matrix.prototype.isIdentity = function () {
  1494. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1495. return false;
  1496. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1497. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1498. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1499. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1500. return false;
  1501. return true;
  1502. };
  1503. Matrix.prototype.determinant = function () {
  1504. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1505. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1506. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1507. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1508. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1509. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1510. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1511. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1512. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1513. };
  1514. // Methods
  1515. Matrix.prototype.toArray = function () {
  1516. return this.m;
  1517. };
  1518. Matrix.prototype.asArray = function () {
  1519. return this.toArray();
  1520. };
  1521. Matrix.prototype.invert = function () {
  1522. this.invertToRef(this);
  1523. return this;
  1524. };
  1525. Matrix.prototype.reset = function () {
  1526. for (var index = 0; index < 16; index++) {
  1527. this.m[index] = 0;
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.add = function (other) {
  1532. var result = new Matrix();
  1533. this.addToRef(other, result);
  1534. return result;
  1535. };
  1536. Matrix.prototype.addToRef = function (other, result) {
  1537. for (var index = 0; index < 16; index++) {
  1538. result.m[index] = this.m[index] + other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.addToSelf = function (other) {
  1543. for (var index = 0; index < 16; index++) {
  1544. this.m[index] += other.m[index];
  1545. }
  1546. return this;
  1547. };
  1548. Matrix.prototype.invertToRef = function (other) {
  1549. var l1 = this.m[0];
  1550. var l2 = this.m[1];
  1551. var l3 = this.m[2];
  1552. var l4 = this.m[3];
  1553. var l5 = this.m[4];
  1554. var l6 = this.m[5];
  1555. var l7 = this.m[6];
  1556. var l8 = this.m[7];
  1557. var l9 = this.m[8];
  1558. var l10 = this.m[9];
  1559. var l11 = this.m[10];
  1560. var l12 = this.m[11];
  1561. var l13 = this.m[12];
  1562. var l14 = this.m[13];
  1563. var l15 = this.m[14];
  1564. var l16 = this.m[15];
  1565. var l17 = (l11 * l16) - (l12 * l15);
  1566. var l18 = (l10 * l16) - (l12 * l14);
  1567. var l19 = (l10 * l15) - (l11 * l14);
  1568. var l20 = (l9 * l16) - (l12 * l13);
  1569. var l21 = (l9 * l15) - (l11 * l13);
  1570. var l22 = (l9 * l14) - (l10 * l13);
  1571. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1572. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1573. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1574. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1575. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1576. var l28 = (l7 * l16) - (l8 * l15);
  1577. var l29 = (l6 * l16) - (l8 * l14);
  1578. var l30 = (l6 * l15) - (l7 * l14);
  1579. var l31 = (l5 * l16) - (l8 * l13);
  1580. var l32 = (l5 * l15) - (l7 * l13);
  1581. var l33 = (l5 * l14) - (l6 * l13);
  1582. var l34 = (l7 * l12) - (l8 * l11);
  1583. var l35 = (l6 * l12) - (l8 * l10);
  1584. var l36 = (l6 * l11) - (l7 * l10);
  1585. var l37 = (l5 * l12) - (l8 * l9);
  1586. var l38 = (l5 * l11) - (l7 * l9);
  1587. var l39 = (l5 * l10) - (l6 * l9);
  1588. other.m[0] = l23 * l27;
  1589. other.m[4] = l24 * l27;
  1590. other.m[8] = l25 * l27;
  1591. other.m[12] = l26 * l27;
  1592. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1593. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1594. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1595. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1596. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1597. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1598. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1599. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1600. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1601. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1602. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1603. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1604. return this;
  1605. };
  1606. Matrix.prototype.setTranslation = function (vector3) {
  1607. this.m[12] = vector3.x;
  1608. this.m[13] = vector3.y;
  1609. this.m[14] = vector3.z;
  1610. return this;
  1611. };
  1612. Matrix.prototype.multiply = function (other) {
  1613. var result = new Matrix();
  1614. this.multiplyToRef(other, result);
  1615. return result;
  1616. };
  1617. Matrix.prototype.copyFrom = function (other) {
  1618. for (var index = 0; index < 16; index++) {
  1619. this.m[index] = other.m[index];
  1620. }
  1621. return this;
  1622. };
  1623. Matrix.prototype.copyToArray = function (array, offset) {
  1624. if (offset === void 0) { offset = 0; }
  1625. for (var index = 0; index < 16; index++) {
  1626. array[offset + index] = this.m[index];
  1627. }
  1628. return this;
  1629. };
  1630. Matrix.prototype.multiplyToRef = function (other, result) {
  1631. this.multiplyToArray(other, result.m, 0);
  1632. return this;
  1633. };
  1634. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1635. var tm0 = this.m[0];
  1636. var tm1 = this.m[1];
  1637. var tm2 = this.m[2];
  1638. var tm3 = this.m[3];
  1639. var tm4 = this.m[4];
  1640. var tm5 = this.m[5];
  1641. var tm6 = this.m[6];
  1642. var tm7 = this.m[7];
  1643. var tm8 = this.m[8];
  1644. var tm9 = this.m[9];
  1645. var tm10 = this.m[10];
  1646. var tm11 = this.m[11];
  1647. var tm12 = this.m[12];
  1648. var tm13 = this.m[13];
  1649. var tm14 = this.m[14];
  1650. var tm15 = this.m[15];
  1651. var om0 = other.m[0];
  1652. var om1 = other.m[1];
  1653. var om2 = other.m[2];
  1654. var om3 = other.m[3];
  1655. var om4 = other.m[4];
  1656. var om5 = other.m[5];
  1657. var om6 = other.m[6];
  1658. var om7 = other.m[7];
  1659. var om8 = other.m[8];
  1660. var om9 = other.m[9];
  1661. var om10 = other.m[10];
  1662. var om11 = other.m[11];
  1663. var om12 = other.m[12];
  1664. var om13 = other.m[13];
  1665. var om14 = other.m[14];
  1666. var om15 = other.m[15];
  1667. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1668. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1669. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1670. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1671. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1672. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1673. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1674. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1675. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1676. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1677. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1678. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1679. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1680. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1681. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1682. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1683. return this;
  1684. };
  1685. Matrix.prototype.equals = function (value) {
  1686. return value &&
  1687. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1688. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1689. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1690. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1691. };
  1692. Matrix.prototype.clone = function () {
  1693. 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]);
  1694. };
  1695. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1696. translation.x = this.m[12];
  1697. translation.y = this.m[13];
  1698. translation.z = this.m[14];
  1699. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1700. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1701. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1702. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1703. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1704. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1705. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1706. rotation.x = 0;
  1707. rotation.y = 0;
  1708. rotation.z = 0;
  1709. rotation.w = 1;
  1710. return false;
  1711. }
  1712. 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);
  1713. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1714. return true;
  1715. };
  1716. // Statics
  1717. Matrix.FromArray = function (array, offset) {
  1718. var result = new Matrix();
  1719. if (!offset) {
  1720. offset = 0;
  1721. }
  1722. Matrix.FromArrayToRef(array, offset, result);
  1723. return result;
  1724. };
  1725. Matrix.FromArrayToRef = function (array, offset, result) {
  1726. for (var index = 0; index < 16; index++) {
  1727. result.m[index] = array[index + offset];
  1728. }
  1729. };
  1730. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1731. for (var index = 0; index < 16; index++) {
  1732. result.m[index] = array[index + offset] * scale;
  1733. }
  1734. };
  1735. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1736. result.m[0] = initialM11;
  1737. result.m[1] = initialM12;
  1738. result.m[2] = initialM13;
  1739. result.m[3] = initialM14;
  1740. result.m[4] = initialM21;
  1741. result.m[5] = initialM22;
  1742. result.m[6] = initialM23;
  1743. result.m[7] = initialM24;
  1744. result.m[8] = initialM31;
  1745. result.m[9] = initialM32;
  1746. result.m[10] = initialM33;
  1747. result.m[11] = initialM34;
  1748. result.m[12] = initialM41;
  1749. result.m[13] = initialM42;
  1750. result.m[14] = initialM43;
  1751. result.m[15] = initialM44;
  1752. };
  1753. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1754. var result = new Matrix();
  1755. result.m[0] = initialM11;
  1756. result.m[1] = initialM12;
  1757. result.m[2] = initialM13;
  1758. result.m[3] = initialM14;
  1759. result.m[4] = initialM21;
  1760. result.m[5] = initialM22;
  1761. result.m[6] = initialM23;
  1762. result.m[7] = initialM24;
  1763. result.m[8] = initialM31;
  1764. result.m[9] = initialM32;
  1765. result.m[10] = initialM33;
  1766. result.m[11] = initialM34;
  1767. result.m[12] = initialM41;
  1768. result.m[13] = initialM42;
  1769. result.m[14] = initialM43;
  1770. result.m[15] = initialM44;
  1771. return result;
  1772. };
  1773. Matrix.Compose = function (scale, rotation, translation) {
  1774. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1775. var rotationMatrix = Matrix.Identity();
  1776. rotation.toRotationMatrix(rotationMatrix);
  1777. result = result.multiply(rotationMatrix);
  1778. result.setTranslation(translation);
  1779. return result;
  1780. };
  1781. Matrix.Identity = function () {
  1782. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1783. };
  1784. Matrix.IdentityToRef = function (result) {
  1785. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1786. };
  1787. Matrix.Zero = function () {
  1788. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1789. };
  1790. Matrix.RotationX = function (angle) {
  1791. var result = new Matrix();
  1792. Matrix.RotationXToRef(angle, result);
  1793. return result;
  1794. };
  1795. Matrix.Invert = function (source) {
  1796. var result = new Matrix();
  1797. source.invertToRef(result);
  1798. return result;
  1799. };
  1800. Matrix.RotationXToRef = function (angle, result) {
  1801. var s = Math.sin(angle);
  1802. var c = Math.cos(angle);
  1803. result.m[0] = 1.0;
  1804. result.m[15] = 1.0;
  1805. result.m[5] = c;
  1806. result.m[10] = c;
  1807. result.m[9] = -s;
  1808. result.m[6] = s;
  1809. result.m[1] = 0;
  1810. result.m[2] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[7] = 0;
  1814. result.m[8] = 0;
  1815. result.m[11] = 0;
  1816. result.m[12] = 0;
  1817. result.m[13] = 0;
  1818. result.m[14] = 0;
  1819. };
  1820. Matrix.RotationY = function (angle) {
  1821. var result = new Matrix();
  1822. Matrix.RotationYToRef(angle, result);
  1823. return result;
  1824. };
  1825. Matrix.RotationYToRef = function (angle, result) {
  1826. var s = Math.sin(angle);
  1827. var c = Math.cos(angle);
  1828. result.m[5] = 1.0;
  1829. result.m[15] = 1.0;
  1830. result.m[0] = c;
  1831. result.m[2] = -s;
  1832. result.m[8] = s;
  1833. result.m[10] = c;
  1834. result.m[1] = 0;
  1835. result.m[3] = 0;
  1836. result.m[4] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[9] = 0;
  1840. result.m[11] = 0;
  1841. result.m[12] = 0;
  1842. result.m[13] = 0;
  1843. result.m[14] = 0;
  1844. };
  1845. Matrix.RotationZ = function (angle) {
  1846. var result = new Matrix();
  1847. Matrix.RotationZToRef(angle, result);
  1848. return result;
  1849. };
  1850. Matrix.RotationZToRef = function (angle, result) {
  1851. var s = Math.sin(angle);
  1852. var c = Math.cos(angle);
  1853. result.m[10] = 1.0;
  1854. result.m[15] = 1.0;
  1855. result.m[0] = c;
  1856. result.m[1] = s;
  1857. result.m[4] = -s;
  1858. result.m[5] = c;
  1859. result.m[2] = 0;
  1860. result.m[3] = 0;
  1861. result.m[6] = 0;
  1862. result.m[7] = 0;
  1863. result.m[8] = 0;
  1864. result.m[9] = 0;
  1865. result.m[11] = 0;
  1866. result.m[12] = 0;
  1867. result.m[13] = 0;
  1868. result.m[14] = 0;
  1869. };
  1870. Matrix.RotationAxis = function (axis, angle) {
  1871. var result = Matrix.Zero();
  1872. Matrix.RotationAxisToRef(axis, angle, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1876. var s = Math.sin(-angle);
  1877. var c = Math.cos(-angle);
  1878. var c1 = 1 - c;
  1879. axis.normalize();
  1880. result.m[0] = (axis.x * axis.x) * c1 + c;
  1881. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1882. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1883. result.m[3] = 0.0;
  1884. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1885. result.m[5] = (axis.y * axis.y) * c1 + c;
  1886. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1887. result.m[7] = 0.0;
  1888. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1889. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1890. result.m[10] = (axis.z * axis.z) * c1 + c;
  1891. result.m[11] = 0.0;
  1892. result.m[15] = 1.0;
  1893. };
  1894. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1895. var result = new Matrix();
  1896. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1897. return result;
  1898. };
  1899. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1900. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1901. this._tempQuaternion.toRotationMatrix(result);
  1902. };
  1903. Matrix.Scaling = function (x, y, z) {
  1904. var result = Matrix.Zero();
  1905. Matrix.ScalingToRef(x, y, z, result);
  1906. return result;
  1907. };
  1908. Matrix.ScalingToRef = function (x, y, z, result) {
  1909. result.m[0] = x;
  1910. result.m[1] = 0;
  1911. result.m[2] = 0;
  1912. result.m[3] = 0;
  1913. result.m[4] = 0;
  1914. result.m[5] = y;
  1915. result.m[6] = 0;
  1916. result.m[7] = 0;
  1917. result.m[8] = 0;
  1918. result.m[9] = 0;
  1919. result.m[10] = z;
  1920. result.m[11] = 0;
  1921. result.m[12] = 0;
  1922. result.m[13] = 0;
  1923. result.m[14] = 0;
  1924. result.m[15] = 1.0;
  1925. };
  1926. Matrix.Translation = function (x, y, z) {
  1927. var result = Matrix.Identity();
  1928. Matrix.TranslationToRef(x, y, z, result);
  1929. return result;
  1930. };
  1931. Matrix.TranslationToRef = function (x, y, z, result) {
  1932. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1933. };
  1934. Matrix.Lerp = function (startValue, endValue, gradient) {
  1935. var startScale = new Vector3(0, 0, 0);
  1936. var startRotation = new Quaternion();
  1937. var startTranslation = new Vector3(0, 0, 0);
  1938. startValue.decompose(startScale, startRotation, startTranslation);
  1939. var endScale = new Vector3(0, 0, 0);
  1940. var endRotation = new Quaternion();
  1941. var endTranslation = new Vector3(0, 0, 0);
  1942. endValue.decompose(endScale, endRotation, endTranslation);
  1943. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1944. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1945. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1946. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1947. };
  1948. Matrix.LookAtLH = function (eye, target, up) {
  1949. var result = Matrix.Zero();
  1950. Matrix.LookAtLHToRef(eye, target, up, result);
  1951. return result;
  1952. };
  1953. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1954. // Z axis
  1955. target.subtractToRef(eye, this._zAxis);
  1956. this._zAxis.normalize();
  1957. // X axis
  1958. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1959. if (this._xAxis.lengthSquared() === 0) {
  1960. this._xAxis.x = 1.0;
  1961. }
  1962. else {
  1963. this._xAxis.normalize();
  1964. }
  1965. // Y axis
  1966. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1967. this._yAxis.normalize();
  1968. // Eye angles
  1969. var ex = -Vector3.Dot(this._xAxis, eye);
  1970. var ey = -Vector3.Dot(this._yAxis, eye);
  1971. var ez = -Vector3.Dot(this._zAxis, eye);
  1972. 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);
  1973. };
  1974. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1975. var matrix = Matrix.Zero();
  1976. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1977. return matrix;
  1978. };
  1979. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1980. var hw = 2.0 / width;
  1981. var hh = 2.0 / height;
  1982. var id = 1.0 / (zfar - znear);
  1983. var nid = znear / (znear - zfar);
  1984. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1985. };
  1986. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1987. var matrix = Matrix.Zero();
  1988. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1989. return matrix;
  1990. };
  1991. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1992. result.m[0] = 2.0 / (right - left);
  1993. result.m[1] = result.m[2] = result.m[3] = 0;
  1994. result.m[5] = 2.0 / (top - bottom);
  1995. result.m[4] = result.m[6] = result.m[7] = 0;
  1996. result.m[10] = -1.0 / (znear - zfar);
  1997. result.m[8] = result.m[9] = result.m[11] = 0;
  1998. result.m[12] = (left + right) / (left - right);
  1999. result.m[13] = (top + bottom) / (bottom - top);
  2000. result.m[14] = znear / (znear - zfar);
  2001. result.m[15] = 1.0;
  2002. };
  2003. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2004. var matrix = Matrix.Zero();
  2005. matrix.m[0] = (2.0 * znear) / width;
  2006. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2007. matrix.m[5] = (2.0 * znear) / height;
  2008. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2009. matrix.m[10] = -zfar / (znear - zfar);
  2010. matrix.m[8] = matrix.m[9] = 0.0;
  2011. matrix.m[11] = 1.0;
  2012. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2013. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2014. return matrix;
  2015. };
  2016. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2017. var matrix = Matrix.Zero();
  2018. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2019. return matrix;
  2020. };
  2021. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2022. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2023. var tan = 1.0 / (Math.tan(fov * 0.5));
  2024. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2025. if (v_fixed) {
  2026. result.m[0] = tan / aspect;
  2027. }
  2028. else {
  2029. result.m[0] = tan;
  2030. }
  2031. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2032. if (v_fixed) {
  2033. result.m[5] = tan;
  2034. }
  2035. else {
  2036. result.m[5] = tan * aspect;
  2037. }
  2038. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2039. result.m[8] = result.m[9] = 0.0;
  2040. result.m[10] = -zfar / (znear - zfar);
  2041. result.m[11] = 1.0;
  2042. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2043. result.m[14] = (znear * zfar) / (znear - zfar);
  2044. };
  2045. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2046. var cw = viewport.width;
  2047. var ch = viewport.height;
  2048. var cx = viewport.x;
  2049. var cy = viewport.y;
  2050. 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);
  2051. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2052. };
  2053. Matrix.GetAsMatrix2x2 = function (matrix) {
  2054. return new Float32Array([
  2055. matrix.m[0], matrix.m[1],
  2056. matrix.m[4], matrix.m[5]
  2057. ]);
  2058. };
  2059. Matrix.GetAsMatrix3x3 = function (matrix) {
  2060. return new Float32Array([
  2061. matrix.m[0], matrix.m[1], matrix.m[2],
  2062. matrix.m[4], matrix.m[5], matrix.m[6],
  2063. matrix.m[8], matrix.m[9], matrix.m[10]
  2064. ]);
  2065. };
  2066. Matrix.Transpose = function (matrix) {
  2067. var result = new Matrix();
  2068. result.m[0] = matrix.m[0];
  2069. result.m[1] = matrix.m[4];
  2070. result.m[2] = matrix.m[8];
  2071. result.m[3] = matrix.m[12];
  2072. result.m[4] = matrix.m[1];
  2073. result.m[5] = matrix.m[5];
  2074. result.m[6] = matrix.m[9];
  2075. result.m[7] = matrix.m[13];
  2076. result.m[8] = matrix.m[2];
  2077. result.m[9] = matrix.m[6];
  2078. result.m[10] = matrix.m[10];
  2079. result.m[11] = matrix.m[14];
  2080. result.m[12] = matrix.m[3];
  2081. result.m[13] = matrix.m[7];
  2082. result.m[14] = matrix.m[11];
  2083. result.m[15] = matrix.m[15];
  2084. return result;
  2085. };
  2086. Matrix.Reflection = function (plane) {
  2087. var matrix = new Matrix();
  2088. Matrix.ReflectionToRef(plane, matrix);
  2089. return matrix;
  2090. };
  2091. Matrix.ReflectionToRef = function (plane, result) {
  2092. plane.normalize();
  2093. var x = plane.normal.x;
  2094. var y = plane.normal.y;
  2095. var z = plane.normal.z;
  2096. var temp = -2 * x;
  2097. var temp2 = -2 * y;
  2098. var temp3 = -2 * z;
  2099. result.m[0] = (temp * x) + 1;
  2100. result.m[1] = temp2 * x;
  2101. result.m[2] = temp3 * x;
  2102. result.m[3] = 0.0;
  2103. result.m[4] = temp * y;
  2104. result.m[5] = (temp2 * y) + 1;
  2105. result.m[6] = temp3 * y;
  2106. result.m[7] = 0.0;
  2107. result.m[8] = temp * z;
  2108. result.m[9] = temp2 * z;
  2109. result.m[10] = (temp3 * z) + 1;
  2110. result.m[11] = 0.0;
  2111. result.m[12] = temp * plane.d;
  2112. result.m[13] = temp2 * plane.d;
  2113. result.m[14] = temp3 * plane.d;
  2114. result.m[15] = 1.0;
  2115. };
  2116. Matrix._tempQuaternion = new Quaternion();
  2117. Matrix._xAxis = Vector3.Zero();
  2118. Matrix._yAxis = Vector3.Zero();
  2119. Matrix._zAxis = Vector3.Zero();
  2120. return Matrix;
  2121. })();
  2122. BABYLON.Matrix = Matrix;
  2123. var Plane = (function () {
  2124. function Plane(a, b, c, d) {
  2125. this.normal = new Vector3(a, b, c);
  2126. this.d = d;
  2127. }
  2128. Plane.prototype.asArray = function () {
  2129. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2130. };
  2131. // Methods
  2132. Plane.prototype.clone = function () {
  2133. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2134. };
  2135. Plane.prototype.normalize = function () {
  2136. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2137. var magnitude = 0;
  2138. if (norm !== 0) {
  2139. magnitude = 1.0 / norm;
  2140. }
  2141. this.normal.x *= magnitude;
  2142. this.normal.y *= magnitude;
  2143. this.normal.z *= magnitude;
  2144. this.d *= magnitude;
  2145. return this;
  2146. };
  2147. Plane.prototype.transform = function (transformation) {
  2148. var transposedMatrix = Matrix.Transpose(transformation);
  2149. var x = this.normal.x;
  2150. var y = this.normal.y;
  2151. var z = this.normal.z;
  2152. var d = this.d;
  2153. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2154. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2155. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2156. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2157. return new Plane(normalX, normalY, normalZ, finalD);
  2158. };
  2159. Plane.prototype.dotCoordinate = function (point) {
  2160. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2161. };
  2162. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2163. var x1 = point2.x - point1.x;
  2164. var y1 = point2.y - point1.y;
  2165. var z1 = point2.z - point1.z;
  2166. var x2 = point3.x - point1.x;
  2167. var y2 = point3.y - point1.y;
  2168. var z2 = point3.z - point1.z;
  2169. var yz = (y1 * z2) - (z1 * y2);
  2170. var xz = (z1 * x2) - (x1 * z2);
  2171. var xy = (x1 * y2) - (y1 * x2);
  2172. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2173. var invPyth;
  2174. if (pyth !== 0) {
  2175. invPyth = 1.0 / pyth;
  2176. }
  2177. else {
  2178. invPyth = 0;
  2179. }
  2180. this.normal.x = yz * invPyth;
  2181. this.normal.y = xz * invPyth;
  2182. this.normal.z = xy * invPyth;
  2183. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2184. return this;
  2185. };
  2186. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2187. var dot = Vector3.Dot(this.normal, direction);
  2188. return (dot <= epsilon);
  2189. };
  2190. Plane.prototype.signedDistanceTo = function (point) {
  2191. return Vector3.Dot(point, this.normal) + this.d;
  2192. };
  2193. // Statics
  2194. Plane.FromArray = function (array) {
  2195. return new Plane(array[0], array[1], array[2], array[3]);
  2196. };
  2197. Plane.FromPoints = function (point1, point2, point3) {
  2198. var result = new Plane(0, 0, 0, 0);
  2199. result.copyFromPoints(point1, point2, point3);
  2200. return result;
  2201. };
  2202. Plane.FromPositionAndNormal = function (origin, normal) {
  2203. var result = new Plane(0, 0, 0, 0);
  2204. normal.normalize();
  2205. result.normal = normal;
  2206. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2207. return result;
  2208. };
  2209. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2210. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2211. return Vector3.Dot(point, normal) + d;
  2212. };
  2213. return Plane;
  2214. })();
  2215. BABYLON.Plane = Plane;
  2216. var Viewport = (function () {
  2217. function Viewport(x, y, width, height) {
  2218. this.x = x;
  2219. this.y = y;
  2220. this.width = width;
  2221. this.height = height;
  2222. }
  2223. Viewport.prototype.toGlobal = function (engine) {
  2224. var width = engine.getRenderWidth();
  2225. var height = engine.getRenderHeight();
  2226. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2227. };
  2228. return Viewport;
  2229. })();
  2230. BABYLON.Viewport = Viewport;
  2231. var Frustum = (function () {
  2232. function Frustum() {
  2233. }
  2234. Frustum.GetPlanes = function (transform) {
  2235. var frustumPlanes = [];
  2236. for (var index = 0; index < 6; index++) {
  2237. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2238. }
  2239. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2240. return frustumPlanes;
  2241. };
  2242. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2243. // Near
  2244. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2245. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2246. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2247. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2248. frustumPlanes[0].normalize();
  2249. // Far
  2250. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2251. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2252. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2253. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2254. frustumPlanes[1].normalize();
  2255. // Left
  2256. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2257. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2258. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2259. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2260. frustumPlanes[2].normalize();
  2261. // Right
  2262. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2263. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2264. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2265. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2266. frustumPlanes[3].normalize();
  2267. // Top
  2268. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2269. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2270. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2271. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2272. frustumPlanes[4].normalize();
  2273. // Bottom
  2274. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2275. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2276. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2277. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2278. frustumPlanes[5].normalize();
  2279. };
  2280. return Frustum;
  2281. })();
  2282. BABYLON.Frustum = Frustum;
  2283. var Ray = (function () {
  2284. function Ray(origin, direction, length) {
  2285. if (length === void 0) { length = Number.MAX_VALUE; }
  2286. this.origin = origin;
  2287. this.direction = direction;
  2288. this.length = length;
  2289. }
  2290. // Methods
  2291. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2292. var d = 0.0;
  2293. var maxValue = Number.MAX_VALUE;
  2294. var inv;
  2295. var min;
  2296. var max;
  2297. var temp;
  2298. if (Math.abs(this.direction.x) < 0.0000001) {
  2299. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2300. return false;
  2301. }
  2302. }
  2303. else {
  2304. inv = 1.0 / this.direction.x;
  2305. min = (minimum.x - this.origin.x) * inv;
  2306. max = (maximum.x - this.origin.x) * inv;
  2307. if (max === -Infinity) {
  2308. max = Infinity;
  2309. }
  2310. if (min > max) {
  2311. temp = min;
  2312. min = max;
  2313. max = temp;
  2314. }
  2315. d = Math.max(min, d);
  2316. maxValue = Math.min(max, maxValue);
  2317. if (d > maxValue) {
  2318. return false;
  2319. }
  2320. }
  2321. if (Math.abs(this.direction.y) < 0.0000001) {
  2322. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2323. return false;
  2324. }
  2325. }
  2326. else {
  2327. inv = 1.0 / this.direction.y;
  2328. min = (minimum.y - this.origin.y) * inv;
  2329. max = (maximum.y - this.origin.y) * inv;
  2330. if (max === -Infinity) {
  2331. max = Infinity;
  2332. }
  2333. if (min > max) {
  2334. temp = min;
  2335. min = max;
  2336. max = temp;
  2337. }
  2338. d = Math.max(min, d);
  2339. maxValue = Math.min(max, maxValue);
  2340. if (d > maxValue) {
  2341. return false;
  2342. }
  2343. }
  2344. if (Math.abs(this.direction.z) < 0.0000001) {
  2345. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2346. return false;
  2347. }
  2348. }
  2349. else {
  2350. inv = 1.0 / this.direction.z;
  2351. min = (minimum.z - this.origin.z) * inv;
  2352. max = (maximum.z - this.origin.z) * inv;
  2353. if (max === -Infinity) {
  2354. max = Infinity;
  2355. }
  2356. if (min > max) {
  2357. temp = min;
  2358. min = max;
  2359. max = temp;
  2360. }
  2361. d = Math.max(min, d);
  2362. maxValue = Math.min(max, maxValue);
  2363. if (d > maxValue) {
  2364. return false;
  2365. }
  2366. }
  2367. return true;
  2368. };
  2369. Ray.prototype.intersectsBox = function (box) {
  2370. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2371. };
  2372. Ray.prototype.intersectsSphere = function (sphere) {
  2373. var x = sphere.center.x - this.origin.x;
  2374. var y = sphere.center.y - this.origin.y;
  2375. var z = sphere.center.z - this.origin.z;
  2376. var pyth = (x * x) + (y * y) + (z * z);
  2377. var rr = sphere.radius * sphere.radius;
  2378. if (pyth <= rr) {
  2379. return true;
  2380. }
  2381. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2382. if (dot < 0.0) {
  2383. return false;
  2384. }
  2385. var temp = pyth - (dot * dot);
  2386. return temp <= rr;
  2387. };
  2388. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2389. if (!this._edge1) {
  2390. this._edge1 = Vector3.Zero();
  2391. this._edge2 = Vector3.Zero();
  2392. this._pvec = Vector3.Zero();
  2393. this._tvec = Vector3.Zero();
  2394. this._qvec = Vector3.Zero();
  2395. }
  2396. vertex1.subtractToRef(vertex0, this._edge1);
  2397. vertex2.subtractToRef(vertex0, this._edge2);
  2398. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2399. var det = Vector3.Dot(this._edge1, this._pvec);
  2400. if (det === 0) {
  2401. return null;
  2402. }
  2403. var invdet = 1 / det;
  2404. this.origin.subtractToRef(vertex0, this._tvec);
  2405. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2406. if (bu < 0 || bu > 1.0) {
  2407. return null;
  2408. }
  2409. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2410. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2411. if (bv < 0 || bu + bv > 1.0) {
  2412. return null;
  2413. }
  2414. //check if the distance is longer than the predefined length.
  2415. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2416. if (distance > this.length) {
  2417. return null;
  2418. }
  2419. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2420. };
  2421. // Statics
  2422. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2423. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2424. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2425. var direction = end.subtract(start);
  2426. direction.normalize();
  2427. return new Ray(start, direction);
  2428. };
  2429. /**
  2430. * 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
  2431. * transformed to the given world matrix.
  2432. * @param origin The origin point
  2433. * @param end The end point
  2434. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2435. */
  2436. Ray.CreateNewFromTo = function (origin, end, world) {
  2437. if (world === void 0) { world = Matrix.Identity(); }
  2438. var direction = end.subtract(origin);
  2439. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2440. direction.normalize();
  2441. return Ray.Transform(new Ray(origin, direction, length), world);
  2442. };
  2443. Ray.Transform = function (ray, matrix) {
  2444. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2445. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2446. return new Ray(newOrigin, newDirection, ray.length);
  2447. };
  2448. return Ray;
  2449. })();
  2450. BABYLON.Ray = Ray;
  2451. (function (Space) {
  2452. Space[Space["LOCAL"] = 0] = "LOCAL";
  2453. Space[Space["WORLD"] = 1] = "WORLD";
  2454. })(BABYLON.Space || (BABYLON.Space = {}));
  2455. var Space = BABYLON.Space;
  2456. var Axis = (function () {
  2457. function Axis() {
  2458. }
  2459. Axis.X = new Vector3(1, 0, 0);
  2460. Axis.Y = new Vector3(0, 1, 0);
  2461. Axis.Z = new Vector3(0, 0, 1);
  2462. return Axis;
  2463. })();
  2464. BABYLON.Axis = Axis;
  2465. ;
  2466. var BezierCurve = (function () {
  2467. function BezierCurve() {
  2468. }
  2469. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2470. // Extract X (which is equal to time here)
  2471. var f0 = 1 - 3 * x2 + 3 * x1;
  2472. var f1 = 3 * x2 - 6 * x1;
  2473. var f2 = 3 * x1;
  2474. var refinedT = t;
  2475. for (var i = 0; i < 5; i++) {
  2476. var refinedT2 = refinedT * refinedT;
  2477. var refinedT3 = refinedT2 * refinedT;
  2478. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2479. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2480. refinedT -= (x - t) * slope;
  2481. refinedT = Math.min(1, Math.max(0, refinedT));
  2482. }
  2483. // Resolve cubic bezier for the given x
  2484. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2485. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2486. Math.pow(refinedT, 3);
  2487. };
  2488. return BezierCurve;
  2489. })();
  2490. BABYLON.BezierCurve = BezierCurve;
  2491. (function (Orientation) {
  2492. Orientation[Orientation["CW"] = 0] = "CW";
  2493. Orientation[Orientation["CCW"] = 1] = "CCW";
  2494. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2495. var Orientation = BABYLON.Orientation;
  2496. var Angle = (function () {
  2497. function Angle(radians) {
  2498. var _this = this;
  2499. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2500. this.radians = function () { return _this._radians; };
  2501. this._radians = radians;
  2502. if (this._radians < 0)
  2503. this._radians += (2 * Math.PI);
  2504. }
  2505. Angle.BetweenTwoPoints = function (a, b) {
  2506. var delta = b.subtract(a);
  2507. var theta = Math.atan2(delta.y, delta.x);
  2508. return new Angle(theta);
  2509. };
  2510. Angle.FromRadians = function (radians) {
  2511. return new Angle(radians);
  2512. };
  2513. Angle.FromDegrees = function (degrees) {
  2514. return new Angle(degrees * Math.PI / 180);
  2515. };
  2516. return Angle;
  2517. })();
  2518. BABYLON.Angle = Angle;
  2519. var Arc2 = (function () {
  2520. function Arc2(startPoint, midPoint, endPoint) {
  2521. this.startPoint = startPoint;
  2522. this.midPoint = midPoint;
  2523. this.endPoint = endPoint;
  2524. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2525. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2526. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2527. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2528. 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);
  2529. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2530. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2531. var a1 = this.startAngle.degrees();
  2532. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2533. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2534. // angles correction
  2535. if (a2 - a1 > +180.0)
  2536. a2 -= 360.0;
  2537. if (a2 - a1 < -180.0)
  2538. a2 += 360.0;
  2539. if (a3 - a2 > +180.0)
  2540. a3 -= 360.0;
  2541. if (a3 - a2 < -180.0)
  2542. a3 += 360.0;
  2543. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2544. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2545. }
  2546. return Arc2;
  2547. })();
  2548. BABYLON.Arc2 = Arc2;
  2549. var PathCursor = (function () {
  2550. function PathCursor(path) {
  2551. this.path = path;
  2552. this._onchange = new Array();
  2553. this.value = 0;
  2554. this.animations = new Array();
  2555. }
  2556. PathCursor.prototype.getPoint = function () {
  2557. var point = this.path.getPointAtLengthPosition(this.value);
  2558. return new Vector3(point.x, 0, point.y);
  2559. };
  2560. PathCursor.prototype.moveAhead = function (step) {
  2561. if (step === void 0) { step = 0.002; }
  2562. this.move(step);
  2563. return this;
  2564. };
  2565. PathCursor.prototype.moveBack = function (step) {
  2566. if (step === void 0) { step = 0.002; }
  2567. this.move(-step);
  2568. return this;
  2569. };
  2570. PathCursor.prototype.move = function (step) {
  2571. if (Math.abs(step) > 1) {
  2572. throw "step size should be less than 1.";
  2573. }
  2574. this.value += step;
  2575. this.ensureLimits();
  2576. this.raiseOnChange();
  2577. return this;
  2578. };
  2579. PathCursor.prototype.ensureLimits = function () {
  2580. while (this.value > 1) {
  2581. this.value -= 1;
  2582. }
  2583. while (this.value < 0) {
  2584. this.value += 1;
  2585. }
  2586. return this;
  2587. };
  2588. // used by animation engine
  2589. PathCursor.prototype.markAsDirty = function (propertyName) {
  2590. this.ensureLimits();
  2591. this.raiseOnChange();
  2592. return this;
  2593. };
  2594. PathCursor.prototype.raiseOnChange = function () {
  2595. var _this = this;
  2596. this._onchange.forEach(function (f) { return f(_this); });
  2597. return this;
  2598. };
  2599. PathCursor.prototype.onchange = function (f) {
  2600. this._onchange.push(f);
  2601. return this;
  2602. };
  2603. return PathCursor;
  2604. })();
  2605. BABYLON.PathCursor = PathCursor;
  2606. var Path2 = (function () {
  2607. function Path2(x, y) {
  2608. this._points = new Array();
  2609. this._length = 0;
  2610. this.closed = false;
  2611. this._points.push(new Vector2(x, y));
  2612. }
  2613. Path2.prototype.addLineTo = function (x, y) {
  2614. if (closed) {
  2615. BABYLON.Tools.Error("cannot add lines to closed paths");
  2616. return this;
  2617. }
  2618. var newPoint = new Vector2(x, y);
  2619. var previousPoint = this._points[this._points.length - 1];
  2620. this._points.push(newPoint);
  2621. this._length += newPoint.subtract(previousPoint).length();
  2622. return this;
  2623. };
  2624. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2625. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2626. if (closed) {
  2627. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2628. return this;
  2629. }
  2630. var startPoint = this._points[this._points.length - 1];
  2631. var midPoint = new Vector2(midX, midY);
  2632. var endPoint = new Vector2(endX, endY);
  2633. var arc = new Arc2(startPoint, midPoint, endPoint);
  2634. var increment = arc.angle.radians() / numberOfSegments;
  2635. if (arc.orientation === Orientation.CW)
  2636. increment *= -1;
  2637. var currentAngle = arc.startAngle.radians() + increment;
  2638. for (var i = 0; i < numberOfSegments; i++) {
  2639. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2640. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2641. this.addLineTo(x, y);
  2642. currentAngle += increment;
  2643. }
  2644. return this;
  2645. };
  2646. Path2.prototype.close = function () {
  2647. this.closed = true;
  2648. return this;
  2649. };
  2650. Path2.prototype.length = function () {
  2651. var result = this._length;
  2652. if (!this.closed) {
  2653. var lastPoint = this._points[this._points.length - 1];
  2654. var firstPoint = this._points[0];
  2655. result += (firstPoint.subtract(lastPoint).length());
  2656. }
  2657. return result;
  2658. };
  2659. Path2.prototype.getPoints = function () {
  2660. return this._points;
  2661. };
  2662. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2663. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2664. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2665. return Vector2.Zero();
  2666. }
  2667. var lengthPosition = normalizedLengthPosition * this.length();
  2668. var previousOffset = 0;
  2669. for (var i = 0; i < this._points.length; i++) {
  2670. var j = (i + 1) % this._points.length;
  2671. var a = this._points[i];
  2672. var b = this._points[j];
  2673. var bToA = b.subtract(a);
  2674. var nextOffset = (bToA.length() + previousOffset);
  2675. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2676. var dir = bToA.normalize();
  2677. var localOffset = lengthPosition - previousOffset;
  2678. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2679. }
  2680. previousOffset = nextOffset;
  2681. }
  2682. BABYLON.Tools.Error("internal error");
  2683. return Vector2.Zero();
  2684. };
  2685. Path2.StartingAt = function (x, y) {
  2686. return new Path2(x, y);
  2687. };
  2688. return Path2;
  2689. })();
  2690. BABYLON.Path2 = Path2;
  2691. var Path3D = (function () {
  2692. /**
  2693. * new Path3D(path, normal, raw)
  2694. * path : an array of Vector3, the curve axis of the Path3D
  2695. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2696. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2697. */
  2698. function Path3D(path, firstNormal, raw) {
  2699. this.path = path;
  2700. this._curve = new Array();
  2701. this._distances = new Array();
  2702. this._tangents = new Array();
  2703. this._normals = new Array();
  2704. this._binormals = new Array();
  2705. for (var p = 0; p < path.length; p++) {
  2706. this._curve[p] = path[p].clone(); // hard copy
  2707. }
  2708. this._raw = raw || false;
  2709. this._compute(firstNormal);
  2710. }
  2711. Path3D.prototype.getCurve = function () {
  2712. return this._curve;
  2713. };
  2714. Path3D.prototype.getTangents = function () {
  2715. return this._tangents;
  2716. };
  2717. Path3D.prototype.getNormals = function () {
  2718. return this._normals;
  2719. };
  2720. Path3D.prototype.getBinormals = function () {
  2721. return this._binormals;
  2722. };
  2723. Path3D.prototype.getDistances = function () {
  2724. return this._distances;
  2725. };
  2726. Path3D.prototype.update = function (path, firstNormal) {
  2727. for (var p = 0; p < path.length; p++) {
  2728. this._curve[p].x = path[p].x;
  2729. this._curve[p].y = path[p].y;
  2730. this._curve[p].z = path[p].z;
  2731. }
  2732. this._compute(firstNormal);
  2733. return this;
  2734. };
  2735. // private function compute() : computes tangents, normals and binormals
  2736. Path3D.prototype._compute = function (firstNormal) {
  2737. var l = this._curve.length;
  2738. // first and last tangents
  2739. this._tangents[0] = this._getFirstNonNullVector(0);
  2740. if (!this._raw) {
  2741. this._tangents[0].normalize();
  2742. }
  2743. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2744. if (!this._raw) {
  2745. this._tangents[l - 1].normalize();
  2746. }
  2747. // normals and binormals at first point : arbitrary vector with _normalVector()
  2748. var tg0 = this._tangents[0];
  2749. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2750. this._normals[0] = pp0;
  2751. if (!this._raw) {
  2752. this._normals[0].normalize();
  2753. }
  2754. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2755. if (!this._raw) {
  2756. this._binormals[0].normalize();
  2757. }
  2758. this._distances[0] = 0;
  2759. // normals and binormals : next points
  2760. var prev; // previous vector (segment)
  2761. var cur; // current vector (segment)
  2762. var curTang; // current tangent
  2763. // previous normal
  2764. var prevBinor; // previous binormal
  2765. for (var i = 1; i < l; i++) {
  2766. // tangents
  2767. prev = this._getLastNonNullVector(i);
  2768. if (i < l - 1) {
  2769. cur = this._getFirstNonNullVector(i);
  2770. this._tangents[i] = prev.add(cur);
  2771. this._tangents[i].normalize();
  2772. }
  2773. this._distances[i] = this._distances[i - 1] + prev.length();
  2774. // normals and binormals
  2775. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2776. curTang = this._tangents[i];
  2777. prevBinor = this._binormals[i - 1];
  2778. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2779. if (!this._raw) {
  2780. this._normals[i].normalize();
  2781. }
  2782. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2783. if (!this._raw) {
  2784. this._binormals[i].normalize();
  2785. }
  2786. }
  2787. };
  2788. // private function getFirstNonNullVector(index)
  2789. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2790. Path3D.prototype._getFirstNonNullVector = function (index) {
  2791. var i = 1;
  2792. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2793. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2794. i++;
  2795. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2796. }
  2797. return nNVector;
  2798. };
  2799. // private function getLastNonNullVector(index)
  2800. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2801. Path3D.prototype._getLastNonNullVector = function (index) {
  2802. var i = 1;
  2803. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2804. while (nLVector.length() === 0 && index > i + 1) {
  2805. i++;
  2806. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2807. }
  2808. return nLVector;
  2809. };
  2810. // private function normalVector(v0, vt, va) :
  2811. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2812. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2813. Path3D.prototype._normalVector = function (v0, vt, va) {
  2814. var normal0;
  2815. if (va === undefined || va === null) {
  2816. var point;
  2817. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2818. point = new Vector3(0, -1, 0);
  2819. }
  2820. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2821. point = new Vector3(1, 0, 0);
  2822. }
  2823. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2824. point = new Vector3(0, 0, 1);
  2825. }
  2826. normal0 = Vector3.Cross(vt, point);
  2827. }
  2828. else {
  2829. normal0 = Vector3.Cross(vt, va);
  2830. Vector3.CrossToRef(normal0, vt, normal0);
  2831. }
  2832. normal0.normalize();
  2833. return normal0;
  2834. };
  2835. return Path3D;
  2836. })();
  2837. BABYLON.Path3D = Path3D;
  2838. var Curve3 = (function () {
  2839. function Curve3(points) {
  2840. this._length = 0;
  2841. this._points = points;
  2842. this._length = this._computeLength(points);
  2843. }
  2844. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2845. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2846. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2847. var bez = new Array();
  2848. var equation = function (t, val0, val1, val2) {
  2849. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2850. return res;
  2851. };
  2852. for (var i = 0; i <= nbPoints; i++) {
  2853. 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)));
  2854. }
  2855. return new Curve3(bez);
  2856. };
  2857. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2858. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2859. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2860. var bez = new Array();
  2861. var equation = function (t, val0, val1, val2, val3) {
  2862. 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;
  2863. return res;
  2864. };
  2865. for (var i = 0; i <= nbPoints; i++) {
  2866. 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)));
  2867. }
  2868. return new Curve3(bez);
  2869. };
  2870. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2871. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2872. var hermite = new Array();
  2873. var step = 1 / nbPoints;
  2874. for (var i = 0; i <= nbPoints; i++) {
  2875. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2876. }
  2877. return new Curve3(hermite);
  2878. };
  2879. Curve3.prototype.getPoints = function () {
  2880. return this._points;
  2881. };
  2882. Curve3.prototype.length = function () {
  2883. return this._length;
  2884. };
  2885. Curve3.prototype.continue = function (curve) {
  2886. var lastPoint = this._points[this._points.length - 1];
  2887. var continuedPoints = this._points.slice();
  2888. var curvePoints = curve.getPoints();
  2889. for (var i = 1; i < curvePoints.length; i++) {
  2890. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2891. }
  2892. var continuedCurve = new Curve3(continuedPoints);
  2893. return continuedCurve;
  2894. };
  2895. Curve3.prototype._computeLength = function (path) {
  2896. var l = 0;
  2897. for (var i = 1; i < path.length; i++) {
  2898. l += (path[i].subtract(path[i - 1])).length();
  2899. }
  2900. return l;
  2901. };
  2902. return Curve3;
  2903. })();
  2904. BABYLON.Curve3 = Curve3;
  2905. // Vertex formats
  2906. var PositionNormalVertex = (function () {
  2907. function PositionNormalVertex(position, normal) {
  2908. if (position === void 0) { position = Vector3.Zero(); }
  2909. if (normal === void 0) { normal = Vector3.Up(); }
  2910. this.position = position;
  2911. this.normal = normal;
  2912. }
  2913. PositionNormalVertex.prototype.clone = function () {
  2914. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2915. };
  2916. return PositionNormalVertex;
  2917. })();
  2918. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2919. var PositionNormalTextureVertex = (function () {
  2920. function PositionNormalTextureVertex(position, normal, uv) {
  2921. if (position === void 0) { position = Vector3.Zero(); }
  2922. if (normal === void 0) { normal = Vector3.Up(); }
  2923. if (uv === void 0) { uv = Vector2.Zero(); }
  2924. this.position = position;
  2925. this.normal = normal;
  2926. this.uv = uv;
  2927. }
  2928. PositionNormalTextureVertex.prototype.clone = function () {
  2929. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2930. };
  2931. return PositionNormalTextureVertex;
  2932. })();
  2933. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2934. })(BABYLON || (BABYLON = {}));
  2935. var BABYLON;
  2936. (function (BABYLON) {
  2937. var Database = (function () {
  2938. function Database(urlToScene, callbackManifestChecked) {
  2939. // Handling various flavors of prefixed version of IndexedDB
  2940. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2941. this.callbackManifestChecked = callbackManifestChecked;
  2942. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2943. this.db = null;
  2944. this.enableSceneOffline = false;
  2945. this.enableTexturesOffline = false;
  2946. this.manifestVersionFound = 0;
  2947. this.mustUpdateRessources = false;
  2948. this.hasReachedQuota = false;
  2949. if (!Database.IDBStorageEnabled) {
  2950. this.callbackManifestChecked(true);
  2951. }
  2952. else {
  2953. this.checkManifestFile();
  2954. }
  2955. }
  2956. Database.prototype.checkManifestFile = function () {
  2957. var _this = this;
  2958. function noManifestFile() {
  2959. that.enableSceneOffline = false;
  2960. that.enableTexturesOffline = false;
  2961. that.callbackManifestChecked(false);
  2962. }
  2963. var that = this;
  2964. var manifestURL = this.currentSceneUrl + ".manifest";
  2965. var xhr = new XMLHttpRequest();
  2966. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2967. xhr.open("GET", manifestURLTimeStamped, true);
  2968. xhr.addEventListener("load", function () {
  2969. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2970. try {
  2971. var manifestFile = JSON.parse(xhr.response);
  2972. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2973. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2974. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2975. _this.manifestVersionFound = manifestFile.version;
  2976. }
  2977. if (_this.callbackManifestChecked) {
  2978. _this.callbackManifestChecked(true);
  2979. }
  2980. }
  2981. catch (ex) {
  2982. noManifestFile();
  2983. }
  2984. }
  2985. else {
  2986. noManifestFile();
  2987. }
  2988. }, false);
  2989. xhr.addEventListener("error", function (event) {
  2990. noManifestFile();
  2991. }, false);
  2992. try {
  2993. xhr.send();
  2994. }
  2995. catch (ex) {
  2996. BABYLON.Tools.Error("Error on XHR send request.");
  2997. that.callbackManifestChecked(false);
  2998. }
  2999. };
  3000. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3001. var _this = this;
  3002. function handleError() {
  3003. that.isSupported = false;
  3004. if (errorCallback)
  3005. errorCallback();
  3006. }
  3007. var that = this;
  3008. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3009. // Your browser doesn't support IndexedDB
  3010. this.isSupported = false;
  3011. if (errorCallback)
  3012. errorCallback();
  3013. }
  3014. else {
  3015. // If the DB hasn't been opened or created yet
  3016. if (!this.db) {
  3017. this.hasReachedQuota = false;
  3018. this.isSupported = true;
  3019. var request = this.idbFactory.open("babylonjs", 1);
  3020. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3021. request.onerror = function (event) {
  3022. handleError();
  3023. };
  3024. // executes when a version change transaction cannot complete due to other active transactions
  3025. request.onblocked = function (event) {
  3026. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3027. handleError();
  3028. };
  3029. // DB has been opened successfully
  3030. request.onsuccess = function (event) {
  3031. _this.db = request.result;
  3032. successCallback();
  3033. };
  3034. // Initialization of the DB. Creating Scenes & Textures stores
  3035. request.onupgradeneeded = function (event) {
  3036. _this.db = (event.target).result;
  3037. try {
  3038. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3039. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3040. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3041. }
  3042. catch (ex) {
  3043. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3044. handleError();
  3045. }
  3046. };
  3047. }
  3048. else {
  3049. if (successCallback)
  3050. successCallback();
  3051. }
  3052. }
  3053. };
  3054. Database.prototype.loadImageFromDB = function (url, image) {
  3055. var _this = this;
  3056. var completeURL = Database.ReturnFullUrlLocation(url);
  3057. var saveAndLoadImage = function () {
  3058. if (!_this.hasReachedQuota && _this.db !== null) {
  3059. // the texture is not yet in the DB, let's try to save it
  3060. _this._saveImageIntoDBAsync(completeURL, image);
  3061. }
  3062. else {
  3063. image.src = url;
  3064. }
  3065. };
  3066. if (!this.mustUpdateRessources) {
  3067. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3068. }
  3069. else {
  3070. saveAndLoadImage();
  3071. }
  3072. };
  3073. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3074. if (this.isSupported && this.db !== null) {
  3075. var texture;
  3076. var transaction = this.db.transaction(["textures"]);
  3077. transaction.onabort = function (event) {
  3078. image.src = url;
  3079. };
  3080. transaction.oncomplete = function (event) {
  3081. var blobTextureURL;
  3082. if (texture) {
  3083. var URL = window.URL || window.webkitURL;
  3084. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3085. image.onerror = function () {
  3086. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3087. image.src = url;
  3088. };
  3089. image.src = blobTextureURL;
  3090. }
  3091. else {
  3092. notInDBCallback();
  3093. }
  3094. };
  3095. var getRequest = transaction.objectStore("textures").get(url);
  3096. getRequest.onsuccess = function (event) {
  3097. texture = (event.target).result;
  3098. };
  3099. getRequest.onerror = function (event) {
  3100. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3101. image.src = url;
  3102. };
  3103. }
  3104. else {
  3105. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3106. image.src = url;
  3107. }
  3108. };
  3109. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3110. var _this = this;
  3111. if (this.isSupported) {
  3112. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3113. var generateBlobUrl = function () {
  3114. var blobTextureURL;
  3115. if (blob) {
  3116. var URL = window.URL || window.webkitURL;
  3117. try {
  3118. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3119. }
  3120. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3121. catch (ex) {
  3122. blobTextureURL = URL.createObjectURL(blob);
  3123. }
  3124. }
  3125. image.src = blobTextureURL;
  3126. };
  3127. if (Database.IsUASupportingBlobStorage) {
  3128. var xhr = new XMLHttpRequest(), blob;
  3129. xhr.open("GET", url, true);
  3130. xhr.responseType = "blob";
  3131. xhr.addEventListener("load", function () {
  3132. if (xhr.status === 200) {
  3133. // Blob as response (XHR2)
  3134. blob = xhr.response;
  3135. var transaction = _this.db.transaction(["textures"], "readwrite");
  3136. // the transaction could abort because of a QuotaExceededError error
  3137. transaction.onabort = function (event) {
  3138. try {
  3139. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3140. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3141. this.hasReachedQuota = true;
  3142. }
  3143. }
  3144. catch (ex) { }
  3145. generateBlobUrl();
  3146. };
  3147. transaction.oncomplete = function (event) {
  3148. generateBlobUrl();
  3149. };
  3150. var newTexture = { textureUrl: url, data: blob };
  3151. try {
  3152. // Put the blob into the dabase
  3153. var addRequest = transaction.objectStore("textures").put(newTexture);
  3154. addRequest.onsuccess = function (event) {
  3155. };
  3156. addRequest.onerror = function (event) {
  3157. generateBlobUrl();
  3158. };
  3159. }
  3160. catch (ex) {
  3161. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3162. if (ex.code === 25) {
  3163. Database.IsUASupportingBlobStorage = false;
  3164. }
  3165. image.src = url;
  3166. }
  3167. }
  3168. else {
  3169. image.src = url;
  3170. }
  3171. }, false);
  3172. xhr.addEventListener("error", function (event) {
  3173. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3174. image.src = url;
  3175. }, false);
  3176. xhr.send();
  3177. }
  3178. else {
  3179. image.src = url;
  3180. }
  3181. }
  3182. else {
  3183. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3184. image.src = url;
  3185. }
  3186. };
  3187. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3188. var _this = this;
  3189. var updateVersion = function (event) {
  3190. // the version is not yet in the DB or we need to update it
  3191. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3192. };
  3193. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3194. };
  3195. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3196. var _this = this;
  3197. if (this.isSupported) {
  3198. var version;
  3199. try {
  3200. var transaction = this.db.transaction(["versions"]);
  3201. transaction.oncomplete = function (event) {
  3202. if (version) {
  3203. // If the version in the JSON file is > than the version in DB
  3204. if (_this.manifestVersionFound > version.data) {
  3205. _this.mustUpdateRessources = true;
  3206. updateInDBCallback();
  3207. }
  3208. else {
  3209. callback(version.data);
  3210. }
  3211. }
  3212. else {
  3213. _this.mustUpdateRessources = true;
  3214. updateInDBCallback();
  3215. }
  3216. };
  3217. transaction.onabort = function (event) {
  3218. callback(-1);
  3219. };
  3220. var getRequest = transaction.objectStore("versions").get(url);
  3221. getRequest.onsuccess = function (event) {
  3222. version = (event.target).result;
  3223. };
  3224. getRequest.onerror = function (event) {
  3225. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3226. callback(-1);
  3227. };
  3228. }
  3229. catch (ex) {
  3230. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3231. callback(-1);
  3232. }
  3233. }
  3234. else {
  3235. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3236. callback(-1);
  3237. }
  3238. };
  3239. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3240. var _this = this;
  3241. if (this.isSupported && !this.hasReachedQuota) {
  3242. try {
  3243. // Open a transaction to the database
  3244. var transaction = this.db.transaction(["versions"], "readwrite");
  3245. // the transaction could abort because of a QuotaExceededError error
  3246. transaction.onabort = function (event) {
  3247. try {
  3248. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3249. _this.hasReachedQuota = true;
  3250. }
  3251. }
  3252. catch (ex) { }
  3253. callback(-1);
  3254. };
  3255. transaction.oncomplete = function (event) {
  3256. callback(_this.manifestVersionFound);
  3257. };
  3258. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3259. // Put the scene into the database
  3260. var addRequest = transaction.objectStore("versions").put(newVersion);
  3261. addRequest.onsuccess = function (event) {
  3262. };
  3263. addRequest.onerror = function (event) {
  3264. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3265. };
  3266. }
  3267. catch (ex) {
  3268. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3269. callback(-1);
  3270. }
  3271. }
  3272. else {
  3273. callback(-1);
  3274. }
  3275. };
  3276. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3277. var _this = this;
  3278. var completeUrl = Database.ReturnFullUrlLocation(url);
  3279. var saveAndLoadFile = function (event) {
  3280. // the scene is not yet in the DB, let's try to save it
  3281. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3282. };
  3283. this._checkVersionFromDB(completeUrl, function (version) {
  3284. if (version !== -1) {
  3285. if (!_this.mustUpdateRessources) {
  3286. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3287. }
  3288. else {
  3289. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3290. }
  3291. }
  3292. else {
  3293. errorCallback();
  3294. }
  3295. });
  3296. };
  3297. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3298. if (this.isSupported) {
  3299. var targetStore;
  3300. if (url.indexOf(".babylon") !== -1) {
  3301. targetStore = "scenes";
  3302. }
  3303. else {
  3304. targetStore = "textures";
  3305. }
  3306. var file;
  3307. var transaction = this.db.transaction([targetStore]);
  3308. transaction.oncomplete = function (event) {
  3309. if (file) {
  3310. callback(file.data);
  3311. }
  3312. else {
  3313. notInDBCallback();
  3314. }
  3315. };
  3316. transaction.onabort = function (event) {
  3317. notInDBCallback();
  3318. };
  3319. var getRequest = transaction.objectStore(targetStore).get(url);
  3320. getRequest.onsuccess = function (event) {
  3321. file = (event.target).result;
  3322. };
  3323. getRequest.onerror = function (event) {
  3324. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3325. notInDBCallback();
  3326. };
  3327. }
  3328. else {
  3329. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3330. callback();
  3331. }
  3332. };
  3333. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3334. var _this = this;
  3335. if (this.isSupported) {
  3336. var targetStore;
  3337. if (url.indexOf(".babylon") !== -1) {
  3338. targetStore = "scenes";
  3339. }
  3340. else {
  3341. targetStore = "textures";
  3342. }
  3343. // Create XHR
  3344. var xhr = new XMLHttpRequest(), fileData;
  3345. xhr.open("GET", url, true);
  3346. if (useArrayBuffer) {
  3347. xhr.responseType = "arraybuffer";
  3348. }
  3349. xhr.onprogress = progressCallback;
  3350. xhr.addEventListener("load", function () {
  3351. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3352. // Blob as response (XHR2)
  3353. //fileData = xhr.responseText;
  3354. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3355. if (!_this.hasReachedQuota) {
  3356. // Open a transaction to the database
  3357. var transaction = _this.db.transaction([targetStore], "readwrite");
  3358. // the transaction could abort because of a QuotaExceededError error
  3359. transaction.onabort = function (event) {
  3360. try {
  3361. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3362. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3363. this.hasReachedQuota = true;
  3364. }
  3365. }
  3366. catch (ex) { }
  3367. callback(fileData);
  3368. };
  3369. transaction.oncomplete = function (event) {
  3370. callback(fileData);
  3371. };
  3372. var newFile;
  3373. if (targetStore === "scenes") {
  3374. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3375. }
  3376. else {
  3377. newFile = { textureUrl: url, data: fileData };
  3378. }
  3379. try {
  3380. // Put the scene into the database
  3381. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3382. addRequest.onsuccess = function (event) {
  3383. };
  3384. addRequest.onerror = function (event) {
  3385. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3386. };
  3387. }
  3388. catch (ex) {
  3389. callback(fileData);
  3390. }
  3391. }
  3392. else {
  3393. callback(fileData);
  3394. }
  3395. }
  3396. else {
  3397. callback();
  3398. }
  3399. }, false);
  3400. xhr.addEventListener("error", function (event) {
  3401. BABYLON.Tools.Error("error on XHR request.");
  3402. callback();
  3403. }, false);
  3404. xhr.send();
  3405. }
  3406. else {
  3407. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3408. callback();
  3409. }
  3410. };
  3411. Database.IsUASupportingBlobStorage = true;
  3412. Database.IDBStorageEnabled = true;
  3413. Database.parseURL = function (url) {
  3414. var a = document.createElement('a');
  3415. a.href = url;
  3416. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3417. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3418. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3419. return absLocation;
  3420. };
  3421. Database.ReturnFullUrlLocation = function (url) {
  3422. if (url.indexOf("http:/") === -1) {
  3423. return (Database.parseURL(window.location.href) + url);
  3424. }
  3425. else {
  3426. return url;
  3427. }
  3428. };
  3429. return Database;
  3430. })();
  3431. BABYLON.Database = Database;
  3432. })(BABYLON || (BABYLON = {}));
  3433. var BABYLON;
  3434. (function (BABYLON) {
  3435. var Internals;
  3436. (function (Internals) {
  3437. /*
  3438. * Based on jsTGALoader - Javascript loader for TGA file
  3439. * By Vincent Thibault
  3440. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3441. */
  3442. var TGATools = (function () {
  3443. function TGATools() {
  3444. }
  3445. TGATools.GetTGAHeader = function (data) {
  3446. var offset = 0;
  3447. var header = {
  3448. id_length: data[offset++],
  3449. colormap_type: data[offset++],
  3450. image_type: data[offset++],
  3451. colormap_index: data[offset++] | data[offset++] << 8,
  3452. colormap_length: data[offset++] | data[offset++] << 8,
  3453. colormap_size: data[offset++],
  3454. origin: [
  3455. data[offset++] | data[offset++] << 8,
  3456. data[offset++] | data[offset++] << 8
  3457. ],
  3458. width: data[offset++] | data[offset++] << 8,
  3459. height: data[offset++] | data[offset++] << 8,
  3460. pixel_size: data[offset++],
  3461. flags: data[offset++]
  3462. };
  3463. return header;
  3464. };
  3465. TGATools.UploadContent = function (gl, data) {
  3466. // Not enough data to contain header ?
  3467. if (data.length < 19) {
  3468. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3469. return;
  3470. }
  3471. // Read Header
  3472. var offset = 18;
  3473. var header = TGATools.GetTGAHeader(data);
  3474. // Assume it's a valid Targa file.
  3475. if (header.id_length + offset > data.length) {
  3476. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3477. return;
  3478. }
  3479. // Skip not needed data
  3480. offset += header.id_length;
  3481. var use_rle = false;
  3482. var use_pal = false;
  3483. var use_rgb = false;
  3484. var use_grey = false;
  3485. // Get some informations.
  3486. switch (header.image_type) {
  3487. case TGATools._TYPE_RLE_INDEXED:
  3488. use_rle = true;
  3489. case TGATools._TYPE_INDEXED:
  3490. use_pal = true;
  3491. break;
  3492. case TGATools._TYPE_RLE_RGB:
  3493. use_rle = true;
  3494. case TGATools._TYPE_RGB:
  3495. use_rgb = true;
  3496. break;
  3497. case TGATools._TYPE_RLE_GREY:
  3498. use_rle = true;
  3499. case TGATools._TYPE_GREY:
  3500. use_grey = true;
  3501. break;
  3502. }
  3503. var pixel_data;
  3504. var numAlphaBits = header.flags & 0xf;
  3505. var pixel_size = header.pixel_size >> 3;
  3506. var pixel_total = header.width * header.height * pixel_size;
  3507. // Read palettes
  3508. var palettes;
  3509. if (use_pal) {
  3510. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3511. }
  3512. // Read LRE
  3513. if (use_rle) {
  3514. pixel_data = new Uint8Array(pixel_total);
  3515. var c, count, i;
  3516. var localOffset = 0;
  3517. var pixels = new Uint8Array(pixel_size);
  3518. while (offset < pixel_total && localOffset < pixel_total) {
  3519. c = data[offset++];
  3520. count = (c & 0x7f) + 1;
  3521. // RLE pixels
  3522. if (c & 0x80) {
  3523. // Bind pixel tmp array
  3524. for (i = 0; i < pixel_size; ++i) {
  3525. pixels[i] = data[offset++];
  3526. }
  3527. // Copy pixel array
  3528. for (i = 0; i < count; ++i) {
  3529. pixel_data.set(pixels, localOffset + i * pixel_size);
  3530. }
  3531. localOffset += pixel_size * count;
  3532. }
  3533. else {
  3534. count *= pixel_size;
  3535. for (i = 0; i < count; ++i) {
  3536. pixel_data[localOffset + i] = data[offset++];
  3537. }
  3538. localOffset += count;
  3539. }
  3540. }
  3541. }
  3542. else {
  3543. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3544. }
  3545. // Load to texture
  3546. var x_start, y_start, x_step, y_step, y_end, x_end;
  3547. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3548. default:
  3549. case TGATools._ORIGIN_UL:
  3550. x_start = 0;
  3551. x_step = 1;
  3552. x_end = header.width;
  3553. y_start = 0;
  3554. y_step = 1;
  3555. y_end = header.height;
  3556. break;
  3557. case TGATools._ORIGIN_BL:
  3558. x_start = 0;
  3559. x_step = 1;
  3560. x_end = header.width;
  3561. y_start = header.height - 1;
  3562. y_step = -1;
  3563. y_end = -1;
  3564. break;
  3565. case TGATools._ORIGIN_UR:
  3566. x_start = header.width - 1;
  3567. x_step = -1;
  3568. x_end = -1;
  3569. y_start = 0;
  3570. y_step = 1;
  3571. y_end = header.height;
  3572. break;
  3573. case TGATools._ORIGIN_BR:
  3574. x_start = header.width - 1;
  3575. x_step = -1;
  3576. x_end = -1;
  3577. y_start = header.height - 1;
  3578. y_step = -1;
  3579. y_end = -1;
  3580. break;
  3581. }
  3582. // Load the specify method
  3583. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3584. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3585. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3586. };
  3587. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3588. var image = pixel_data, colormap = palettes;
  3589. var width = header.width, height = header.height;
  3590. var color, i = 0, x, y;
  3591. var imageData = new Uint8Array(width * height * 4);
  3592. for (y = y_start; y !== y_end; y += y_step) {
  3593. for (x = x_start; x !== x_end; x += x_step, i++) {
  3594. color = image[i];
  3595. imageData[(x + width * y) * 4 + 3] = 255;
  3596. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3597. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3598. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3599. }
  3600. }
  3601. return imageData;
  3602. };
  3603. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3604. var image = pixel_data;
  3605. var width = header.width, height = header.height;
  3606. var color, i = 0, x, y;
  3607. var imageData = new Uint8Array(width * height * 4);
  3608. for (y = y_start; y !== y_end; y += y_step) {
  3609. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3610. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3611. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3612. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3613. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3614. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3615. }
  3616. }
  3617. return imageData;
  3618. };
  3619. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3620. var image = pixel_data;
  3621. var width = header.width, height = header.height;
  3622. var i = 0, x, y;
  3623. var imageData = new Uint8Array(width * height * 4);
  3624. for (y = y_start; y !== y_end; y += y_step) {
  3625. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3626. imageData[(x + width * y) * 4 + 3] = 255;
  3627. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3628. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3629. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3630. }
  3631. }
  3632. return imageData;
  3633. };
  3634. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3635. var image = pixel_data;
  3636. var width = header.width, height = header.height;
  3637. var i = 0, x, y;
  3638. var imageData = new Uint8Array(width * height * 4);
  3639. for (y = y_start; y !== y_end; y += y_step) {
  3640. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3641. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3642. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3643. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3644. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3645. }
  3646. }
  3647. return imageData;
  3648. };
  3649. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3650. var image = pixel_data;
  3651. var width = header.width, height = header.height;
  3652. var color, i = 0, x, y;
  3653. var imageData = new Uint8Array(width * height * 4);
  3654. for (y = y_start; y !== y_end; y += y_step) {
  3655. for (x = x_start; x !== x_end; x += x_step, i++) {
  3656. color = image[i];
  3657. imageData[(x + width * y) * 4 + 0] = color;
  3658. imageData[(x + width * y) * 4 + 1] = color;
  3659. imageData[(x + width * y) * 4 + 2] = color;
  3660. imageData[(x + width * y) * 4 + 3] = 255;
  3661. }
  3662. }
  3663. return imageData;
  3664. };
  3665. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3666. var image = pixel_data;
  3667. var width = header.width, height = header.height;
  3668. var i = 0, x, y;
  3669. var imageData = new Uint8Array(width * height * 4);
  3670. for (y = y_start; y !== y_end; y += y_step) {
  3671. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3672. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3673. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3674. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3675. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3676. }
  3677. }
  3678. return imageData;
  3679. };
  3680. TGATools._TYPE_NO_DATA = 0;
  3681. TGATools._TYPE_INDEXED = 1;
  3682. TGATools._TYPE_RGB = 2;
  3683. TGATools._TYPE_GREY = 3;
  3684. TGATools._TYPE_RLE_INDEXED = 9;
  3685. TGATools._TYPE_RLE_RGB = 10;
  3686. TGATools._TYPE_RLE_GREY = 11;
  3687. TGATools._ORIGIN_MASK = 0x30;
  3688. TGATools._ORIGIN_SHIFT = 0x04;
  3689. TGATools._ORIGIN_BL = 0x00;
  3690. TGATools._ORIGIN_BR = 0x01;
  3691. TGATools._ORIGIN_UL = 0x02;
  3692. TGATools._ORIGIN_UR = 0x03;
  3693. return TGATools;
  3694. })();
  3695. Internals.TGATools = TGATools;
  3696. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3697. })(BABYLON || (BABYLON = {}));
  3698. var BABYLON;
  3699. (function (BABYLON) {
  3700. var SmartArray = (function () {
  3701. function SmartArray(capacity) {
  3702. this.length = 0;
  3703. this._duplicateId = 0;
  3704. this.data = new Array(capacity);
  3705. this._id = SmartArray._GlobalId++;
  3706. }
  3707. SmartArray.prototype.push = function (value) {
  3708. this.data[this.length++] = value;
  3709. if (this.length > this.data.length) {
  3710. this.data.length *= 2;
  3711. }
  3712. if (!value.__smartArrayFlags) {
  3713. value.__smartArrayFlags = {};
  3714. }
  3715. value.__smartArrayFlags[this._id] = this._duplicateId;
  3716. };
  3717. SmartArray.prototype.pushNoDuplicate = function (value) {
  3718. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3719. return;
  3720. }
  3721. this.push(value);
  3722. };
  3723. SmartArray.prototype.sort = function (compareFn) {
  3724. this.data.sort(compareFn);
  3725. };
  3726. SmartArray.prototype.reset = function () {
  3727. this.length = 0;
  3728. this._duplicateId++;
  3729. };
  3730. SmartArray.prototype.concat = function (array) {
  3731. if (array.length === 0) {
  3732. return;
  3733. }
  3734. if (this.length + array.length > this.data.length) {
  3735. this.data.length = (this.length + array.length) * 2;
  3736. }
  3737. for (var index = 0; index < array.length; index++) {
  3738. this.data[this.length++] = (array.data || array)[index];
  3739. }
  3740. };
  3741. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3742. if (array.length === 0) {
  3743. return;
  3744. }
  3745. if (this.length + array.length > this.data.length) {
  3746. this.data.length = (this.length + array.length) * 2;
  3747. }
  3748. for (var index = 0; index < array.length; index++) {
  3749. var item = (array.data || array)[index];
  3750. this.pushNoDuplicate(item);
  3751. }
  3752. };
  3753. SmartArray.prototype.indexOf = function (value) {
  3754. var position = this.data.indexOf(value);
  3755. if (position >= this.length) {
  3756. return -1;
  3757. }
  3758. return position;
  3759. };
  3760. // Statics
  3761. SmartArray._GlobalId = 0;
  3762. return SmartArray;
  3763. })();
  3764. BABYLON.SmartArray = SmartArray;
  3765. })(BABYLON || (BABYLON = {}));
  3766. var BABYLON;
  3767. (function (BABYLON) {
  3768. var SmartCollection = (function () {
  3769. function SmartCollection(capacity) {
  3770. if (capacity === void 0) { capacity = 10; }
  3771. this.count = 0;
  3772. this._initialCapacity = capacity;
  3773. this.items = {};
  3774. this._keys = new Array(this._initialCapacity);
  3775. }
  3776. SmartCollection.prototype.add = function (key, item) {
  3777. if (this.items[key] != undefined) {
  3778. return -1;
  3779. }
  3780. this.items[key] = item;
  3781. //literal keys are always strings, but we keep source type of key in _keys array
  3782. this._keys[this.count++] = key;
  3783. if (this.count > this._keys.length) {
  3784. this._keys.length *= 2;
  3785. }
  3786. return this.count;
  3787. };
  3788. SmartCollection.prototype.remove = function (key) {
  3789. if (this.items[key] == undefined) {
  3790. return -1;
  3791. }
  3792. return this.removeItemOfIndex(this.indexOf(key));
  3793. };
  3794. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3795. if (index < this.count && index > -1) {
  3796. delete this.items[this._keys[index]];
  3797. //here, shifting by hand is better optimised than .splice
  3798. while (index < this.count) {
  3799. this._keys[index] = this._keys[index + 1];
  3800. index++;
  3801. }
  3802. }
  3803. else {
  3804. return -1;
  3805. }
  3806. return --this.count;
  3807. };
  3808. SmartCollection.prototype.indexOf = function (key) {
  3809. for (var i = 0; i !== this.count; i++) {
  3810. if (this._keys[i] === key) {
  3811. return i;
  3812. }
  3813. }
  3814. return -1;
  3815. };
  3816. SmartCollection.prototype.item = function (key) {
  3817. return this.items[key];
  3818. };
  3819. SmartCollection.prototype.getAllKeys = function () {
  3820. if (this.count > 0) {
  3821. var keys = new Array(this.count);
  3822. for (var i = 0; i < this.count; i++) {
  3823. keys[i] = this._keys[i];
  3824. }
  3825. return keys;
  3826. }
  3827. else {
  3828. return undefined;
  3829. }
  3830. };
  3831. SmartCollection.prototype.getKeyByIndex = function (index) {
  3832. if (index < this.count && index > -1) {
  3833. return this._keys[index];
  3834. }
  3835. else {
  3836. return undefined;
  3837. }
  3838. };
  3839. SmartCollection.prototype.getItemByIndex = function (index) {
  3840. if (index < this.count && index > -1) {
  3841. return this.items[this._keys[index]];
  3842. }
  3843. else {
  3844. return undefined;
  3845. }
  3846. };
  3847. SmartCollection.prototype.empty = function () {
  3848. if (this.count > 0) {
  3849. this.count = 0;
  3850. this.items = {};
  3851. this._keys = new Array(this._initialCapacity);
  3852. }
  3853. };
  3854. SmartCollection.prototype.forEach = function (block) {
  3855. var key;
  3856. for (key in this.items) {
  3857. if (this.items.hasOwnProperty(key)) {
  3858. block(this.items[key]);
  3859. }
  3860. }
  3861. };
  3862. return SmartCollection;
  3863. })();
  3864. BABYLON.SmartCollection = SmartCollection;
  3865. })(BABYLON || (BABYLON = {}));
  3866. var BABYLON;
  3867. (function (BABYLON) {
  3868. // Screenshots
  3869. var screenshotCanvas;
  3870. var cloneValue = function (source, destinationObject) {
  3871. if (!source)
  3872. return null;
  3873. if (source instanceof BABYLON.Mesh) {
  3874. return null;
  3875. }
  3876. if (source instanceof BABYLON.SubMesh) {
  3877. return source.clone(destinationObject);
  3878. }
  3879. else if (source.clone) {
  3880. return source.clone();
  3881. }
  3882. return null;
  3883. };
  3884. var Tools = (function () {
  3885. function Tools() {
  3886. }
  3887. Tools.ToHex = function (i) {
  3888. var str = i.toString(16);
  3889. if (i <= 15) {
  3890. return ("0" + str).toUpperCase();
  3891. }
  3892. return str.toUpperCase();
  3893. };
  3894. Tools.SetImmediate = function (action) {
  3895. if (window.setImmediate) {
  3896. window.setImmediate(action);
  3897. }
  3898. else {
  3899. setTimeout(action, 1);
  3900. }
  3901. };
  3902. Tools.IsExponentOfTwo = function (value) {
  3903. var count = 1;
  3904. do {
  3905. count *= 2;
  3906. } while (count < value);
  3907. return count === value;
  3908. };
  3909. Tools.GetExponentOfTwo = function (value, max) {
  3910. var count = 1;
  3911. do {
  3912. count *= 2;
  3913. } while (count < value);
  3914. if (count > max)
  3915. count = max;
  3916. return count;
  3917. };
  3918. Tools.GetFilename = function (path) {
  3919. var index = path.lastIndexOf("/");
  3920. if (index < 0)
  3921. return path;
  3922. return path.substring(index + 1);
  3923. };
  3924. Tools.GetDOMTextContent = function (element) {
  3925. var result = "";
  3926. var child = element.firstChild;
  3927. while (child) {
  3928. if (child.nodeType === 3) {
  3929. result += child.textContent;
  3930. }
  3931. child = child.nextSibling;
  3932. }
  3933. return result;
  3934. };
  3935. Tools.ToDegrees = function (angle) {
  3936. return angle * 180 / Math.PI;
  3937. };
  3938. Tools.ToRadians = function (angle) {
  3939. return angle * Math.PI / 180;
  3940. };
  3941. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3942. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3943. var output = "";
  3944. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3945. var i = 0;
  3946. var bytes = new Uint8Array(buffer);
  3947. while (i < bytes.length) {
  3948. chr1 = bytes[i++];
  3949. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3950. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3951. enc1 = chr1 >> 2;
  3952. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3953. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3954. enc4 = chr3 & 63;
  3955. if (isNaN(chr2)) {
  3956. enc3 = enc4 = 64;
  3957. }
  3958. else if (isNaN(chr3)) {
  3959. enc4 = 64;
  3960. }
  3961. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3962. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3963. }
  3964. return "data:image/png;base64," + output;
  3965. };
  3966. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3967. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3968. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3969. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3970. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3971. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3972. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3973. }
  3974. return {
  3975. minimum: minimum,
  3976. maximum: maximum
  3977. };
  3978. };
  3979. Tools.ExtractMinAndMax = function (positions, start, count) {
  3980. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3981. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3982. for (var index = start; index < start + count; index++) {
  3983. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3986. }
  3987. return {
  3988. minimum: minimum,
  3989. maximum: maximum
  3990. };
  3991. };
  3992. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3993. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3994. return undefined;
  3995. return Array.isArray(obj) ? obj : [obj];
  3996. };
  3997. // Misc.
  3998. Tools.GetPointerPrefix = function () {
  3999. var eventPrefix = "pointer";
  4000. // Check if hand.js is referenced or if the browser natively supports pointer events
  4001. if (!navigator.pointerEnabled) {
  4002. eventPrefix = "mouse";
  4003. }
  4004. return eventPrefix;
  4005. };
  4006. Tools.QueueNewFrame = function (func) {
  4007. if (window.requestAnimationFrame)
  4008. window.requestAnimationFrame(func);
  4009. else if (window.msRequestAnimationFrame)
  4010. window.msRequestAnimationFrame(func);
  4011. else if (window.webkitRequestAnimationFrame)
  4012. window.webkitRequestAnimationFrame(func);
  4013. else if (window.mozRequestAnimationFrame)
  4014. window.mozRequestAnimationFrame(func);
  4015. else if (window.oRequestAnimationFrame)
  4016. window.oRequestAnimationFrame(func);
  4017. else {
  4018. window.setTimeout(func, 16);
  4019. }
  4020. };
  4021. Tools.RequestFullscreen = function (element) {
  4022. if (element.requestFullscreen)
  4023. element.requestFullscreen();
  4024. else if (element.msRequestFullscreen)
  4025. element.msRequestFullscreen();
  4026. else if (element.webkitRequestFullscreen)
  4027. element.webkitRequestFullscreen();
  4028. else if (element.mozRequestFullScreen)
  4029. element.mozRequestFullScreen();
  4030. };
  4031. Tools.ExitFullscreen = function () {
  4032. if (document.exitFullscreen) {
  4033. document.exitFullscreen();
  4034. }
  4035. else if (document.mozCancelFullScreen) {
  4036. document.mozCancelFullScreen();
  4037. }
  4038. else if (document.webkitCancelFullScreen) {
  4039. document.webkitCancelFullScreen();
  4040. }
  4041. else if (document.msCancelFullScreen) {
  4042. document.msCancelFullScreen();
  4043. }
  4044. };
  4045. // External files
  4046. Tools.CleanUrl = function (url) {
  4047. url = url.replace(/#/mg, "%23");
  4048. return url;
  4049. };
  4050. Tools.LoadImage = function (url, onload, onerror, database) {
  4051. if (url instanceof ArrayBuffer) {
  4052. url = Tools.EncodeArrayBufferTobase64(url);
  4053. }
  4054. url = Tools.CleanUrl(url);
  4055. var img = new Image();
  4056. if (url.substr(0, 5) !== "data:") {
  4057. if (Tools.CorsBehavior) {
  4058. switch (typeof (Tools.CorsBehavior)) {
  4059. case "function":
  4060. var result = Tools.CorsBehavior(url);
  4061. if (result) {
  4062. img.crossOrigin = result;
  4063. }
  4064. break;
  4065. case "string":
  4066. default:
  4067. img.crossOrigin = Tools.CorsBehavior;
  4068. break;
  4069. }
  4070. }
  4071. }
  4072. img.onload = function () {
  4073. onload(img);
  4074. };
  4075. img.onerror = function (err) {
  4076. Tools.Error("Error while trying to load texture: " + url);
  4077. 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";
  4078. onload(img);
  4079. };
  4080. var noIndexedDB = function () {
  4081. img.src = url;
  4082. };
  4083. var loadFromIndexedDB = function () {
  4084. database.loadImageFromDB(url, img);
  4085. };
  4086. //ANY database to do!
  4087. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4088. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4089. }
  4090. else {
  4091. if (url.indexOf("file:") === -1) {
  4092. noIndexedDB();
  4093. }
  4094. else {
  4095. try {
  4096. var textureName = url.substring(5);
  4097. var blobURL;
  4098. try {
  4099. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4100. }
  4101. catch (ex) {
  4102. // Chrome doesn't support oneTimeOnly parameter
  4103. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4104. }
  4105. img.src = blobURL;
  4106. }
  4107. catch (e) {
  4108. img.src = null;
  4109. }
  4110. }
  4111. }
  4112. return img;
  4113. };
  4114. //ANY
  4115. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4116. url = Tools.CleanUrl(url);
  4117. var noIndexedDB = function () {
  4118. var request = new XMLHttpRequest();
  4119. var loadUrl = Tools.BaseUrl + url;
  4120. request.open('GET', loadUrl, true);
  4121. if (useArrayBuffer) {
  4122. request.responseType = "arraybuffer";
  4123. }
  4124. request.onprogress = progressCallBack;
  4125. request.onreadystatechange = function () {
  4126. if (request.readyState === 4) {
  4127. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4128. callback(!useArrayBuffer ? request.responseText : request.response);
  4129. }
  4130. else {
  4131. if (onError) {
  4132. onError();
  4133. }
  4134. else {
  4135. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4136. }
  4137. }
  4138. }
  4139. };
  4140. request.send(null);
  4141. };
  4142. var loadFromIndexedDB = function () {
  4143. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4144. };
  4145. if (url.indexOf("file:") !== -1) {
  4146. var fileName = url.substring(5);
  4147. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4148. }
  4149. else {
  4150. // Caching all files
  4151. if (database && database.enableSceneOffline) {
  4152. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4153. }
  4154. else {
  4155. noIndexedDB();
  4156. }
  4157. }
  4158. };
  4159. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4160. var reader = new FileReader();
  4161. reader.onload = function (e) {
  4162. //target doesn't have result from ts 1.3
  4163. callback(e.target['result']);
  4164. };
  4165. reader.onprogress = progressCallback;
  4166. reader.readAsDataURL(fileToLoad);
  4167. };
  4168. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4169. var reader = new FileReader();
  4170. reader.onerror = function (e) {
  4171. Tools.Log("Error while reading file: " + fileToLoad.name);
  4172. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4173. };
  4174. reader.onload = function (e) {
  4175. //target doesn't have result from ts 1.3
  4176. callback(e.target['result']);
  4177. };
  4178. reader.onprogress = progressCallBack;
  4179. if (!useArrayBuffer) {
  4180. // Asynchronous read
  4181. reader.readAsText(fileToLoad);
  4182. }
  4183. else {
  4184. reader.readAsArrayBuffer(fileToLoad);
  4185. }
  4186. };
  4187. //returns a downloadable url to a file content.
  4188. Tools.FileAsURL = function (content) {
  4189. var fileBlob = new Blob([content]);
  4190. var url = window.URL || window.webkitURL;
  4191. var link = url.createObjectURL(fileBlob);
  4192. return link;
  4193. };
  4194. // Misc.
  4195. Tools.Clamp = function (value, min, max) {
  4196. if (min === void 0) { min = 0; }
  4197. if (max === void 0) { max = 1; }
  4198. return Math.min(max, Math.max(min, value));
  4199. };
  4200. // Returns -1 when value is a negative number and
  4201. // +1 when value is a positive number.
  4202. Tools.Sign = function (value) {
  4203. value = +value; // convert to a number
  4204. if (value === 0 || isNaN(value))
  4205. return value;
  4206. return value > 0 ? 1 : -1;
  4207. };
  4208. Tools.Format = function (value, decimals) {
  4209. if (decimals === void 0) { decimals = 2; }
  4210. return value.toFixed(decimals);
  4211. };
  4212. Tools.CheckExtends = function (v, min, max) {
  4213. if (v.x < min.x)
  4214. min.x = v.x;
  4215. if (v.y < min.y)
  4216. min.y = v.y;
  4217. if (v.z < min.z)
  4218. min.z = v.z;
  4219. if (v.x > max.x)
  4220. max.x = v.x;
  4221. if (v.y > max.y)
  4222. max.y = v.y;
  4223. if (v.z > max.z)
  4224. max.z = v.z;
  4225. };
  4226. Tools.WithinEpsilon = function (a, b, epsilon) {
  4227. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4228. var num = a - b;
  4229. return -epsilon <= num && num <= epsilon;
  4230. };
  4231. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4232. for (var prop in source) {
  4233. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4234. continue;
  4235. }
  4236. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4237. continue;
  4238. }
  4239. var sourceValue = source[prop];
  4240. var typeOfSourceValue = typeof sourceValue;
  4241. if (typeOfSourceValue === "function") {
  4242. continue;
  4243. }
  4244. if (typeOfSourceValue === "object") {
  4245. if (sourceValue instanceof Array) {
  4246. destination[prop] = [];
  4247. if (sourceValue.length > 0) {
  4248. if (typeof sourceValue[0] == "object") {
  4249. for (var index = 0; index < sourceValue.length; index++) {
  4250. var clonedValue = cloneValue(sourceValue[index], destination);
  4251. if (destination[prop].indexOf(clonedValue) === -1) {
  4252. destination[prop].push(clonedValue);
  4253. }
  4254. }
  4255. }
  4256. else {
  4257. destination[prop] = sourceValue.slice(0);
  4258. }
  4259. }
  4260. }
  4261. else {
  4262. destination[prop] = cloneValue(sourceValue, destination);
  4263. }
  4264. }
  4265. else {
  4266. destination[prop] = sourceValue;
  4267. }
  4268. }
  4269. };
  4270. Tools.IsEmpty = function (obj) {
  4271. for (var i in obj) {
  4272. return false;
  4273. }
  4274. return true;
  4275. };
  4276. Tools.RegisterTopRootEvents = function (events) {
  4277. for (var index = 0; index < events.length; index++) {
  4278. var event = events[index];
  4279. window.addEventListener(event.name, event.handler, false);
  4280. try {
  4281. if (window.parent) {
  4282. window.parent.addEventListener(event.name, event.handler, false);
  4283. }
  4284. }
  4285. catch (e) {
  4286. }
  4287. }
  4288. };
  4289. Tools.UnregisterTopRootEvents = function (events) {
  4290. for (var index = 0; index < events.length; index++) {
  4291. var event = events[index];
  4292. window.removeEventListener(event.name, event.handler);
  4293. try {
  4294. if (window.parent) {
  4295. window.parent.removeEventListener(event.name, event.handler);
  4296. }
  4297. }
  4298. catch (e) {
  4299. }
  4300. }
  4301. };
  4302. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4303. // Read the contents of the framebuffer
  4304. var numberOfChannelsByLine = width * 4;
  4305. var halfHeight = height / 2;
  4306. //Reading datas from WebGL
  4307. var data = engine.readPixels(0, 0, width, height);
  4308. //To flip image on Y axis.
  4309. for (var i = 0; i < halfHeight; i++) {
  4310. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4311. var currentCell = j + i * numberOfChannelsByLine;
  4312. var targetLine = height - i - 1;
  4313. var targetCell = j + targetLine * numberOfChannelsByLine;
  4314. var temp = data[currentCell];
  4315. data[currentCell] = data[targetCell];
  4316. data[targetCell] = temp;
  4317. }
  4318. }
  4319. // Create a 2D canvas to store the result
  4320. if (!screenshotCanvas) {
  4321. screenshotCanvas = document.createElement('canvas');
  4322. }
  4323. screenshotCanvas.width = width;
  4324. screenshotCanvas.height = height;
  4325. var context = screenshotCanvas.getContext('2d');
  4326. // Copy the pixels to a 2D canvas
  4327. var imageData = context.createImageData(width, height);
  4328. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4329. var castData = imageData.data;
  4330. castData.set(data);
  4331. context.putImageData(imageData, 0, 0);
  4332. var base64Image = screenshotCanvas.toDataURL();
  4333. if (successCallback) {
  4334. successCallback(base64Image);
  4335. }
  4336. else {
  4337. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4338. if (("download" in document.createElement("a"))) {
  4339. var a = window.document.createElement("a");
  4340. a.href = base64Image;
  4341. var date = new Date();
  4342. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4343. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4344. window.document.body.appendChild(a);
  4345. a.addEventListener("click", function () {
  4346. a.parentElement.removeChild(a);
  4347. });
  4348. a.click();
  4349. }
  4350. else {
  4351. var newWindow = window.open("");
  4352. var img = newWindow.document.createElement("img");
  4353. img.src = base64Image;
  4354. newWindow.document.body.appendChild(img);
  4355. }
  4356. }
  4357. };
  4358. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4359. var width;
  4360. var height;
  4361. //If a precision value is specified
  4362. if (size.precision) {
  4363. width = Math.round(engine.getRenderWidth() * size.precision);
  4364. height = Math.round(width / engine.getAspectRatio(camera));
  4365. size = { width: width, height: height };
  4366. }
  4367. else if (size.width && size.height) {
  4368. width = size.width;
  4369. height = size.height;
  4370. }
  4371. else if (size.width && !size.height) {
  4372. width = size.width;
  4373. height = Math.round(width / engine.getAspectRatio(camera));
  4374. size = { width: width, height: height };
  4375. }
  4376. else if (size.height && !size.width) {
  4377. height = size.height;
  4378. width = Math.round(height * engine.getAspectRatio(camera));
  4379. size = { width: width, height: height };
  4380. }
  4381. else if (!isNaN(size)) {
  4382. height = size;
  4383. width = size;
  4384. }
  4385. else {
  4386. Tools.Error("Invalid 'size' parameter !");
  4387. return;
  4388. }
  4389. var scene = camera.getScene();
  4390. var previousCamera = null;
  4391. if (scene.activeCamera !== camera) {
  4392. previousCamera = scene.activeCamera;
  4393. scene.activeCamera = camera;
  4394. }
  4395. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4396. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4397. texture.renderList = scene.meshes;
  4398. texture.onAfterRender = function () {
  4399. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4400. };
  4401. scene.incrementRenderId();
  4402. texture.render(true);
  4403. texture.dispose();
  4404. if (previousCamera) {
  4405. scene.activeCamera = previousCamera;
  4406. }
  4407. };
  4408. // XHR response validator for local file scenario
  4409. Tools.ValidateXHRData = function (xhr, dataType) {
  4410. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4411. if (dataType === void 0) { dataType = 7; }
  4412. try {
  4413. if (dataType & 1) {
  4414. if (xhr.responseText && xhr.responseText.length > 0) {
  4415. return true;
  4416. }
  4417. else if (dataType === 1) {
  4418. return false;
  4419. }
  4420. }
  4421. if (dataType & 2) {
  4422. // Check header width and height since there is no "TGA" magic number
  4423. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4424. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4425. return true;
  4426. }
  4427. else if (dataType === 2) {
  4428. return false;
  4429. }
  4430. }
  4431. if (dataType & 4) {
  4432. // Check for the "DDS" magic number
  4433. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4434. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4435. return true;
  4436. }
  4437. else {
  4438. return false;
  4439. }
  4440. }
  4441. }
  4442. catch (e) {
  4443. }
  4444. return false;
  4445. };
  4446. Object.defineProperty(Tools, "NoneLogLevel", {
  4447. get: function () {
  4448. return Tools._NoneLogLevel;
  4449. },
  4450. enumerable: true,
  4451. configurable: true
  4452. });
  4453. Object.defineProperty(Tools, "MessageLogLevel", {
  4454. get: function () {
  4455. return Tools._MessageLogLevel;
  4456. },
  4457. enumerable: true,
  4458. configurable: true
  4459. });
  4460. Object.defineProperty(Tools, "WarningLogLevel", {
  4461. get: function () {
  4462. return Tools._WarningLogLevel;
  4463. },
  4464. enumerable: true,
  4465. configurable: true
  4466. });
  4467. Object.defineProperty(Tools, "ErrorLogLevel", {
  4468. get: function () {
  4469. return Tools._ErrorLogLevel;
  4470. },
  4471. enumerable: true,
  4472. configurable: true
  4473. });
  4474. Object.defineProperty(Tools, "AllLogLevel", {
  4475. get: function () {
  4476. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4477. },
  4478. enumerable: true,
  4479. configurable: true
  4480. });
  4481. Tools._AddLogEntry = function (entry) {
  4482. Tools._LogCache = entry + Tools._LogCache;
  4483. if (Tools.OnNewCacheEntry) {
  4484. Tools.OnNewCacheEntry(entry);
  4485. }
  4486. };
  4487. Tools._FormatMessage = function (message) {
  4488. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4489. var date = new Date();
  4490. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4491. };
  4492. Tools._LogDisabled = function (message) {
  4493. // nothing to do
  4494. };
  4495. Tools._LogEnabled = function (message) {
  4496. var formattedMessage = Tools._FormatMessage(message);
  4497. console.log("BJS - " + formattedMessage);
  4498. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4499. Tools._AddLogEntry(entry);
  4500. };
  4501. Tools._WarnDisabled = function (message) {
  4502. // nothing to do
  4503. };
  4504. Tools._WarnEnabled = function (message) {
  4505. var formattedMessage = Tools._FormatMessage(message);
  4506. console.warn("BJS - " + formattedMessage);
  4507. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4508. Tools._AddLogEntry(entry);
  4509. };
  4510. Tools._ErrorDisabled = function (message) {
  4511. // nothing to do
  4512. };
  4513. Tools._ErrorEnabled = function (message) {
  4514. Tools.errorsCount++;
  4515. var formattedMessage = Tools._FormatMessage(message);
  4516. console.error("BJS - " + formattedMessage);
  4517. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4518. Tools._AddLogEntry(entry);
  4519. };
  4520. Object.defineProperty(Tools, "LogCache", {
  4521. get: function () {
  4522. return Tools._LogCache;
  4523. },
  4524. enumerable: true,
  4525. configurable: true
  4526. });
  4527. Tools.ClearLogCache = function () {
  4528. Tools._LogCache = "";
  4529. Tools.errorsCount = 0;
  4530. };
  4531. Object.defineProperty(Tools, "LogLevels", {
  4532. set: function (level) {
  4533. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4534. Tools.Log = Tools._LogEnabled;
  4535. }
  4536. else {
  4537. Tools.Log = Tools._LogDisabled;
  4538. }
  4539. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4540. Tools.Warn = Tools._WarnEnabled;
  4541. }
  4542. else {
  4543. Tools.Warn = Tools._WarnDisabled;
  4544. }
  4545. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4546. Tools.Error = Tools._ErrorEnabled;
  4547. }
  4548. else {
  4549. Tools.Error = Tools._ErrorDisabled;
  4550. }
  4551. },
  4552. enumerable: true,
  4553. configurable: true
  4554. });
  4555. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4556. get: function () {
  4557. return Tools._PerformanceNoneLogLevel;
  4558. },
  4559. enumerable: true,
  4560. configurable: true
  4561. });
  4562. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4563. get: function () {
  4564. return Tools._PerformanceUserMarkLogLevel;
  4565. },
  4566. enumerable: true,
  4567. configurable: true
  4568. });
  4569. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4570. get: function () {
  4571. return Tools._PerformanceConsoleLogLevel;
  4572. },
  4573. enumerable: true,
  4574. configurable: true
  4575. });
  4576. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4577. set: function (level) {
  4578. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4579. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4580. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4581. return;
  4582. }
  4583. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4584. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4585. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4586. return;
  4587. }
  4588. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4589. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4595. };
  4596. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4597. };
  4598. Tools._StartUserMark = function (counterName, condition) {
  4599. if (condition === void 0) { condition = true; }
  4600. if (!condition || !Tools._performance.mark) {
  4601. return;
  4602. }
  4603. Tools._performance.mark(counterName + "-Begin");
  4604. };
  4605. Tools._EndUserMark = function (counterName, condition) {
  4606. if (condition === void 0) { condition = true; }
  4607. if (!condition || !Tools._performance.mark) {
  4608. return;
  4609. }
  4610. Tools._performance.mark(counterName + "-End");
  4611. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4612. };
  4613. Tools._StartPerformanceConsole = function (counterName, condition) {
  4614. if (condition === void 0) { condition = true; }
  4615. if (!condition) {
  4616. return;
  4617. }
  4618. Tools._StartUserMark(counterName, condition);
  4619. if (console.time) {
  4620. console.time(counterName);
  4621. }
  4622. };
  4623. Tools._EndPerformanceConsole = function (counterName, condition) {
  4624. if (condition === void 0) { condition = true; }
  4625. if (!condition) {
  4626. return;
  4627. }
  4628. Tools._EndUserMark(counterName, condition);
  4629. if (console.time) {
  4630. console.timeEnd(counterName);
  4631. }
  4632. };
  4633. Object.defineProperty(Tools, "Now", {
  4634. get: function () {
  4635. if (window.performance && window.performance.now) {
  4636. return window.performance.now();
  4637. }
  4638. return new Date().getTime();
  4639. },
  4640. enumerable: true,
  4641. configurable: true
  4642. });
  4643. Tools.BaseUrl = "";
  4644. Tools.CorsBehavior = "anonymous";
  4645. // Logs
  4646. Tools._NoneLogLevel = 0;
  4647. Tools._MessageLogLevel = 1;
  4648. Tools._WarningLogLevel = 2;
  4649. Tools._ErrorLogLevel = 4;
  4650. Tools._LogCache = "";
  4651. Tools.errorsCount = 0;
  4652. Tools.Log = Tools._LogEnabled;
  4653. Tools.Warn = Tools._WarnEnabled;
  4654. Tools.Error = Tools._ErrorEnabled;
  4655. // Performances
  4656. Tools._PerformanceNoneLogLevel = 0;
  4657. Tools._PerformanceUserMarkLogLevel = 1;
  4658. Tools._PerformanceConsoleLogLevel = 2;
  4659. Tools._performance = window.performance;
  4660. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4661. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4662. return Tools;
  4663. })();
  4664. BABYLON.Tools = Tools;
  4665. /**
  4666. * An implementation of a loop for asynchronous functions.
  4667. */
  4668. var AsyncLoop = (function () {
  4669. /**
  4670. * Constroctor.
  4671. * @param iterations the number of iterations.
  4672. * @param _fn the function to run each iteration
  4673. * @param _successCallback the callback that will be called upon succesful execution
  4674. * @param offset starting offset.
  4675. */
  4676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4677. if (offset === void 0) { offset = 0; }
  4678. this.iterations = iterations;
  4679. this._fn = _fn;
  4680. this._successCallback = _successCallback;
  4681. this.index = offset - 1;
  4682. this._done = false;
  4683. }
  4684. /**
  4685. * Execute the next iteration. Must be called after the last iteration was finished.
  4686. */
  4687. AsyncLoop.prototype.executeNext = function () {
  4688. if (!this._done) {
  4689. if (this.index + 1 < this.iterations) {
  4690. ++this.index;
  4691. this._fn(this);
  4692. }
  4693. else {
  4694. this.breakLoop();
  4695. }
  4696. }
  4697. };
  4698. /**
  4699. * Break the loop and run the success callback.
  4700. */
  4701. AsyncLoop.prototype.breakLoop = function () {
  4702. this._done = true;
  4703. this._successCallback();
  4704. };
  4705. /**
  4706. * Helper function
  4707. */
  4708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4709. if (offset === void 0) { offset = 0; }
  4710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4711. loop.executeNext();
  4712. return loop;
  4713. };
  4714. /**
  4715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4716. * @param iterations total number of iterations
  4717. * @param syncedIterations number of synchronous iterations in each async iteration.
  4718. * @param fn the function to call each iteration.
  4719. * @param callback a success call back that will be called when iterating stops.
  4720. * @param breakFunction a break condition (optional)
  4721. * @param timeout timeout settings for the setTimeout function. default - 0.
  4722. * @constructor
  4723. */
  4724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4725. if (timeout === void 0) { timeout = 0; }
  4726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4727. if (breakFunction && breakFunction())
  4728. loop.breakLoop();
  4729. else {
  4730. setTimeout(function () {
  4731. for (var i = 0; i < syncedIterations; ++i) {
  4732. var iteration = (loop.index * syncedIterations) + i;
  4733. if (iteration >= iterations)
  4734. break;
  4735. fn(iteration);
  4736. if (breakFunction && breakFunction()) {
  4737. loop.breakLoop();
  4738. break;
  4739. }
  4740. }
  4741. loop.executeNext();
  4742. }, timeout);
  4743. }
  4744. }, callback);
  4745. };
  4746. return AsyncLoop;
  4747. })();
  4748. BABYLON.AsyncLoop = AsyncLoop;
  4749. })(BABYLON || (BABYLON = {}));
  4750. var BABYLON;
  4751. (function (BABYLON) {
  4752. var _DepthCullingState = (function () {
  4753. function _DepthCullingState() {
  4754. this._isDepthTestDirty = false;
  4755. this._isDepthMaskDirty = false;
  4756. this._isDepthFuncDirty = false;
  4757. this._isCullFaceDirty = false;
  4758. this._isCullDirty = false;
  4759. this._isZOffsetDirty = false;
  4760. }
  4761. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4762. get: function () {
  4763. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4764. },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4769. get: function () {
  4770. return this._zOffset;
  4771. },
  4772. set: function (value) {
  4773. if (this._zOffset === value) {
  4774. return;
  4775. }
  4776. this._zOffset = value;
  4777. this._isZOffsetDirty = true;
  4778. },
  4779. enumerable: true,
  4780. configurable: true
  4781. });
  4782. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4783. get: function () {
  4784. return this._cullFace;
  4785. },
  4786. set: function (value) {
  4787. if (this._cullFace === value) {
  4788. return;
  4789. }
  4790. this._cullFace = value;
  4791. this._isCullFaceDirty = true;
  4792. },
  4793. enumerable: true,
  4794. configurable: true
  4795. });
  4796. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4797. get: function () {
  4798. return this._cull;
  4799. },
  4800. set: function (value) {
  4801. if (this._cull === value) {
  4802. return;
  4803. }
  4804. this._cull = value;
  4805. this._isCullDirty = true;
  4806. },
  4807. enumerable: true,
  4808. configurable: true
  4809. });
  4810. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4811. get: function () {
  4812. return this._depthFunc;
  4813. },
  4814. set: function (value) {
  4815. if (this._depthFunc === value) {
  4816. return;
  4817. }
  4818. this._depthFunc = value;
  4819. this._isDepthFuncDirty = true;
  4820. },
  4821. enumerable: true,
  4822. configurable: true
  4823. });
  4824. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4825. get: function () {
  4826. return this._depthMask;
  4827. },
  4828. set: function (value) {
  4829. if (this._depthMask === value) {
  4830. return;
  4831. }
  4832. this._depthMask = value;
  4833. this._isDepthMaskDirty = true;
  4834. },
  4835. enumerable: true,
  4836. configurable: true
  4837. });
  4838. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4839. get: function () {
  4840. return this._depthTest;
  4841. },
  4842. set: function (value) {
  4843. if (this._depthTest === value) {
  4844. return;
  4845. }
  4846. this._depthTest = value;
  4847. this._isDepthTestDirty = true;
  4848. },
  4849. enumerable: true,
  4850. configurable: true
  4851. });
  4852. _DepthCullingState.prototype.reset = function () {
  4853. this._depthMask = true;
  4854. this._depthTest = true;
  4855. this._depthFunc = null;
  4856. this._cull = null;
  4857. this._cullFace = null;
  4858. this._zOffset = 0;
  4859. this._isDepthTestDirty = true;
  4860. this._isDepthMaskDirty = true;
  4861. this._isDepthFuncDirty = false;
  4862. this._isCullFaceDirty = false;
  4863. this._isCullDirty = false;
  4864. this._isZOffsetDirty = false;
  4865. };
  4866. _DepthCullingState.prototype.apply = function (gl) {
  4867. if (!this.isDirty) {
  4868. return;
  4869. }
  4870. // Cull
  4871. if (this._isCullDirty) {
  4872. if (this.cull) {
  4873. gl.enable(gl.CULL_FACE);
  4874. }
  4875. else {
  4876. gl.disable(gl.CULL_FACE);
  4877. }
  4878. this._isCullDirty = false;
  4879. }
  4880. // Cull face
  4881. if (this._isCullFaceDirty) {
  4882. gl.cullFace(this.cullFace);
  4883. this._isCullFaceDirty = false;
  4884. }
  4885. // Depth mask
  4886. if (this._isDepthMaskDirty) {
  4887. gl.depthMask(this.depthMask);
  4888. this._isDepthMaskDirty = false;
  4889. }
  4890. // Depth test
  4891. if (this._isDepthTestDirty) {
  4892. if (this.depthTest) {
  4893. gl.enable(gl.DEPTH_TEST);
  4894. }
  4895. else {
  4896. gl.disable(gl.DEPTH_TEST);
  4897. }
  4898. this._isDepthTestDirty = false;
  4899. }
  4900. // Depth func
  4901. if (this._isDepthFuncDirty) {
  4902. gl.depthFunc(this.depthFunc);
  4903. this._isDepthFuncDirty = false;
  4904. }
  4905. // zOffset
  4906. if (this._isZOffsetDirty) {
  4907. if (this.zOffset) {
  4908. gl.enable(gl.POLYGON_OFFSET_FILL);
  4909. gl.polygonOffset(this.zOffset, 0);
  4910. }
  4911. else {
  4912. gl.disable(gl.POLYGON_OFFSET_FILL);
  4913. }
  4914. this._isZOffsetDirty = false;
  4915. }
  4916. };
  4917. return _DepthCullingState;
  4918. })();
  4919. BABYLON._DepthCullingState = _DepthCullingState;
  4920. var _AlphaState = (function () {
  4921. function _AlphaState() {
  4922. this._isAlphaBlendDirty = false;
  4923. this._isBlendFunctionParametersDirty = false;
  4924. this._alphaBlend = false;
  4925. this._blendFunctionParameters = new Array(4);
  4926. }
  4927. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4928. get: function () {
  4929. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4935. get: function () {
  4936. return this._alphaBlend;
  4937. },
  4938. set: function (value) {
  4939. if (this._alphaBlend === value) {
  4940. return;
  4941. }
  4942. this._alphaBlend = value;
  4943. this._isAlphaBlendDirty = true;
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4949. if (this._blendFunctionParameters[0] === value0 &&
  4950. this._blendFunctionParameters[1] === value1 &&
  4951. this._blendFunctionParameters[2] === value2 &&
  4952. this._blendFunctionParameters[3] === value3) {
  4953. return;
  4954. }
  4955. this._blendFunctionParameters[0] = value0;
  4956. this._blendFunctionParameters[1] = value1;
  4957. this._blendFunctionParameters[2] = value2;
  4958. this._blendFunctionParameters[3] = value3;
  4959. this._isBlendFunctionParametersDirty = true;
  4960. };
  4961. _AlphaState.prototype.reset = function () {
  4962. this._alphaBlend = false;
  4963. this._blendFunctionParameters[0] = null;
  4964. this._blendFunctionParameters[1] = null;
  4965. this._blendFunctionParameters[2] = null;
  4966. this._blendFunctionParameters[3] = null;
  4967. this._isAlphaBlendDirty = true;
  4968. this._isBlendFunctionParametersDirty = false;
  4969. };
  4970. _AlphaState.prototype.apply = function (gl) {
  4971. if (!this.isDirty) {
  4972. return;
  4973. }
  4974. // Alpha blend
  4975. if (this._isAlphaBlendDirty) {
  4976. if (this._alphaBlend) {
  4977. gl.enable(gl.BLEND);
  4978. }
  4979. else {
  4980. gl.disable(gl.BLEND);
  4981. }
  4982. this._isAlphaBlendDirty = false;
  4983. }
  4984. // Alpha function
  4985. if (this._isBlendFunctionParametersDirty) {
  4986. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4987. this._isBlendFunctionParametersDirty = false;
  4988. }
  4989. };
  4990. return _AlphaState;
  4991. })();
  4992. BABYLON._AlphaState = _AlphaState;
  4993. var compileShader = function (gl, source, type, defines) {
  4994. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4995. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4996. gl.compileShader(shader);
  4997. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4998. throw new Error(gl.getShaderInfoLog(shader));
  4999. }
  5000. return shader;
  5001. };
  5002. var getWebGLTextureType = function (gl, type) {
  5003. var textureType = gl.UNSIGNED_BYTE;
  5004. if (type === Engine.TEXTURETYPE_FLOAT)
  5005. textureType = gl.FLOAT;
  5006. return textureType;
  5007. };
  5008. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5009. var magFilter = gl.NEAREST;
  5010. var minFilter = gl.NEAREST;
  5011. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5012. magFilter = gl.LINEAR;
  5013. if (generateMipMaps) {
  5014. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5015. }
  5016. else {
  5017. minFilter = gl.LINEAR;
  5018. }
  5019. }
  5020. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5021. magFilter = gl.LINEAR;
  5022. if (generateMipMaps) {
  5023. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5024. }
  5025. else {
  5026. minFilter = gl.LINEAR;
  5027. }
  5028. }
  5029. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5030. magFilter = gl.NEAREST;
  5031. if (generateMipMaps) {
  5032. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5033. }
  5034. else {
  5035. minFilter = gl.NEAREST;
  5036. }
  5037. }
  5038. return {
  5039. min: minFilter,
  5040. mag: magFilter
  5041. };
  5042. };
  5043. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5045. var engine = scene.getEngine();
  5046. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5047. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5048. gl.bindTexture(gl.TEXTURE_2D, texture);
  5049. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5050. texture._baseWidth = width;
  5051. texture._baseHeight = height;
  5052. texture._width = potWidth;
  5053. texture._height = potHeight;
  5054. texture.isReady = true;
  5055. processFunction(potWidth, potHeight);
  5056. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5057. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5058. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5059. if (!noMipmap && !isCompressed) {
  5060. gl.generateMipmap(gl.TEXTURE_2D);
  5061. }
  5062. gl.bindTexture(gl.TEXTURE_2D, null);
  5063. engine.resetTextureCache();
  5064. scene._removePendingData(texture);
  5065. };
  5066. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5067. var img;
  5068. var onload = function () {
  5069. loadedImages[index] = img;
  5070. loadedImages._internalCount++;
  5071. scene._removePendingData(img);
  5072. if (loadedImages._internalCount === 6) {
  5073. onfinish(loadedImages);
  5074. }
  5075. };
  5076. var onerror = function () {
  5077. scene._removePendingData(img);
  5078. };
  5079. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5080. scene._addPendingData(img);
  5081. };
  5082. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5083. var loadedImages = [];
  5084. loadedImages._internalCount = 0;
  5085. for (var index = 0; index < 6; index++) {
  5086. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5087. }
  5088. };
  5089. var EngineCapabilities = (function () {
  5090. function EngineCapabilities() {
  5091. }
  5092. return EngineCapabilities;
  5093. })();
  5094. BABYLON.EngineCapabilities = EngineCapabilities;
  5095. /**
  5096. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5097. */
  5098. var Engine = (function () {
  5099. /**
  5100. * @constructor
  5101. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5102. * @param {boolean} [antialias] - enable antialias
  5103. * @param options - further options to be sent to the getContext function
  5104. */
  5105. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5106. var _this = this;
  5107. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5108. // Public members
  5109. this.isFullscreen = false;
  5110. this.isPointerLock = false;
  5111. this.cullBackFaces = true;
  5112. this.renderEvenInBackground = true;
  5113. // To enable/disable IDB support and avoid XHR on .manifest
  5114. this.enableOfflineSupport = true;
  5115. this.scenes = new Array();
  5116. this._windowIsBackground = false;
  5117. this._drawCalls = 0;
  5118. this._renderingQueueLaunched = false;
  5119. this._activeRenderLoops = [];
  5120. // FPS
  5121. this.fpsRange = 60;
  5122. this.previousFramesDuration = [];
  5123. this.fps = 60;
  5124. this.deltaTime = 0;
  5125. // States
  5126. this._depthCullingState = new _DepthCullingState();
  5127. this._alphaState = new _AlphaState();
  5128. this._alphaMode = Engine.ALPHA_DISABLE;
  5129. // Cache
  5130. this._loadedTexturesCache = new Array();
  5131. this._maxTextureChannels = 16;
  5132. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5133. this._compiledEffects = {};
  5134. this._uintIndicesCurrentlySet = false;
  5135. this._renderingCanvas = canvas;
  5136. options = options || {};
  5137. options.antialias = antialias;
  5138. if (options.preserveDrawingBuffer === undefined) {
  5139. options.preserveDrawingBuffer = false;
  5140. }
  5141. // GL
  5142. try {
  5143. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5144. }
  5145. catch (e) {
  5146. throw new Error("WebGL not supported");
  5147. }
  5148. if (!this._gl) {
  5149. throw new Error("WebGL not supported");
  5150. }
  5151. this._onBlur = function () {
  5152. _this._windowIsBackground = true;
  5153. };
  5154. this._onFocus = function () {
  5155. _this._windowIsBackground = false;
  5156. };
  5157. window.addEventListener("blur", this._onBlur);
  5158. window.addEventListener("focus", this._onFocus);
  5159. // Viewport
  5160. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5161. this.resize();
  5162. // Caps
  5163. this._caps = new EngineCapabilities();
  5164. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5165. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5166. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5167. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5168. // Infos
  5169. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5170. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5171. if (rendererInfo != null) {
  5172. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5173. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5174. }
  5175. if (!this._glVendor) {
  5176. this._glVendor = "Unknown vendor";
  5177. }
  5178. if (!this._glRenderer) {
  5179. this._glRenderer = "Unknown renderer";
  5180. }
  5181. // Extensions
  5182. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5183. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5184. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5185. 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');
  5186. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5187. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5188. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5189. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5190. this._caps.highPrecisionShaderSupported = true;
  5191. if (this._gl.getShaderPrecisionFormat) {
  5192. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5193. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5194. }
  5195. // Depth buffer
  5196. this.setDepthBuffer(true);
  5197. this.setDepthFunctionToLessOrEqual();
  5198. this.setDepthWrite(true);
  5199. // Fullscreen
  5200. this._onFullscreenChange = function () {
  5201. if (document.fullscreen !== undefined) {
  5202. _this.isFullscreen = document.fullscreen;
  5203. }
  5204. else if (document.mozFullScreen !== undefined) {
  5205. _this.isFullscreen = document.mozFullScreen;
  5206. }
  5207. else if (document.webkitIsFullScreen !== undefined) {
  5208. _this.isFullscreen = document.webkitIsFullScreen;
  5209. }
  5210. else if (document.msIsFullScreen !== undefined) {
  5211. _this.isFullscreen = document.msIsFullScreen;
  5212. }
  5213. // Pointer lock
  5214. if (_this.isFullscreen && _this._pointerLockRequested) {
  5215. canvas.requestPointerLock = canvas.requestPointerLock ||
  5216. canvas.msRequestPointerLock ||
  5217. canvas.mozRequestPointerLock ||
  5218. canvas.webkitRequestPointerLock;
  5219. if (canvas.requestPointerLock) {
  5220. canvas.requestPointerLock();
  5221. }
  5222. }
  5223. };
  5224. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5225. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5226. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5227. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5228. // Pointer lock
  5229. this._onPointerLockChange = function () {
  5230. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5231. document.webkitPointerLockElement === canvas ||
  5232. document.msPointerLockElement === canvas ||
  5233. document.pointerLockElement === canvas);
  5234. };
  5235. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5236. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5237. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5238. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5239. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5240. Engine.audioEngine = new BABYLON.AudioEngine();
  5241. }
  5242. //default loading screen
  5243. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5244. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5245. }
  5246. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5247. get: function () {
  5248. return Engine._ALPHA_DISABLE;
  5249. },
  5250. enumerable: true,
  5251. configurable: true
  5252. });
  5253. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5254. get: function () {
  5255. return Engine._ALPHA_ONEONE;
  5256. },
  5257. enumerable: true,
  5258. configurable: true
  5259. });
  5260. Object.defineProperty(Engine, "ALPHA_ADD", {
  5261. get: function () {
  5262. return Engine._ALPHA_ADD;
  5263. },
  5264. enumerable: true,
  5265. configurable: true
  5266. });
  5267. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5268. get: function () {
  5269. return Engine._ALPHA_COMBINE;
  5270. },
  5271. enumerable: true,
  5272. configurable: true
  5273. });
  5274. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5275. get: function () {
  5276. return Engine._ALPHA_SUBTRACT;
  5277. },
  5278. enumerable: true,
  5279. configurable: true
  5280. });
  5281. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5282. get: function () {
  5283. return Engine._ALPHA_MULTIPLY;
  5284. },
  5285. enumerable: true,
  5286. configurable: true
  5287. });
  5288. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5289. get: function () {
  5290. return Engine._ALPHA_MAXIMIZED;
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5296. get: function () {
  5297. return Engine._DELAYLOADSTATE_NONE;
  5298. },
  5299. enumerable: true,
  5300. configurable: true
  5301. });
  5302. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5303. get: function () {
  5304. return Engine._DELAYLOADSTATE_LOADED;
  5305. },
  5306. enumerable: true,
  5307. configurable: true
  5308. });
  5309. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5310. get: function () {
  5311. return Engine._DELAYLOADSTATE_LOADING;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5317. get: function () {
  5318. return Engine._DELAYLOADSTATE_NOTLOADED;
  5319. },
  5320. enumerable: true,
  5321. configurable: true
  5322. });
  5323. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5324. get: function () {
  5325. return Engine._TEXTUREFORMAT_ALPHA;
  5326. },
  5327. enumerable: true,
  5328. configurable: true
  5329. });
  5330. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5331. get: function () {
  5332. return Engine._TEXTUREFORMAT_LUMINANCE;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5338. get: function () {
  5339. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5345. get: function () {
  5346. return Engine._TEXTUREFORMAT_RGB;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5352. get: function () {
  5353. return Engine._TEXTUREFORMAT_RGBA;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5359. get: function () {
  5360. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5361. },
  5362. enumerable: true,
  5363. configurable: true
  5364. });
  5365. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5366. get: function () {
  5367. return Engine._TEXTURETYPE_FLOAT;
  5368. },
  5369. enumerable: true,
  5370. configurable: true
  5371. });
  5372. Object.defineProperty(Engine, "Version", {
  5373. get: function () {
  5374. return "2.3.0-alpha";
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Engine.prototype._prepareWorkingCanvas = function () {
  5380. if (this._workingCanvas) {
  5381. return;
  5382. }
  5383. this._workingCanvas = document.createElement("canvas");
  5384. this._workingContext = this._workingCanvas.getContext("2d");
  5385. };
  5386. Engine.prototype.resetTextureCache = function () {
  5387. for (var index = 0; index < this._maxTextureChannels; index++) {
  5388. this._activeTexturesCache[index] = null;
  5389. }
  5390. };
  5391. Engine.prototype.getGlInfo = function () {
  5392. return {
  5393. vendor: this._glVendor,
  5394. renderer: this._glRenderer,
  5395. version: this._glVersion
  5396. };
  5397. };
  5398. Engine.prototype.getAspectRatio = function (camera) {
  5399. var viewport = camera.viewport;
  5400. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5401. };
  5402. Engine.prototype.getRenderWidth = function () {
  5403. if (this._currentRenderTarget) {
  5404. return this._currentRenderTarget._width;
  5405. }
  5406. return this._renderingCanvas.width;
  5407. };
  5408. Engine.prototype.getRenderHeight = function () {
  5409. if (this._currentRenderTarget) {
  5410. return this._currentRenderTarget._height;
  5411. }
  5412. return this._renderingCanvas.height;
  5413. };
  5414. Engine.prototype.getRenderingCanvas = function () {
  5415. return this._renderingCanvas;
  5416. };
  5417. Engine.prototype.getRenderingCanvasClientRect = function () {
  5418. return this._renderingCanvas.getBoundingClientRect();
  5419. };
  5420. Engine.prototype.setHardwareScalingLevel = function (level) {
  5421. this._hardwareScalingLevel = level;
  5422. this.resize();
  5423. };
  5424. Engine.prototype.getHardwareScalingLevel = function () {
  5425. return this._hardwareScalingLevel;
  5426. };
  5427. Engine.prototype.getLoadedTexturesCache = function () {
  5428. return this._loadedTexturesCache;
  5429. };
  5430. Engine.prototype.getCaps = function () {
  5431. return this._caps;
  5432. };
  5433. Object.defineProperty(Engine.prototype, "drawCalls", {
  5434. get: function () {
  5435. return this._drawCalls;
  5436. },
  5437. enumerable: true,
  5438. configurable: true
  5439. });
  5440. // Methods
  5441. Engine.prototype.resetDrawCalls = function () {
  5442. this._drawCalls = 0;
  5443. };
  5444. Engine.prototype.setDepthFunctionToGreater = function () {
  5445. this._depthCullingState.depthFunc = this._gl.GREATER;
  5446. };
  5447. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5448. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5449. };
  5450. Engine.prototype.setDepthFunctionToLess = function () {
  5451. this._depthCullingState.depthFunc = this._gl.LESS;
  5452. };
  5453. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5454. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5455. };
  5456. /**
  5457. * stop executing a render loop function and remove it from the execution array
  5458. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5459. */
  5460. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5461. if (!renderFunction) {
  5462. this._activeRenderLoops = [];
  5463. return;
  5464. }
  5465. var index = this._activeRenderLoops.indexOf(renderFunction);
  5466. if (index >= 0) {
  5467. this._activeRenderLoops.splice(index, 1);
  5468. }
  5469. };
  5470. Engine.prototype._renderLoop = function () {
  5471. var shouldRender = true;
  5472. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5473. shouldRender = false;
  5474. }
  5475. if (shouldRender) {
  5476. // Start new frame
  5477. this.beginFrame();
  5478. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5479. var renderFunction = this._activeRenderLoops[index];
  5480. renderFunction();
  5481. }
  5482. // Present
  5483. this.endFrame();
  5484. }
  5485. if (this._activeRenderLoops.length > 0) {
  5486. // Register new frame
  5487. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5488. }
  5489. else {
  5490. this._renderingQueueLaunched = false;
  5491. }
  5492. };
  5493. /**
  5494. * Register and execute a render loop. The engine can have more than one render function.
  5495. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5496. * @example
  5497. * engine.runRenderLoop(function () {
  5498. * scene.render()
  5499. * })
  5500. */
  5501. Engine.prototype.runRenderLoop = function (renderFunction) {
  5502. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5503. return;
  5504. }
  5505. this._activeRenderLoops.push(renderFunction);
  5506. if (!this._renderingQueueLaunched) {
  5507. this._renderingQueueLaunched = true;
  5508. this._bindedRenderFunction = this._renderLoop.bind(this);
  5509. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5510. }
  5511. };
  5512. /**
  5513. * Toggle full screen mode.
  5514. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5515. */
  5516. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5517. if (this.isFullscreen) {
  5518. BABYLON.Tools.ExitFullscreen();
  5519. }
  5520. else {
  5521. this._pointerLockRequested = requestPointerLock;
  5522. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5523. }
  5524. };
  5525. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5526. this.applyStates();
  5527. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5528. if (this._depthCullingState.depthMask) {
  5529. this._gl.clearDepth(1.0);
  5530. }
  5531. var mode = 0;
  5532. if (backBuffer)
  5533. mode |= this._gl.COLOR_BUFFER_BIT;
  5534. if (depthStencil && this._depthCullingState.depthMask)
  5535. mode |= this._gl.DEPTH_BUFFER_BIT;
  5536. this._gl.clear(mode);
  5537. };
  5538. /**
  5539. * Set the WebGL's viewport
  5540. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5541. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5542. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5543. */
  5544. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5545. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5546. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5547. var x = viewport.x || 0;
  5548. var y = viewport.y || 0;
  5549. this._cachedViewport = viewport;
  5550. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5551. };
  5552. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5553. this._cachedViewport = null;
  5554. this._gl.viewport(x, y, width, height);
  5555. };
  5556. Engine.prototype.beginFrame = function () {
  5557. this._measureFps();
  5558. };
  5559. Engine.prototype.endFrame = function () {
  5560. //this.flushFramebuffer();
  5561. };
  5562. /**
  5563. * resize the view according to the canvas' size.
  5564. * @example
  5565. * window.addEventListener("resize", function () {
  5566. * engine.resize();
  5567. * });
  5568. */
  5569. Engine.prototype.resize = function () {
  5570. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5571. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5572. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5573. for (var index = 0; index < this.scenes.length; index++) {
  5574. var scene = this.scenes[index];
  5575. if (scene.debugLayer.isVisible()) {
  5576. scene.debugLayer._syncPositions();
  5577. }
  5578. }
  5579. };
  5580. /**
  5581. * force a specific size of the canvas
  5582. * @param {number} width - the new canvas' width
  5583. * @param {number} height - the new canvas' height
  5584. */
  5585. Engine.prototype.setSize = function (width, height) {
  5586. this._renderingCanvas.width = width;
  5587. this._renderingCanvas.height = height;
  5588. for (var index = 0; index < this.scenes.length; index++) {
  5589. var scene = this.scenes[index];
  5590. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5591. var cam = scene.cameras[camIndex];
  5592. cam._currentRenderId = 0;
  5593. }
  5594. }
  5595. };
  5596. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5597. this._currentRenderTarget = texture;
  5598. var gl = this._gl;
  5599. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5600. if (texture.isCube) {
  5601. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5602. }
  5603. else {
  5604. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5605. }
  5606. this._gl.viewport(0, 0, texture._width, texture._height);
  5607. this.wipeCaches();
  5608. };
  5609. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5610. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5611. this._currentRenderTarget = null;
  5612. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5613. var gl = this._gl;
  5614. gl.bindTexture(gl.TEXTURE_2D, texture);
  5615. gl.generateMipmap(gl.TEXTURE_2D);
  5616. gl.bindTexture(gl.TEXTURE_2D, null);
  5617. }
  5618. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5619. };
  5620. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5621. if (texture.generateMipMaps) {
  5622. var gl = this._gl;
  5623. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5624. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5625. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5626. }
  5627. };
  5628. Engine.prototype.flushFramebuffer = function () {
  5629. this._gl.flush();
  5630. };
  5631. Engine.prototype.restoreDefaultFramebuffer = function () {
  5632. this._currentRenderTarget = null;
  5633. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5634. this.setViewport(this._cachedViewport);
  5635. this.wipeCaches();
  5636. };
  5637. // VBOs
  5638. Engine.prototype._resetVertexBufferBinding = function () {
  5639. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5640. this._cachedVertexBuffers = null;
  5641. };
  5642. Engine.prototype.createVertexBuffer = function (vertices) {
  5643. var vbo = this._gl.createBuffer();
  5644. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5645. if (vertices instanceof Float32Array) {
  5646. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5647. }
  5648. else {
  5649. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5650. }
  5651. this._resetVertexBufferBinding();
  5652. vbo.references = 1;
  5653. return vbo;
  5654. };
  5655. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5656. var vbo = this._gl.createBuffer();
  5657. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5658. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5659. this._resetVertexBufferBinding();
  5660. vbo.references = 1;
  5661. return vbo;
  5662. };
  5663. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5664. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5665. if (offset === undefined) {
  5666. offset = 0;
  5667. }
  5668. if (vertices instanceof Float32Array) {
  5669. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5670. }
  5671. else {
  5672. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5673. }
  5674. this._resetVertexBufferBinding();
  5675. };
  5676. Engine.prototype._resetIndexBufferBinding = function () {
  5677. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5678. this._cachedIndexBuffer = null;
  5679. };
  5680. Engine.prototype.createIndexBuffer = function (indices) {
  5681. var vbo = this._gl.createBuffer();
  5682. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5683. // Check for 32 bits indices
  5684. var arrayBuffer;
  5685. var need32Bits = false;
  5686. if (this._caps.uintIndices) {
  5687. for (var index = 0; index < indices.length; index++) {
  5688. if (indices[index] > 65535) {
  5689. need32Bits = true;
  5690. break;
  5691. }
  5692. }
  5693. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5694. }
  5695. else {
  5696. arrayBuffer = new Uint16Array(indices);
  5697. }
  5698. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5699. this._resetIndexBufferBinding();
  5700. vbo.references = 1;
  5701. vbo.is32Bits = need32Bits;
  5702. return vbo;
  5703. };
  5704. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5705. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5706. this._cachedVertexBuffers = vertexBuffer;
  5707. this._cachedEffectForVertexBuffers = effect;
  5708. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5709. var offset = 0;
  5710. for (var index = 0; index < vertexDeclaration.length; index++) {
  5711. var order = effect.getAttributeLocation(index);
  5712. if (order >= 0) {
  5713. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5714. }
  5715. offset += vertexDeclaration[index] * 4;
  5716. }
  5717. }
  5718. if (this._cachedIndexBuffer !== indexBuffer) {
  5719. this._cachedIndexBuffer = indexBuffer;
  5720. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5721. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5722. }
  5723. };
  5724. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5725. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5726. this._cachedVertexBuffers = vertexBuffers;
  5727. this._cachedEffectForVertexBuffers = effect;
  5728. var attributes = effect.getAttributesNames();
  5729. for (var index = 0; index < attributes.length; index++) {
  5730. var order = effect.getAttributeLocation(index);
  5731. if (order >= 0) {
  5732. var vertexBuffer = vertexBuffers[attributes[index]];
  5733. if (!vertexBuffer) {
  5734. continue;
  5735. }
  5736. var stride = vertexBuffer.getStrideSize();
  5737. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5738. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5739. }
  5740. }
  5741. }
  5742. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5743. this._cachedIndexBuffer = indexBuffer;
  5744. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5745. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5746. }
  5747. };
  5748. Engine.prototype._releaseBuffer = function (buffer) {
  5749. buffer.references--;
  5750. if (buffer.references === 0) {
  5751. this._gl.deleteBuffer(buffer);
  5752. return true;
  5753. }
  5754. return false;
  5755. };
  5756. Engine.prototype.createInstancesBuffer = function (capacity) {
  5757. var buffer = this._gl.createBuffer();
  5758. buffer.capacity = capacity;
  5759. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5760. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5761. return buffer;
  5762. };
  5763. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5764. this._gl.deleteBuffer(buffer);
  5765. };
  5766. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5767. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5768. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5769. for (var index = 0; index < 4; index++) {
  5770. var offsetLocation = offsetLocations[index];
  5771. this._gl.enableVertexAttribArray(offsetLocation);
  5772. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5773. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5774. }
  5775. };
  5776. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5777. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5778. for (var index = 0; index < 4; index++) {
  5779. var offsetLocation = offsetLocations[index];
  5780. this._gl.disableVertexAttribArray(offsetLocation);
  5781. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5782. }
  5783. };
  5784. Engine.prototype.applyStates = function () {
  5785. this._depthCullingState.apply(this._gl);
  5786. this._alphaState.apply(this._gl);
  5787. };
  5788. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5789. // Apply states
  5790. this.applyStates();
  5791. this._drawCalls++;
  5792. // Render
  5793. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5794. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5795. if (instancesCount) {
  5796. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5797. return;
  5798. }
  5799. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5800. };
  5801. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5802. // Apply states
  5803. this.applyStates();
  5804. this._drawCalls++;
  5805. if (instancesCount) {
  5806. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5807. return;
  5808. }
  5809. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5810. };
  5811. // Shaders
  5812. Engine.prototype._releaseEffect = function (effect) {
  5813. if (this._compiledEffects[effect._key]) {
  5814. delete this._compiledEffects[effect._key];
  5815. if (effect.getProgram()) {
  5816. this._gl.deleteProgram(effect.getProgram());
  5817. }
  5818. }
  5819. };
  5820. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5821. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5822. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5823. var name = vertex + "+" + fragment + "@" + defines;
  5824. if (this._compiledEffects[name]) {
  5825. return this._compiledEffects[name];
  5826. }
  5827. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5828. effect._key = name;
  5829. this._compiledEffects[name] = effect;
  5830. return effect;
  5831. };
  5832. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5833. if (uniformsNames === void 0) { uniformsNames = []; }
  5834. if (samplers === void 0) { samplers = []; }
  5835. if (defines === void 0) { defines = ""; }
  5836. return this.createEffect({
  5837. vertex: "particles",
  5838. fragmentElement: fragmentName
  5839. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5840. };
  5841. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5842. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5843. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5844. var shaderProgram = this._gl.createProgram();
  5845. this._gl.attachShader(shaderProgram, vertexShader);
  5846. this._gl.attachShader(shaderProgram, fragmentShader);
  5847. this._gl.linkProgram(shaderProgram);
  5848. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5849. if (!linked) {
  5850. var error = this._gl.getProgramInfoLog(shaderProgram);
  5851. if (error) {
  5852. throw new Error(error);
  5853. }
  5854. }
  5855. this._gl.deleteShader(vertexShader);
  5856. this._gl.deleteShader(fragmentShader);
  5857. return shaderProgram;
  5858. };
  5859. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5860. var results = [];
  5861. for (var index = 0; index < uniformsNames.length; index++) {
  5862. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5863. }
  5864. return results;
  5865. };
  5866. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5867. var results = [];
  5868. for (var index = 0; index < attributesNames.length; index++) {
  5869. try {
  5870. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5871. }
  5872. catch (e) {
  5873. results.push(-1);
  5874. }
  5875. }
  5876. return results;
  5877. };
  5878. Engine.prototype.enableEffect = function (effect) {
  5879. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5880. if (effect && effect.onBind) {
  5881. effect.onBind(effect);
  5882. }
  5883. return;
  5884. }
  5885. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5886. // Use program
  5887. this._gl.useProgram(effect.getProgram());
  5888. for (var i in this._vertexAttribArrays) {
  5889. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5890. continue;
  5891. }
  5892. this._vertexAttribArrays[i] = false;
  5893. this._gl.disableVertexAttribArray(i);
  5894. }
  5895. var attributesCount = effect.getAttributesCount();
  5896. for (var index = 0; index < attributesCount; index++) {
  5897. // Attributes
  5898. var order = effect.getAttributeLocation(index);
  5899. if (order >= 0) {
  5900. this._vertexAttribArrays[order] = true;
  5901. this._gl.enableVertexAttribArray(order);
  5902. }
  5903. }
  5904. this._currentEffect = effect;
  5905. if (effect.onBind) {
  5906. effect.onBind(effect);
  5907. }
  5908. };
  5909. Engine.prototype.setArray = function (uniform, array) {
  5910. if (!uniform)
  5911. return;
  5912. this._gl.uniform1fv(uniform, array);
  5913. };
  5914. Engine.prototype.setArray2 = function (uniform, array) {
  5915. if (!uniform || array.length % 2 !== 0)
  5916. return;
  5917. this._gl.uniform2fv(uniform, array);
  5918. };
  5919. Engine.prototype.setArray3 = function (uniform, array) {
  5920. if (!uniform || array.length % 3 !== 0)
  5921. return;
  5922. this._gl.uniform3fv(uniform, array);
  5923. };
  5924. Engine.prototype.setArray4 = function (uniform, array) {
  5925. if (!uniform || array.length % 4 !== 0)
  5926. return;
  5927. this._gl.uniform4fv(uniform, array);
  5928. };
  5929. Engine.prototype.setMatrices = function (uniform, matrices) {
  5930. if (!uniform)
  5931. return;
  5932. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5933. };
  5934. Engine.prototype.setMatrix = function (uniform, matrix) {
  5935. if (!uniform)
  5936. return;
  5937. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5938. };
  5939. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5940. if (!uniform)
  5941. return;
  5942. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5943. };
  5944. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5945. if (!uniform)
  5946. return;
  5947. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5948. };
  5949. Engine.prototype.setFloat = function (uniform, value) {
  5950. if (!uniform)
  5951. return;
  5952. this._gl.uniform1f(uniform, value);
  5953. };
  5954. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5955. if (!uniform)
  5956. return;
  5957. this._gl.uniform2f(uniform, x, y);
  5958. };
  5959. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5960. if (!uniform)
  5961. return;
  5962. this._gl.uniform3f(uniform, x, y, z);
  5963. };
  5964. Engine.prototype.setBool = function (uniform, bool) {
  5965. if (!uniform)
  5966. return;
  5967. this._gl.uniform1i(uniform, bool);
  5968. };
  5969. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5970. if (!uniform)
  5971. return;
  5972. this._gl.uniform4f(uniform, x, y, z, w);
  5973. };
  5974. Engine.prototype.setColor3 = function (uniform, color3) {
  5975. if (!uniform)
  5976. return;
  5977. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5978. };
  5979. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5980. if (!uniform)
  5981. return;
  5982. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5983. };
  5984. // States
  5985. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5986. if (zOffset === void 0) { zOffset = 0; }
  5987. if (reverseSide === void 0) { reverseSide = false; }
  5988. // Culling
  5989. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5990. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5991. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5992. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5993. if (culling) {
  5994. this._depthCullingState.cullFace = cullFace;
  5995. this._depthCullingState.cull = true;
  5996. }
  5997. else {
  5998. this._depthCullingState.cull = false;
  5999. }
  6000. }
  6001. // Z offset
  6002. this._depthCullingState.zOffset = zOffset;
  6003. };
  6004. Engine.prototype.setDepthBuffer = function (enable) {
  6005. this._depthCullingState.depthTest = enable;
  6006. };
  6007. Engine.prototype.getDepthWrite = function () {
  6008. return this._depthCullingState.depthMask;
  6009. };
  6010. Engine.prototype.setDepthWrite = function (enable) {
  6011. this._depthCullingState.depthMask = enable;
  6012. };
  6013. Engine.prototype.setColorWrite = function (enable) {
  6014. this._gl.colorMask(enable, enable, enable, enable);
  6015. };
  6016. Engine.prototype.setAlphaMode = function (mode) {
  6017. if (this._alphaMode === mode) {
  6018. return;
  6019. }
  6020. switch (mode) {
  6021. case Engine.ALPHA_DISABLE:
  6022. this.setDepthWrite(true);
  6023. this._alphaState.alphaBlend = false;
  6024. break;
  6025. case Engine.ALPHA_COMBINE:
  6026. this.setDepthWrite(false);
  6027. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6028. this._alphaState.alphaBlend = true;
  6029. break;
  6030. case Engine.ALPHA_ONEONE:
  6031. this.setDepthWrite(false);
  6032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6033. this._alphaState.alphaBlend = true;
  6034. break;
  6035. case Engine.ALPHA_ADD:
  6036. this.setDepthWrite(false);
  6037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6038. this._alphaState.alphaBlend = true;
  6039. break;
  6040. case Engine.ALPHA_SUBTRACT:
  6041. this.setDepthWrite(false);
  6042. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6043. this._alphaState.alphaBlend = true;
  6044. break;
  6045. case Engine.ALPHA_MULTIPLY:
  6046. this.setDepthWrite(false);
  6047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6048. this._alphaState.alphaBlend = true;
  6049. break;
  6050. case Engine.ALPHA_MAXIMIZED:
  6051. this.setDepthWrite(false);
  6052. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6053. this._alphaState.alphaBlend = true;
  6054. break;
  6055. }
  6056. this._alphaMode = mode;
  6057. };
  6058. Engine.prototype.getAlphaMode = function () {
  6059. return this._alphaMode;
  6060. };
  6061. Engine.prototype.setAlphaTesting = function (enable) {
  6062. this._alphaTest = enable;
  6063. };
  6064. Engine.prototype.getAlphaTesting = function () {
  6065. return this._alphaTest;
  6066. };
  6067. // Textures
  6068. Engine.prototype.wipeCaches = function () {
  6069. this.resetTextureCache();
  6070. this._currentEffect = null;
  6071. this._depthCullingState.reset();
  6072. this._alphaState.reset();
  6073. this._cachedVertexBuffers = null;
  6074. this._cachedIndexBuffer = null;
  6075. this._cachedEffectForVertexBuffers = null;
  6076. };
  6077. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6078. var gl = this._gl;
  6079. gl.bindTexture(gl.TEXTURE_2D, texture);
  6080. var magFilter = gl.NEAREST;
  6081. var minFilter = gl.NEAREST;
  6082. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6083. magFilter = gl.LINEAR;
  6084. minFilter = gl.LINEAR;
  6085. }
  6086. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6087. magFilter = gl.LINEAR;
  6088. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6089. }
  6090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6092. gl.bindTexture(gl.TEXTURE_2D, null);
  6093. texture.samplingMode = samplingMode;
  6094. };
  6095. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6096. var _this = this;
  6097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6098. if (onLoad === void 0) { onLoad = null; }
  6099. if (onError === void 0) { onError = null; }
  6100. if (buffer === void 0) { buffer = null; }
  6101. var texture = this._gl.createTexture();
  6102. var extension;
  6103. var fromData = false;
  6104. if (url.substr(0, 5) === "data:") {
  6105. fromData = true;
  6106. }
  6107. if (!fromData)
  6108. extension = url.substr(url.length - 4, 4).toLowerCase();
  6109. else {
  6110. var oldUrl = url;
  6111. fromData = oldUrl.split(':');
  6112. url = oldUrl;
  6113. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6114. }
  6115. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6116. var isTGA = (extension === ".tga");
  6117. scene._addPendingData(texture);
  6118. texture.url = url;
  6119. texture.noMipmap = noMipmap;
  6120. texture.references = 1;
  6121. texture.samplingMode = samplingMode;
  6122. this._loadedTexturesCache.push(texture);
  6123. var onerror = function () {
  6124. scene._removePendingData(texture);
  6125. if (onError) {
  6126. onError();
  6127. }
  6128. };
  6129. var callback;
  6130. if (isTGA) {
  6131. callback = function (arrayBuffer) {
  6132. var data = new Uint8Array(arrayBuffer);
  6133. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6134. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6135. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6136. if (onLoad) {
  6137. onLoad();
  6138. }
  6139. }, samplingMode);
  6140. };
  6141. if (!(fromData instanceof Array))
  6142. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6143. callback(arrayBuffer);
  6144. }, onerror, scene.database, true);
  6145. else
  6146. callback(buffer);
  6147. }
  6148. else if (isDDS) {
  6149. callback = function (data) {
  6150. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6151. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6152. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6153. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6154. if (onLoad) {
  6155. onLoad();
  6156. }
  6157. }, samplingMode);
  6158. };
  6159. if (!(fromData instanceof Array))
  6160. BABYLON.Tools.LoadFile(url, function (data) {
  6161. callback(data);
  6162. }, onerror, scene.database, true);
  6163. else
  6164. callback(buffer);
  6165. }
  6166. else {
  6167. var onload = function (img) {
  6168. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6169. var isPot = (img.width === potWidth && img.height === potHeight);
  6170. if (!isPot) {
  6171. _this._prepareWorkingCanvas();
  6172. _this._workingCanvas.width = potWidth;
  6173. _this._workingCanvas.height = potHeight;
  6174. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6175. _this._workingContext.imageSmoothingEnabled = false;
  6176. _this._workingContext.mozImageSmoothingEnabled = false;
  6177. _this._workingContext.oImageSmoothingEnabled = false;
  6178. _this._workingContext.webkitImageSmoothingEnabled = false;
  6179. _this._workingContext.msImageSmoothingEnabled = false;
  6180. }
  6181. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6182. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6183. _this._workingContext.imageSmoothingEnabled = true;
  6184. _this._workingContext.mozImageSmoothingEnabled = true;
  6185. _this._workingContext.oImageSmoothingEnabled = true;
  6186. _this._workingContext.webkitImageSmoothingEnabled = true;
  6187. _this._workingContext.msImageSmoothingEnabled = true;
  6188. }
  6189. }
  6190. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6191. if (onLoad) {
  6192. onLoad();
  6193. }
  6194. }, samplingMode);
  6195. };
  6196. if (!(fromData instanceof Array))
  6197. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6198. else
  6199. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6200. }
  6201. return texture;
  6202. };
  6203. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6204. if (compression === void 0) { compression = null; }
  6205. var internalFormat = this._gl.RGBA;
  6206. switch (format) {
  6207. case Engine.TEXTUREFORMAT_ALPHA:
  6208. internalFormat = this._gl.ALPHA;
  6209. break;
  6210. case Engine.TEXTUREFORMAT_LUMINANCE:
  6211. internalFormat = this._gl.LUMINANCE;
  6212. break;
  6213. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6214. internalFormat = this._gl.LUMINANCE_ALPHA;
  6215. break;
  6216. case Engine.TEXTUREFORMAT_RGB:
  6217. internalFormat = this._gl.RGB;
  6218. break;
  6219. case Engine.TEXTUREFORMAT_RGBA:
  6220. internalFormat = this._gl.RGBA;
  6221. break;
  6222. }
  6223. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6224. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6225. if (compression) {
  6226. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6227. }
  6228. else {
  6229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6230. }
  6231. if (texture.generateMipMaps) {
  6232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6233. }
  6234. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6235. this.resetTextureCache();
  6236. texture.isReady = true;
  6237. };
  6238. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6239. if (compression === void 0) { compression = null; }
  6240. var texture = this._gl.createTexture();
  6241. texture._baseWidth = width;
  6242. texture._baseHeight = height;
  6243. texture._width = width;
  6244. texture._height = height;
  6245. texture.references = 1;
  6246. this.updateRawTexture(texture, data, format, invertY, compression);
  6247. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6248. // Filters
  6249. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6250. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6251. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6252. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6253. texture.samplingMode = samplingMode;
  6254. this._loadedTexturesCache.push(texture);
  6255. return texture;
  6256. };
  6257. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6258. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6259. var texture = this._gl.createTexture();
  6260. texture._baseWidth = width;
  6261. texture._baseHeight = height;
  6262. if (forceExponantOfTwo) {
  6263. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6264. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6265. }
  6266. this.resetTextureCache();
  6267. texture._width = width;
  6268. texture._height = height;
  6269. texture.isReady = false;
  6270. texture.generateMipMaps = generateMipMaps;
  6271. texture.references = 1;
  6272. texture.samplingMode = samplingMode;
  6273. this.updateTextureSamplingMode(samplingMode, texture);
  6274. this._loadedTexturesCache.push(texture);
  6275. return texture;
  6276. };
  6277. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6278. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6279. if (texture.isCube) {
  6280. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6281. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6282. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6283. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6284. }
  6285. else {
  6286. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6289. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6290. }
  6291. };
  6292. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6293. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6294. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6295. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6296. if (texture.generateMipMaps) {
  6297. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6298. }
  6299. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6300. this.resetTextureCache();
  6301. texture.isReady = true;
  6302. };
  6303. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6304. if (texture._isDisabled) {
  6305. return;
  6306. }
  6307. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6308. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6309. try {
  6310. // Testing video texture support
  6311. if (this._videoTextureSupported === undefined) {
  6312. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6313. if (this._gl.getError() !== 0) {
  6314. this._videoTextureSupported = false;
  6315. }
  6316. else {
  6317. this._videoTextureSupported = true;
  6318. }
  6319. }
  6320. // Copy video through the current working canvas if video texture is not supported
  6321. if (!this._videoTextureSupported) {
  6322. if (!texture._workingCanvas) {
  6323. texture._workingCanvas = document.createElement("canvas");
  6324. texture._workingContext = texture._workingCanvas.getContext("2d");
  6325. texture._workingCanvas.width = texture._width;
  6326. texture._workingCanvas.height = texture._height;
  6327. }
  6328. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6329. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6330. }
  6331. else {
  6332. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6333. }
  6334. if (texture.generateMipMaps) {
  6335. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6336. }
  6337. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6338. this.resetTextureCache();
  6339. texture.isReady = true;
  6340. }
  6341. catch (ex) {
  6342. // Something unexpected
  6343. // Let's disable the texture
  6344. texture._isDisabled = true;
  6345. }
  6346. };
  6347. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6348. // old version had a "generateMipMaps" arg instead of options.
  6349. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6350. // in the same way, generateDepthBuffer is defaulted to true
  6351. var generateMipMaps = false;
  6352. var generateDepthBuffer = true;
  6353. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6354. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6355. if (options !== undefined) {
  6356. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6357. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6358. type = options.type === undefined ? type : options.type;
  6359. if (options.samplingMode !== undefined) {
  6360. samplingMode = options.samplingMode;
  6361. }
  6362. if (type === Engine.TEXTURETYPE_FLOAT) {
  6363. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6364. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6365. }
  6366. }
  6367. var gl = this._gl;
  6368. var texture = gl.createTexture();
  6369. gl.bindTexture(gl.TEXTURE_2D, texture);
  6370. var width = size.width || size;
  6371. var height = size.height || size;
  6372. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6373. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6374. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6375. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6376. }
  6377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6381. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6382. var depthBuffer;
  6383. // Create the depth buffer
  6384. if (generateDepthBuffer) {
  6385. depthBuffer = gl.createRenderbuffer();
  6386. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6387. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6388. }
  6389. // Create the framebuffer
  6390. var framebuffer = gl.createFramebuffer();
  6391. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6392. if (generateDepthBuffer) {
  6393. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6394. }
  6395. if (generateMipMaps) {
  6396. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6397. }
  6398. // Unbind
  6399. gl.bindTexture(gl.TEXTURE_2D, null);
  6400. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6401. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6402. texture._framebuffer = framebuffer;
  6403. if (generateDepthBuffer) {
  6404. texture._depthBuffer = depthBuffer;
  6405. }
  6406. texture._width = width;
  6407. texture._height = height;
  6408. texture.isReady = true;
  6409. texture.generateMipMaps = generateMipMaps;
  6410. texture.references = 1;
  6411. texture.samplingMode = samplingMode;
  6412. this.resetTextureCache();
  6413. this._loadedTexturesCache.push(texture);
  6414. return texture;
  6415. };
  6416. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6417. var gl = this._gl;
  6418. var texture = gl.createTexture();
  6419. var generateMipMaps = true;
  6420. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6421. if (options !== undefined) {
  6422. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6423. if (options.samplingMode !== undefined) {
  6424. samplingMode = options.samplingMode;
  6425. }
  6426. }
  6427. texture.isCube = true;
  6428. texture.references = 1;
  6429. texture.generateMipMaps = generateMipMaps;
  6430. texture.references = 1;
  6431. texture.samplingMode = samplingMode;
  6432. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6433. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6434. for (var face = 0; face < 6; face++) {
  6435. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6436. }
  6437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6441. // Create the depth buffer
  6442. var depthBuffer = gl.createRenderbuffer();
  6443. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6444. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6445. // Create the framebuffer
  6446. var framebuffer = gl.createFramebuffer();
  6447. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6448. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6449. // mipmaps
  6450. if (texture.generateMipMaps) {
  6451. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6452. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6453. }
  6454. // Unbind
  6455. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6457. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6458. texture._framebuffer = framebuffer;
  6459. texture._depthBuffer = depthBuffer;
  6460. this.resetTextureCache();
  6461. texture._width = size;
  6462. texture._height = size;
  6463. texture.isReady = true;
  6464. return texture;
  6465. };
  6466. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6467. var _this = this;
  6468. var gl = this._gl;
  6469. var texture = gl.createTexture();
  6470. texture.isCube = true;
  6471. texture.url = rootUrl;
  6472. texture.references = 1;
  6473. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6474. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6475. if (isDDS) {
  6476. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6477. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6478. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6479. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6480. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6481. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6482. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6483. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6484. }
  6485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6489. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6490. _this.resetTextureCache();
  6491. texture._width = info.width;
  6492. texture._height = info.height;
  6493. texture.isReady = true;
  6494. }, null, null, true);
  6495. }
  6496. else {
  6497. cascadeLoad(rootUrl, scene, function (imgs) {
  6498. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6499. var height = width;
  6500. _this._prepareWorkingCanvas();
  6501. _this._workingCanvas.width = width;
  6502. _this._workingCanvas.height = height;
  6503. var faces = [
  6504. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6505. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6506. ];
  6507. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6508. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6509. for (var index = 0; index < faces.length; index++) {
  6510. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6511. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6512. }
  6513. if (!noMipmap) {
  6514. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6515. }
  6516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6520. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6521. _this.resetTextureCache();
  6522. texture._width = width;
  6523. texture._height = height;
  6524. texture.isReady = true;
  6525. }, extensions);
  6526. }
  6527. return texture;
  6528. };
  6529. Engine.prototype._releaseTexture = function (texture) {
  6530. var gl = this._gl;
  6531. if (texture._framebuffer) {
  6532. gl.deleteFramebuffer(texture._framebuffer);
  6533. }
  6534. if (texture._depthBuffer) {
  6535. gl.deleteRenderbuffer(texture._depthBuffer);
  6536. }
  6537. gl.deleteTexture(texture);
  6538. // Unbind channels
  6539. this.unbindAllTextures();
  6540. var index = this._loadedTexturesCache.indexOf(texture);
  6541. if (index !== -1) {
  6542. this._loadedTexturesCache.splice(index, 1);
  6543. }
  6544. };
  6545. Engine.prototype.bindSamplers = function (effect) {
  6546. this._gl.useProgram(effect.getProgram());
  6547. var samplers = effect.getSamplers();
  6548. for (var index = 0; index < samplers.length; index++) {
  6549. var uniform = effect.getUniform(samplers[index]);
  6550. this._gl.uniform1i(uniform, index);
  6551. }
  6552. this._currentEffect = null;
  6553. };
  6554. Engine.prototype._bindTexture = function (channel, texture) {
  6555. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6557. this._activeTexturesCache[channel] = null;
  6558. };
  6559. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6560. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6561. };
  6562. Engine.prototype.unbindAllTextures = function () {
  6563. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6564. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6566. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6567. this._activeTexturesCache[channel] = null;
  6568. }
  6569. };
  6570. Engine.prototype.setTexture = function (channel, texture) {
  6571. if (channel < 0) {
  6572. return;
  6573. }
  6574. // Not ready?
  6575. if (!texture || !texture.isReady()) {
  6576. if (this._activeTexturesCache[channel] != null) {
  6577. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6578. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6579. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6580. this._activeTexturesCache[channel] = null;
  6581. }
  6582. return;
  6583. }
  6584. // Video
  6585. var alreadyActivated = false;
  6586. if (texture instanceof BABYLON.VideoTexture) {
  6587. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6588. alreadyActivated = true;
  6589. texture.update();
  6590. }
  6591. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6592. texture.delayLoad();
  6593. return;
  6594. }
  6595. if (this._activeTexturesCache[channel] === texture) {
  6596. return;
  6597. }
  6598. this._activeTexturesCache[channel] = texture;
  6599. var internalTexture = texture.getInternalTexture();
  6600. if (!alreadyActivated) {
  6601. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6602. }
  6603. if (internalTexture.isCube) {
  6604. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6605. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6606. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6607. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6608. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6609. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6610. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6611. }
  6612. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6613. }
  6614. else {
  6615. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6616. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6617. internalTexture._cachedWrapU = texture.wrapU;
  6618. switch (texture.wrapU) {
  6619. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6621. break;
  6622. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6623. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6624. break;
  6625. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6627. break;
  6628. }
  6629. }
  6630. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6631. internalTexture._cachedWrapV = texture.wrapV;
  6632. switch (texture.wrapV) {
  6633. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6634. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6635. break;
  6636. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6637. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6638. break;
  6639. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6641. break;
  6642. }
  6643. }
  6644. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6645. }
  6646. };
  6647. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6648. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6649. var value = texture.anisotropicFilteringLevel;
  6650. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6651. value = 1;
  6652. }
  6653. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6654. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6655. texture._cachedAnisotropicFilteringLevel = value;
  6656. }
  6657. };
  6658. Engine.prototype.readPixels = function (x, y, width, height) {
  6659. var data = new Uint8Array(height * width * 4);
  6660. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6661. return data;
  6662. };
  6663. Engine.prototype.releaseInternalTexture = function (texture) {
  6664. if (!texture) {
  6665. return;
  6666. }
  6667. texture.references--;
  6668. // Final reference ?
  6669. if (texture.references === 0) {
  6670. var texturesCache = this.getLoadedTexturesCache();
  6671. var index = texturesCache.indexOf(texture);
  6672. if (index > -1) {
  6673. texturesCache.splice(index, 1);
  6674. }
  6675. this._releaseTexture(texture);
  6676. }
  6677. };
  6678. // Dispose
  6679. Engine.prototype.dispose = function () {
  6680. this.hideLoadingUI();
  6681. this.stopRenderLoop();
  6682. // Release scenes
  6683. while (this.scenes.length) {
  6684. this.scenes[0].dispose();
  6685. }
  6686. // Release audio engine
  6687. Engine.audioEngine.dispose();
  6688. // Release effects
  6689. for (var name in this._compiledEffects) {
  6690. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6691. }
  6692. // Unbind
  6693. for (var i in this._vertexAttribArrays) {
  6694. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6695. continue;
  6696. }
  6697. this._gl.disableVertexAttribArray(i);
  6698. }
  6699. this._gl = null;
  6700. // Events
  6701. window.removeEventListener("blur", this._onBlur);
  6702. window.removeEventListener("focus", this._onFocus);
  6703. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6704. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6705. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6706. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6707. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6708. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6709. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6710. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6711. };
  6712. // Loading screen
  6713. Engine.prototype.displayLoadingUI = function () {
  6714. this._loadingScreen.displayLoadingUI();
  6715. };
  6716. Engine.prototype.hideLoadingUI = function () {
  6717. this._loadingScreen.hideLoadingUI();
  6718. };
  6719. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6720. get: function () {
  6721. return this._loadingScreen;
  6722. },
  6723. set: function (loadingScreen) {
  6724. this._loadingScreen = loadingScreen;
  6725. },
  6726. enumerable: true,
  6727. configurable: true
  6728. });
  6729. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6730. set: function (text) {
  6731. this._loadingScreen.loadingUIText = text;
  6732. },
  6733. enumerable: true,
  6734. configurable: true
  6735. });
  6736. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6737. set: function (color) {
  6738. this._loadingScreen.loadingUIBackgroundColor = color;
  6739. },
  6740. enumerable: true,
  6741. configurable: true
  6742. });
  6743. // FPS
  6744. Engine.prototype.getFps = function () {
  6745. return this.fps;
  6746. };
  6747. Engine.prototype.getDeltaTime = function () {
  6748. return this.deltaTime;
  6749. };
  6750. Engine.prototype._measureFps = function () {
  6751. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6752. var length = this.previousFramesDuration.length;
  6753. if (length >= 2) {
  6754. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6755. }
  6756. if (length >= this.fpsRange) {
  6757. if (length > this.fpsRange) {
  6758. this.previousFramesDuration.splice(0, 1);
  6759. length = this.previousFramesDuration.length;
  6760. }
  6761. var sum = 0;
  6762. for (var id = 0; id < length - 1; id++) {
  6763. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6764. }
  6765. this.fps = 1000.0 / (sum / (length - 1));
  6766. }
  6767. };
  6768. // Statics
  6769. Engine.isSupported = function () {
  6770. try {
  6771. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6772. if (navigator.isCocoonJS) {
  6773. return true;
  6774. }
  6775. var tempcanvas = document.createElement("canvas");
  6776. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6777. return gl != null && !!window.WebGLRenderingContext;
  6778. }
  6779. catch (e) {
  6780. return false;
  6781. }
  6782. };
  6783. // Const statics
  6784. Engine._ALPHA_DISABLE = 0;
  6785. Engine._ALPHA_ADD = 1;
  6786. Engine._ALPHA_COMBINE = 2;
  6787. Engine._ALPHA_SUBTRACT = 3;
  6788. Engine._ALPHA_MULTIPLY = 4;
  6789. Engine._ALPHA_MAXIMIZED = 5;
  6790. Engine._ALPHA_ONEONE = 6;
  6791. Engine._DELAYLOADSTATE_NONE = 0;
  6792. Engine._DELAYLOADSTATE_LOADED = 1;
  6793. Engine._DELAYLOADSTATE_LOADING = 2;
  6794. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6795. Engine._TEXTUREFORMAT_ALPHA = 0;
  6796. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6797. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6798. Engine._TEXTUREFORMAT_RGB = 4;
  6799. Engine._TEXTUREFORMAT_RGBA = 5;
  6800. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6801. Engine._TEXTURETYPE_FLOAT = 1;
  6802. // Updatable statics so stick with vars here
  6803. Engine.Epsilon = 0.001;
  6804. Engine.CollisionsEpsilon = 0.001;
  6805. Engine.CodeRepository = "src/";
  6806. Engine.ShadersRepository = "src/Shaders/";
  6807. return Engine;
  6808. })();
  6809. BABYLON.Engine = Engine;
  6810. })(BABYLON || (BABYLON = {}));
  6811. var BABYLON;
  6812. (function (BABYLON) {
  6813. /**
  6814. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6815. */
  6816. var Node = (function () {
  6817. /**
  6818. * @constructor
  6819. * @param {string} name - the name and id to be given to this node
  6820. * @param {BABYLON.Scene} the scene this node will be added to
  6821. */
  6822. function Node(name, scene) {
  6823. this.state = "";
  6824. this.animations = new Array();
  6825. this._childrenFlag = -1;
  6826. this._isEnabled = true;
  6827. this._isReady = true;
  6828. this._currentRenderId = -1;
  6829. this._parentRenderId = -1;
  6830. this.name = name;
  6831. this.id = name;
  6832. this._scene = scene;
  6833. this._initCache();
  6834. }
  6835. Node.prototype.getScene = function () {
  6836. return this._scene;
  6837. };
  6838. Node.prototype.getEngine = function () {
  6839. return this._scene.getEngine();
  6840. };
  6841. // override it in derived class
  6842. Node.prototype.getWorldMatrix = function () {
  6843. return BABYLON.Matrix.Identity();
  6844. };
  6845. // override it in derived class if you add new variables to the cache
  6846. // and call the parent class method
  6847. Node.prototype._initCache = function () {
  6848. this._cache = {};
  6849. this._cache.parent = undefined;
  6850. };
  6851. Node.prototype.updateCache = function (force) {
  6852. if (!force && this.isSynchronized())
  6853. return;
  6854. this._cache.parent = this.parent;
  6855. this._updateCache();
  6856. };
  6857. // override it in derived class if you add new variables to the cache
  6858. // and call the parent class method if !ignoreParentClass
  6859. Node.prototype._updateCache = function (ignoreParentClass) {
  6860. };
  6861. // override it in derived class if you add new variables to the cache
  6862. Node.prototype._isSynchronized = function () {
  6863. return true;
  6864. };
  6865. Node.prototype._markSyncedWithParent = function () {
  6866. this._parentRenderId = this.parent._currentRenderId;
  6867. };
  6868. Node.prototype.isSynchronizedWithParent = function () {
  6869. if (!this.parent) {
  6870. return true;
  6871. }
  6872. if (this._parentRenderId !== this.parent._currentRenderId) {
  6873. return false;
  6874. }
  6875. return this.parent.isSynchronized();
  6876. };
  6877. Node.prototype.isSynchronized = function (updateCache) {
  6878. var check = this.hasNewParent();
  6879. check = check || !this.isSynchronizedWithParent();
  6880. check = check || !this._isSynchronized();
  6881. if (updateCache)
  6882. this.updateCache(true);
  6883. return !check;
  6884. };
  6885. Node.prototype.hasNewParent = function (update) {
  6886. if (this._cache.parent === this.parent)
  6887. return false;
  6888. if (update)
  6889. this._cache.parent = this.parent;
  6890. return true;
  6891. };
  6892. /**
  6893. * Is this node ready to be used/rendered
  6894. * @return {boolean} is it ready
  6895. */
  6896. Node.prototype.isReady = function () {
  6897. return this._isReady;
  6898. };
  6899. /**
  6900. * Is this node enabled.
  6901. * If the node has a parent and is enabled, the parent will be inspected as well.
  6902. * @return {boolean} whether this node (and its parent) is enabled.
  6903. * @see setEnabled
  6904. */
  6905. Node.prototype.isEnabled = function () {
  6906. if (!this._isEnabled) {
  6907. return false;
  6908. }
  6909. if (this.parent) {
  6910. return this.parent.isEnabled();
  6911. }
  6912. return true;
  6913. };
  6914. /**
  6915. * Set the enabled state of this node.
  6916. * @param {boolean} value - the new enabled state
  6917. * @see isEnabled
  6918. */
  6919. Node.prototype.setEnabled = function (value) {
  6920. this._isEnabled = value;
  6921. };
  6922. /**
  6923. * Is this node a descendant of the given node.
  6924. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6925. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6926. * @see parent
  6927. */
  6928. Node.prototype.isDescendantOf = function (ancestor) {
  6929. if (this.parent) {
  6930. if (this.parent === ancestor) {
  6931. return true;
  6932. }
  6933. return this.parent.isDescendantOf(ancestor);
  6934. }
  6935. return false;
  6936. };
  6937. Node.prototype._getDescendants = function (list, results) {
  6938. for (var index = 0; index < list.length; index++) {
  6939. var item = list[index];
  6940. if (item.isDescendantOf(this)) {
  6941. results.push(item);
  6942. }
  6943. }
  6944. };
  6945. /**
  6946. * Will return all nodes that have this node as parent.
  6947. * @return {BABYLON.Node[]} all children nodes of all types.
  6948. */
  6949. Node.prototype.getDescendants = function () {
  6950. var results = [];
  6951. this._getDescendants(this._scene.meshes, results);
  6952. this._getDescendants(this._scene.lights, results);
  6953. this._getDescendants(this._scene.cameras, results);
  6954. return results;
  6955. };
  6956. Node.prototype._setReady = function (state) {
  6957. if (state === this._isReady) {
  6958. return;
  6959. }
  6960. if (!state) {
  6961. this._isReady = false;
  6962. return;
  6963. }
  6964. this._isReady = true;
  6965. if (this.onReady) {
  6966. this.onReady(this);
  6967. }
  6968. };
  6969. Node.prototype.getAnimationByName = function (name) {
  6970. for (var i = 0; i < this.animations.length; i++) {
  6971. var animation = this.animations[i];
  6972. if (animation.name === name) {
  6973. return animation;
  6974. }
  6975. }
  6976. return null;
  6977. };
  6978. return Node;
  6979. })();
  6980. BABYLON.Node = Node;
  6981. })(BABYLON || (BABYLON = {}));
  6982. var BABYLON;
  6983. (function (BABYLON) {
  6984. var FilesInput = (function () {
  6985. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6986. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6987. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6988. this._engine = p_engine;
  6989. this._canvas = p_canvas;
  6990. this._currentScene = p_scene;
  6991. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6992. this._progressCallback = p_progressCallback;
  6993. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6994. this._textureLoadingCallback = p_textureLoadingCallback;
  6995. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6996. }
  6997. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6998. var _this = this;
  6999. if (p_elementToMonitor) {
  7000. this._elementToMonitor = p_elementToMonitor;
  7001. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7002. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7003. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7004. }
  7005. };
  7006. FilesInput.prototype.renderFunction = function () {
  7007. if (this._additionnalRenderLoopLogicCallback) {
  7008. this._additionnalRenderLoopLogicCallback();
  7009. }
  7010. if (this._currentScene) {
  7011. if (this._textureLoadingCallback) {
  7012. var remaining = this._currentScene.getWaitingItemsCount();
  7013. if (remaining > 0) {
  7014. this._textureLoadingCallback(remaining);
  7015. }
  7016. }
  7017. this._currentScene.render();
  7018. }
  7019. };
  7020. FilesInput.prototype.drag = function (e) {
  7021. e.stopPropagation();
  7022. e.preventDefault();
  7023. };
  7024. FilesInput.prototype.drop = function (eventDrop) {
  7025. eventDrop.stopPropagation();
  7026. eventDrop.preventDefault();
  7027. this.loadFiles(eventDrop);
  7028. };
  7029. FilesInput.prototype.loadFiles = function (event) {
  7030. if (this._startingProcessingFilesCallback)
  7031. this._startingProcessingFilesCallback();
  7032. // Handling data transfer via drag'n'drop
  7033. if (event && event.dataTransfer && event.dataTransfer.files) {
  7034. this._filesToLoad = event.dataTransfer.files;
  7035. }
  7036. // Handling files from input files
  7037. if (event && event.target && event.target.files) {
  7038. this._filesToLoad = event.target.files;
  7039. }
  7040. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7041. for (var i = 0; i < this._filesToLoad.length; i++) {
  7042. switch (this._filesToLoad[i].type) {
  7043. case "image/jpeg":
  7044. case "image/png":
  7045. case "image/bmp":
  7046. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7047. break;
  7048. case "image/targa":
  7049. case "image/vnd.ms-dds":
  7050. case "audio/wav":
  7051. case "audio/x-wav":
  7052. case "audio/mp3":
  7053. case "audio/mpeg":
  7054. case "audio/mpeg3":
  7055. case "audio/x-mpeg-3":
  7056. case "audio/ogg":
  7057. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7058. break;
  7059. default:
  7060. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7061. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7062. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7063. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7064. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7065. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7066. this._sceneFileToLoad = this._filesToLoad[i];
  7067. }
  7068. break;
  7069. }
  7070. }
  7071. this.reload();
  7072. }
  7073. };
  7074. FilesInput.prototype.reload = function () {
  7075. var _this = this;
  7076. var that = this;
  7077. // If a ".babylon" file has been provided
  7078. if (this._sceneFileToLoad) {
  7079. if (this._currentScene) {
  7080. if (BABYLON.Tools.errorsCount > 0) {
  7081. BABYLON.Tools.ClearLogCache();
  7082. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7083. }
  7084. this._engine.stopRenderLoop();
  7085. this._currentScene.dispose();
  7086. }
  7087. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7088. that._currentScene = newScene;
  7089. // Wait for textures and shaders to be ready
  7090. that._currentScene.executeWhenReady(function () {
  7091. // Attach camera to canvas inputs
  7092. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7093. that._currentScene.createDefaultCameraOrLight();
  7094. }
  7095. that._currentScene.activeCamera.attachControl(that._canvas);
  7096. if (that._sceneLoadedCallback) {
  7097. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7098. }
  7099. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7100. });
  7101. }, function (progress) {
  7102. if (_this._progressCallback) {
  7103. _this._progressCallback(progress);
  7104. }
  7105. });
  7106. }
  7107. else {
  7108. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7109. }
  7110. };
  7111. FilesInput.FilesTextures = new Array();
  7112. FilesInput.FilesToLoad = new Array();
  7113. return FilesInput;
  7114. })();
  7115. BABYLON.FilesInput = FilesInput;
  7116. })(BABYLON || (BABYLON = {}));
  7117. var BABYLON;
  7118. (function (BABYLON) {
  7119. var IntersectionInfo = (function () {
  7120. function IntersectionInfo(bu, bv, distance) {
  7121. this.bu = bu;
  7122. this.bv = bv;
  7123. this.distance = distance;
  7124. this.faceId = 0;
  7125. this.subMeshId = 0;
  7126. }
  7127. return IntersectionInfo;
  7128. })();
  7129. BABYLON.IntersectionInfo = IntersectionInfo;
  7130. var PickingInfo = (function () {
  7131. function PickingInfo() {
  7132. this.hit = false;
  7133. this.distance = 0;
  7134. this.pickedPoint = null;
  7135. this.pickedMesh = null;
  7136. this.bu = 0;
  7137. this.bv = 0;
  7138. this.faceId = -1;
  7139. this.subMeshId = 0;
  7140. this.pickedSprite = null;
  7141. }
  7142. // Methods
  7143. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7144. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7145. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7146. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7147. return null;
  7148. }
  7149. var indices = this.pickedMesh.getIndices();
  7150. var result;
  7151. if (useVerticesNormals) {
  7152. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7153. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7154. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7155. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7156. normal0 = normal0.scale(this.bu);
  7157. normal1 = normal1.scale(this.bv);
  7158. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7159. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7160. }
  7161. else {
  7162. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7163. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7164. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7165. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7166. var p1p2 = vertex1.subtract(vertex2);
  7167. var p3p2 = vertex3.subtract(vertex2);
  7168. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7169. }
  7170. if (useWorldCoordinates) {
  7171. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7172. }
  7173. return BABYLON.Vector3.Normalize(result);
  7174. };
  7175. PickingInfo.prototype.getTextureCoordinates = function () {
  7176. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7177. return null;
  7178. }
  7179. var indices = this.pickedMesh.getIndices();
  7180. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7181. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7182. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7183. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7184. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7185. uv1 = uv1.scale(this.bu);
  7186. uv2 = uv2.scale(this.bv);
  7187. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7188. };
  7189. return PickingInfo;
  7190. })();
  7191. BABYLON.PickingInfo = PickingInfo;
  7192. })(BABYLON || (BABYLON = {}));
  7193. var BABYLON;
  7194. (function (BABYLON) {
  7195. var BoundingSphere = (function () {
  7196. function BoundingSphere(minimum, maximum) {
  7197. this.minimum = minimum;
  7198. this.maximum = maximum;
  7199. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7200. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7201. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7202. this.radius = distance * 0.5;
  7203. this.centerWorld = BABYLON.Vector3.Zero();
  7204. this._update(BABYLON.Matrix.Identity());
  7205. }
  7206. // Methods
  7207. BoundingSphere.prototype._update = function (world) {
  7208. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7209. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7210. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7211. };
  7212. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7213. for (var i = 0; i < 6; i++) {
  7214. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7215. return false;
  7216. }
  7217. return true;
  7218. };
  7219. BoundingSphere.prototype.intersectsPoint = function (point) {
  7220. var x = this.centerWorld.x - point.x;
  7221. var y = this.centerWorld.y - point.y;
  7222. var z = this.centerWorld.z - point.z;
  7223. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7224. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7225. return false;
  7226. return true;
  7227. };
  7228. // Statics
  7229. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7230. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7231. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7232. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7233. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7234. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7235. return false;
  7236. return true;
  7237. };
  7238. return BoundingSphere;
  7239. })();
  7240. BABYLON.BoundingSphere = BoundingSphere;
  7241. })(BABYLON || (BABYLON = {}));
  7242. var BABYLON;
  7243. (function (BABYLON) {
  7244. var BoundingBox = (function () {
  7245. function BoundingBox(minimum, maximum) {
  7246. this.minimum = minimum;
  7247. this.maximum = maximum;
  7248. this.vectors = new Array();
  7249. this.vectorsWorld = new Array();
  7250. // Bounding vectors
  7251. this.vectors.push(this.minimum.clone());
  7252. this.vectors.push(this.maximum.clone());
  7253. this.vectors.push(this.minimum.clone());
  7254. this.vectors[2].x = this.maximum.x;
  7255. this.vectors.push(this.minimum.clone());
  7256. this.vectors[3].y = this.maximum.y;
  7257. this.vectors.push(this.minimum.clone());
  7258. this.vectors[4].z = this.maximum.z;
  7259. this.vectors.push(this.maximum.clone());
  7260. this.vectors[5].z = this.minimum.z;
  7261. this.vectors.push(this.maximum.clone());
  7262. this.vectors[6].x = this.minimum.x;
  7263. this.vectors.push(this.maximum.clone());
  7264. this.vectors[7].y = this.minimum.y;
  7265. // OBB
  7266. this.center = this.maximum.add(this.minimum).scale(0.5);
  7267. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7268. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7269. // World
  7270. for (var index = 0; index < this.vectors.length; index++) {
  7271. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7272. }
  7273. this.minimumWorld = BABYLON.Vector3.Zero();
  7274. this.maximumWorld = BABYLON.Vector3.Zero();
  7275. this._update(BABYLON.Matrix.Identity());
  7276. }
  7277. // Methods
  7278. BoundingBox.prototype.getWorldMatrix = function () {
  7279. return this._worldMatrix;
  7280. };
  7281. BoundingBox.prototype._update = function (world) {
  7282. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7283. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7284. for (var index = 0; index < this.vectors.length; index++) {
  7285. var v = this.vectorsWorld[index];
  7286. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7287. if (v.x < this.minimumWorld.x)
  7288. this.minimumWorld.x = v.x;
  7289. if (v.y < this.minimumWorld.y)
  7290. this.minimumWorld.y = v.y;
  7291. if (v.z < this.minimumWorld.z)
  7292. this.minimumWorld.z = v.z;
  7293. if (v.x > this.maximumWorld.x)
  7294. this.maximumWorld.x = v.x;
  7295. if (v.y > this.maximumWorld.y)
  7296. this.maximumWorld.y = v.y;
  7297. if (v.z > this.maximumWorld.z)
  7298. this.maximumWorld.z = v.z;
  7299. }
  7300. // OBB
  7301. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7302. this.center.scaleInPlace(0.5);
  7303. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7304. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7305. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7306. this._worldMatrix = world;
  7307. };
  7308. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7309. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7310. };
  7311. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7312. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7313. };
  7314. BoundingBox.prototype.intersectsPoint = function (point) {
  7315. var delta = -BABYLON.Engine.Epsilon;
  7316. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7317. return false;
  7318. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7319. return false;
  7320. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7321. return false;
  7322. return true;
  7323. };
  7324. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7325. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7326. };
  7327. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7328. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7329. return false;
  7330. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7331. return false;
  7332. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7333. return false;
  7334. return true;
  7335. };
  7336. // Statics
  7337. BoundingBox.Intersects = function (box0, box1) {
  7338. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7339. return false;
  7340. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7341. return false;
  7342. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7343. return false;
  7344. return true;
  7345. };
  7346. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7347. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7348. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7349. return (num <= (sphereRadius * sphereRadius));
  7350. };
  7351. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7352. for (var p = 0; p < 6; p++) {
  7353. for (var i = 0; i < 8; i++) {
  7354. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7355. return false;
  7356. }
  7357. }
  7358. }
  7359. return true;
  7360. };
  7361. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7362. for (var p = 0; p < 6; p++) {
  7363. var inCount = 8;
  7364. for (var i = 0; i < 8; i++) {
  7365. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7366. --inCount;
  7367. }
  7368. else {
  7369. break;
  7370. }
  7371. }
  7372. if (inCount === 0)
  7373. return false;
  7374. }
  7375. return true;
  7376. };
  7377. return BoundingBox;
  7378. })();
  7379. BABYLON.BoundingBox = BoundingBox;
  7380. })(BABYLON || (BABYLON = {}));
  7381. var BABYLON;
  7382. (function (BABYLON) {
  7383. var computeBoxExtents = function (axis, box) {
  7384. var p = BABYLON.Vector3.Dot(box.center, axis);
  7385. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7386. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7387. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7388. var r = r0 + r1 + r2;
  7389. return {
  7390. min: p - r,
  7391. max: p + r
  7392. };
  7393. };
  7394. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7395. var axisOverlap = function (axis, box0, box1) {
  7396. var result0 = computeBoxExtents(axis, box0);
  7397. var result1 = computeBoxExtents(axis, box1);
  7398. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7399. };
  7400. var BoundingInfo = (function () {
  7401. function BoundingInfo(minimum, maximum) {
  7402. this.minimum = minimum;
  7403. this.maximum = maximum;
  7404. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7405. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7406. }
  7407. // Methods
  7408. BoundingInfo.prototype._update = function (world) {
  7409. this.boundingBox._update(world);
  7410. this.boundingSphere._update(world);
  7411. };
  7412. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7413. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7414. return false;
  7415. return this.boundingBox.isInFrustum(frustumPlanes);
  7416. };
  7417. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7418. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7419. };
  7420. BoundingInfo.prototype._checkCollision = function (collider) {
  7421. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7422. };
  7423. BoundingInfo.prototype.intersectsPoint = function (point) {
  7424. if (!this.boundingSphere.centerWorld) {
  7425. return false;
  7426. }
  7427. if (!this.boundingSphere.intersectsPoint(point)) {
  7428. return false;
  7429. }
  7430. if (!this.boundingBox.intersectsPoint(point)) {
  7431. return false;
  7432. }
  7433. return true;
  7434. };
  7435. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7436. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7437. return false;
  7438. }
  7439. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7440. return false;
  7441. }
  7442. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7443. return false;
  7444. }
  7445. if (!precise) {
  7446. return true;
  7447. }
  7448. var box0 = this.boundingBox;
  7449. var box1 = boundingInfo.boundingBox;
  7450. if (!axisOverlap(box0.directions[0], box0, box1))
  7451. return false;
  7452. if (!axisOverlap(box0.directions[1], box0, box1))
  7453. return false;
  7454. if (!axisOverlap(box0.directions[2], box0, box1))
  7455. return false;
  7456. if (!axisOverlap(box1.directions[0], box0, box1))
  7457. return false;
  7458. if (!axisOverlap(box1.directions[1], box0, box1))
  7459. return false;
  7460. if (!axisOverlap(box1.directions[2], box0, box1))
  7461. return false;
  7462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7463. return false;
  7464. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7465. return false;
  7466. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7467. return false;
  7468. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7469. return false;
  7470. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7471. return false;
  7472. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7473. return false;
  7474. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7475. return false;
  7476. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7477. return false;
  7478. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7479. return false;
  7480. return true;
  7481. };
  7482. return BoundingInfo;
  7483. })();
  7484. BABYLON.BoundingInfo = BoundingInfo;
  7485. })(BABYLON || (BABYLON = {}));
  7486. var BABYLON;
  7487. (function (BABYLON) {
  7488. var AbstractMesh = (function (_super) {
  7489. __extends(AbstractMesh, _super);
  7490. function AbstractMesh(name, scene) {
  7491. var _this = this;
  7492. _super.call(this, name, scene);
  7493. // Properties
  7494. this.definedFacingForward = true; // orientation for POV movement & rotation
  7495. this.position = new BABYLON.Vector3(0, 0, 0);
  7496. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7497. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7498. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7499. this.visibility = 1.0;
  7500. this.alphaIndex = Number.MAX_VALUE;
  7501. this.infiniteDistance = false;
  7502. this.isVisible = true;
  7503. this.isPickable = true;
  7504. this.showBoundingBox = false;
  7505. this.showSubMeshesBoundingBox = false;
  7506. this.onDispose = null;
  7507. this.isBlocker = false;
  7508. this.renderingGroupId = 0;
  7509. this.receiveShadows = false;
  7510. this.renderOutline = false;
  7511. this.outlineColor = BABYLON.Color3.Red();
  7512. this.outlineWidth = 0.02;
  7513. this.renderOverlay = false;
  7514. this.overlayColor = BABYLON.Color3.Red();
  7515. this.overlayAlpha = 0.5;
  7516. this.hasVertexAlpha = false;
  7517. this.useVertexColors = true;
  7518. this.applyFog = true;
  7519. this.computeBonesUsingShaders = true;
  7520. this.scalingDeterminant = 1;
  7521. this.numBoneInfluencers = 4;
  7522. this.useOctreeForRenderingSelection = true;
  7523. this.useOctreeForPicking = true;
  7524. this.useOctreeForCollisions = true;
  7525. this.layerMask = 0x0FFFFFFF;
  7526. this.alwaysSelectAsActiveMesh = false;
  7527. // Physics
  7528. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7529. // Collisions
  7530. this._checkCollisions = false;
  7531. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7532. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7533. this._collider = new BABYLON.Collider();
  7534. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7535. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7536. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7537. // Edges
  7538. this.edgesWidth = 1;
  7539. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7540. // Cache
  7541. this._localScaling = BABYLON.Matrix.Zero();
  7542. this._localRotation = BABYLON.Matrix.Zero();
  7543. this._localTranslation = BABYLON.Matrix.Zero();
  7544. this._localBillboard = BABYLON.Matrix.Zero();
  7545. this._localPivotScaling = BABYLON.Matrix.Zero();
  7546. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7547. this._localWorld = BABYLON.Matrix.Zero();
  7548. this._worldMatrix = BABYLON.Matrix.Zero();
  7549. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7550. this._absolutePosition = BABYLON.Vector3.Zero();
  7551. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7552. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7553. this._isDirty = false;
  7554. this._pivotMatrix = BABYLON.Matrix.Identity();
  7555. this._isDisposed = false;
  7556. this._renderId = 0;
  7557. this._intersectionsInProgress = new Array();
  7558. this._onAfterWorldMatrixUpdate = new Array();
  7559. this._isWorldMatrixFrozen = false;
  7560. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7561. if (collidedMesh === void 0) { collidedMesh = null; }
  7562. //TODO move this to the collision coordinator!
  7563. if (_this.getScene().workerCollisions)
  7564. newPosition.multiplyInPlace(_this._collider.radius);
  7565. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7566. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7567. _this.position.addInPlace(_this._diffPositionForCollisions);
  7568. }
  7569. if (_this.onCollide && collidedMesh) {
  7570. _this.onCollide(collidedMesh);
  7571. }
  7572. if (_this.onCollisionPositionChange) {
  7573. _this.onCollisionPositionChange(_this.position);
  7574. }
  7575. };
  7576. scene.addMesh(this);
  7577. }
  7578. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7579. get: function () {
  7580. return AbstractMesh._BILLBOARDMODE_NONE;
  7581. },
  7582. enumerable: true,
  7583. configurable: true
  7584. });
  7585. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7586. get: function () {
  7587. return AbstractMesh._BILLBOARDMODE_X;
  7588. },
  7589. enumerable: true,
  7590. configurable: true
  7591. });
  7592. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7593. get: function () {
  7594. return AbstractMesh._BILLBOARDMODE_Y;
  7595. },
  7596. enumerable: true,
  7597. configurable: true
  7598. });
  7599. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7600. get: function () {
  7601. return AbstractMesh._BILLBOARDMODE_Z;
  7602. },
  7603. enumerable: true,
  7604. configurable: true
  7605. });
  7606. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7607. get: function () {
  7608. return AbstractMesh._BILLBOARDMODE_ALL;
  7609. },
  7610. enumerable: true,
  7611. configurable: true
  7612. });
  7613. // Methods
  7614. AbstractMesh.prototype.disableEdgesRendering = function () {
  7615. if (this._edgesRenderer !== undefined) {
  7616. this._edgesRenderer.dispose();
  7617. this._edgesRenderer = undefined;
  7618. }
  7619. };
  7620. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7621. if (epsilon === void 0) { epsilon = 0.95; }
  7622. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7623. this.disableEdgesRendering();
  7624. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7625. };
  7626. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7627. get: function () {
  7628. return false;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. AbstractMesh.prototype.getLOD = function (camera) {
  7634. return this;
  7635. };
  7636. AbstractMesh.prototype.getTotalVertices = function () {
  7637. return 0;
  7638. };
  7639. AbstractMesh.prototype.getIndices = function () {
  7640. return null;
  7641. };
  7642. AbstractMesh.prototype.getVerticesData = function (kind) {
  7643. return null;
  7644. };
  7645. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7646. return false;
  7647. };
  7648. AbstractMesh.prototype.getBoundingInfo = function () {
  7649. if (this._masterMesh) {
  7650. return this._masterMesh.getBoundingInfo();
  7651. }
  7652. if (!this._boundingInfo) {
  7653. this._updateBoundingInfo();
  7654. }
  7655. return this._boundingInfo;
  7656. };
  7657. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7658. get: function () {
  7659. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. AbstractMesh.prototype._preActivate = function () {
  7665. };
  7666. AbstractMesh.prototype._activate = function (renderId) {
  7667. this._renderId = renderId;
  7668. };
  7669. AbstractMesh.prototype.getWorldMatrix = function () {
  7670. if (this._masterMesh) {
  7671. return this._masterMesh.getWorldMatrix();
  7672. }
  7673. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7674. this.computeWorldMatrix();
  7675. }
  7676. return this._worldMatrix;
  7677. };
  7678. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7679. get: function () {
  7680. return this._worldMatrix;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7686. get: function () {
  7687. return this._absolutePosition;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7693. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7694. this.computeWorldMatrix(true);
  7695. this._isWorldMatrixFrozen = true;
  7696. };
  7697. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7698. this._isWorldMatrixFrozen = false;
  7699. this.computeWorldMatrix(true);
  7700. };
  7701. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7702. get: function () {
  7703. return this._isWorldMatrixFrozen;
  7704. },
  7705. enumerable: true,
  7706. configurable: true
  7707. });
  7708. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7709. axis.normalize();
  7710. if (!this.rotationQuaternion) {
  7711. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7712. this.rotation = BABYLON.Vector3.Zero();
  7713. }
  7714. var rotationQuaternion;
  7715. if (!space || space === BABYLON.Space.LOCAL) {
  7716. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7717. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7718. }
  7719. else {
  7720. if (this.parent) {
  7721. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7722. invertParentWorldMatrix.invert();
  7723. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7724. }
  7725. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7726. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7727. }
  7728. };
  7729. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7730. var displacementVector = axis.scale(distance);
  7731. if (!space || space === BABYLON.Space.LOCAL) {
  7732. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7733. this.setPositionWithLocalVector(tempV3);
  7734. }
  7735. else {
  7736. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7737. }
  7738. };
  7739. AbstractMesh.prototype.getAbsolutePosition = function () {
  7740. this.computeWorldMatrix();
  7741. return this._absolutePosition;
  7742. };
  7743. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7744. if (!absolutePosition) {
  7745. return;
  7746. }
  7747. var absolutePositionX;
  7748. var absolutePositionY;
  7749. var absolutePositionZ;
  7750. if (absolutePosition.x === undefined) {
  7751. if (arguments.length < 3) {
  7752. return;
  7753. }
  7754. absolutePositionX = arguments[0];
  7755. absolutePositionY = arguments[1];
  7756. absolutePositionZ = arguments[2];
  7757. }
  7758. else {
  7759. absolutePositionX = absolutePosition.x;
  7760. absolutePositionY = absolutePosition.y;
  7761. absolutePositionZ = absolutePosition.z;
  7762. }
  7763. if (this.parent) {
  7764. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7765. invertParentWorldMatrix.invert();
  7766. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7767. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7768. }
  7769. else {
  7770. this.position.x = absolutePositionX;
  7771. this.position.y = absolutePositionY;
  7772. this.position.z = absolutePositionZ;
  7773. }
  7774. };
  7775. // ================================== Point of View Movement =================================
  7776. /**
  7777. * Perform relative position change from the point of view of behind the front of the mesh.
  7778. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7779. * Supports definition of mesh facing forward or backward.
  7780. * @param {number} amountRight
  7781. * @param {number} amountUp
  7782. * @param {number} amountForward
  7783. */
  7784. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7785. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7786. };
  7787. /**
  7788. * Calculate relative position change from the point of view of behind the front of the mesh.
  7789. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7790. * Supports definition of mesh facing forward or backward.
  7791. * @param {number} amountRight
  7792. * @param {number} amountUp
  7793. * @param {number} amountForward
  7794. */
  7795. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7796. var rotMatrix = new BABYLON.Matrix();
  7797. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7798. rotQuaternion.toRotationMatrix(rotMatrix);
  7799. var translationDelta = BABYLON.Vector3.Zero();
  7800. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7802. return translationDelta;
  7803. };
  7804. // ================================== Point of View Rotation =================================
  7805. /**
  7806. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7807. * Supports definition of mesh facing forward or backward.
  7808. * @param {number} flipBack
  7809. * @param {number} twirlClockwise
  7810. * @param {number} tiltRight
  7811. */
  7812. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7813. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7814. };
  7815. /**
  7816. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7817. * Supports definition of mesh facing forward or backward.
  7818. * @param {number} flipBack
  7819. * @param {number} twirlClockwise
  7820. * @param {number} tiltRight
  7821. */
  7822. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7823. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7824. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7825. };
  7826. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7827. this._pivotMatrix = matrix;
  7828. this._cache.pivotMatrixUpdated = true;
  7829. };
  7830. AbstractMesh.prototype.getPivotMatrix = function () {
  7831. return this._pivotMatrix;
  7832. };
  7833. AbstractMesh.prototype._isSynchronized = function () {
  7834. if (this._isDirty) {
  7835. return false;
  7836. }
  7837. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7838. return false;
  7839. if (this._cache.pivotMatrixUpdated) {
  7840. return false;
  7841. }
  7842. if (this.infiniteDistance) {
  7843. return false;
  7844. }
  7845. if (!this._cache.position.equals(this.position))
  7846. return false;
  7847. if (this.rotationQuaternion) {
  7848. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7849. return false;
  7850. }
  7851. else {
  7852. if (!this._cache.rotation.equals(this.rotation))
  7853. return false;
  7854. }
  7855. if (!this._cache.scaling.equals(this.scaling))
  7856. return false;
  7857. return true;
  7858. };
  7859. AbstractMesh.prototype._initCache = function () {
  7860. _super.prototype._initCache.call(this);
  7861. this._cache.localMatrixUpdated = false;
  7862. this._cache.position = BABYLON.Vector3.Zero();
  7863. this._cache.scaling = BABYLON.Vector3.Zero();
  7864. this._cache.rotation = BABYLON.Vector3.Zero();
  7865. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7866. this._cache.billboardMode = -1;
  7867. };
  7868. AbstractMesh.prototype.markAsDirty = function (property) {
  7869. if (property === "rotation") {
  7870. this.rotationQuaternion = null;
  7871. }
  7872. this._currentRenderId = Number.MAX_VALUE;
  7873. this._isDirty = true;
  7874. };
  7875. AbstractMesh.prototype._updateBoundingInfo = function () {
  7876. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7877. this._boundingInfo._update(this.worldMatrixFromCache);
  7878. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7879. };
  7880. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7881. if (!this.subMeshes) {
  7882. return;
  7883. }
  7884. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7885. var subMesh = this.subMeshes[subIndex];
  7886. subMesh.updateBoundingInfo(matrix);
  7887. }
  7888. };
  7889. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7890. if (this._isWorldMatrixFrozen) {
  7891. return this._worldMatrix;
  7892. }
  7893. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7894. return this._worldMatrix;
  7895. }
  7896. this._cache.position.copyFrom(this.position);
  7897. this._cache.scaling.copyFrom(this.scaling);
  7898. this._cache.pivotMatrixUpdated = false;
  7899. this._cache.billboardMode = this.billboardMode;
  7900. this._currentRenderId = this.getScene().getRenderId();
  7901. this._isDirty = false;
  7902. // Scaling
  7903. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7904. // Rotation
  7905. if (this.rotationQuaternion) {
  7906. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7907. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7908. }
  7909. else {
  7910. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7911. this._cache.rotation.copyFrom(this.rotation);
  7912. }
  7913. // Translation
  7914. if (this.infiniteDistance && !this.parent) {
  7915. var camera = this.getScene().activeCamera;
  7916. if (camera) {
  7917. var cameraWorldMatrix = camera.getWorldMatrix();
  7918. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7919. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7920. }
  7921. }
  7922. else {
  7923. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7924. }
  7925. // Composing transformations
  7926. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7927. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7928. // Billboarding
  7929. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7930. var localPosition = this.position.clone();
  7931. var zero = this.getScene().activeCamera.globalPosition.clone();
  7932. if (this.parent && this.parent.position) {
  7933. localPosition.addInPlace(this.parent.position);
  7934. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7935. }
  7936. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7937. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7938. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7939. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7940. zero.y = localPosition.y + 0.001;
  7941. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7942. zero.z = localPosition.z + 0.001;
  7943. }
  7944. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7945. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7946. this._localBillboard.invert();
  7947. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7948. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7949. }
  7950. // Local world
  7951. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7952. // Parent
  7953. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7954. this._markSyncedWithParent();
  7955. if (this._meshToBoneReferal) {
  7956. if (!this._localMeshReferalTransform) {
  7957. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7958. }
  7959. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7960. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7961. }
  7962. else {
  7963. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7964. }
  7965. }
  7966. else {
  7967. this._worldMatrix.copyFrom(this._localWorld);
  7968. }
  7969. // Bounding info
  7970. this._updateBoundingInfo();
  7971. // Absolute position
  7972. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7973. // Callbacks
  7974. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7975. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7976. }
  7977. return this._worldMatrix;
  7978. };
  7979. /**
  7980. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7981. * @param func: callback function to add
  7982. */
  7983. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7984. this._onAfterWorldMatrixUpdate.push(func);
  7985. };
  7986. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7987. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7988. if (index > -1) {
  7989. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7990. }
  7991. };
  7992. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7993. this.computeWorldMatrix();
  7994. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7995. };
  7996. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7997. this.computeWorldMatrix();
  7998. var invLocalWorldMatrix = this._localWorld.clone();
  7999. invLocalWorldMatrix.invert();
  8000. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8001. };
  8002. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8003. this.computeWorldMatrix(true);
  8004. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8005. };
  8006. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8007. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8008. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8009. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8010. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8011. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8012. /// <returns>Mesh oriented towards targetMesh</returns>
  8013. yawCor = yawCor || 0; // default to zero if undefined
  8014. pitchCor = pitchCor || 0;
  8015. rollCor = rollCor || 0;
  8016. var dv = targetPoint.subtract(this.position);
  8017. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8018. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8019. var pitch = Math.atan2(dv.y, len);
  8020. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8021. };
  8022. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8023. this._meshToBoneReferal = affectedMesh;
  8024. this.parent = bone;
  8025. if (bone.getWorldMatrix().determinant() < 0) {
  8026. this.scalingDeterminant *= -1;
  8027. }
  8028. };
  8029. AbstractMesh.prototype.detachFromBone = function () {
  8030. if (this.parent.getWorldMatrix().determinant() < 0) {
  8031. this.scalingDeterminant *= -1;
  8032. }
  8033. this._meshToBoneReferal = null;
  8034. this.parent = null;
  8035. };
  8036. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8037. return this._boundingInfo.isInFrustum(frustumPlanes);
  8038. };
  8039. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8040. if (!camera) {
  8041. camera = this.getScene().activeCamera;
  8042. }
  8043. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8044. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8045. return false;
  8046. }
  8047. return true;
  8048. };
  8049. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8050. if (!this._boundingInfo || !mesh._boundingInfo) {
  8051. return false;
  8052. }
  8053. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8054. };
  8055. AbstractMesh.prototype.intersectsPoint = function (point) {
  8056. if (!this._boundingInfo) {
  8057. return false;
  8058. }
  8059. return this._boundingInfo.intersectsPoint(point);
  8060. };
  8061. // Physics
  8062. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8063. var physicsEngine = this.getScene().getPhysicsEngine();
  8064. if (!physicsEngine) {
  8065. return null;
  8066. }
  8067. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8068. if (impostor.impostor) {
  8069. // Old API
  8070. options = impostor;
  8071. impostor = impostor.impostor;
  8072. }
  8073. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8074. physicsEngine._unregisterMesh(this);
  8075. return null;
  8076. }
  8077. if (!options) {
  8078. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8079. }
  8080. else {
  8081. if (!options.mass && options.mass !== 0)
  8082. options.mass = 0;
  8083. if (!options.friction && options.friction !== 0)
  8084. options.friction = 0.2;
  8085. if (!options.restitution && options.restitution !== 0)
  8086. options.restitution = 0.2;
  8087. }
  8088. this._physicImpostor = impostor;
  8089. this._physicsMass = options.mass;
  8090. this._physicsFriction = options.friction;
  8091. this._physicRestitution = options.restitution;
  8092. return physicsEngine._registerMesh(this, impostor, options);
  8093. };
  8094. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8095. if (!this._physicImpostor) {
  8096. return BABYLON.PhysicsEngine.NoImpostor;
  8097. }
  8098. return this._physicImpostor;
  8099. };
  8100. AbstractMesh.prototype.getPhysicsMass = function () {
  8101. if (!this._physicsMass) {
  8102. return 0;
  8103. }
  8104. return this._physicsMass;
  8105. };
  8106. AbstractMesh.prototype.getPhysicsFriction = function () {
  8107. if (!this._physicsFriction) {
  8108. return 0;
  8109. }
  8110. return this._physicsFriction;
  8111. };
  8112. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8113. if (!this._physicRestitution) {
  8114. return 0;
  8115. }
  8116. return this._physicRestitution;
  8117. };
  8118. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8119. if (!camera) {
  8120. camera = this.getScene().activeCamera;
  8121. }
  8122. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8123. };
  8124. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8125. if (!camera) {
  8126. camera = this.getScene().activeCamera;
  8127. }
  8128. return this.absolutePosition.subtract(camera.position).length();
  8129. };
  8130. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8131. if (!this._physicImpostor) {
  8132. return;
  8133. }
  8134. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8135. };
  8136. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8137. if (!this._physicImpostor) {
  8138. return;
  8139. }
  8140. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8141. };
  8142. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8143. if (!this._physicImpostor) {
  8144. return;
  8145. }
  8146. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8147. };
  8148. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8149. // Collisions
  8150. get: function () {
  8151. return this._checkCollisions;
  8152. },
  8153. set: function (collisionEnabled) {
  8154. this._checkCollisions = collisionEnabled;
  8155. if (this.getScene().workerCollisions) {
  8156. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8157. }
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8163. var globalPosition = this.getAbsolutePosition();
  8164. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8165. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8166. this._collider.radius = this.ellipsoid;
  8167. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8168. };
  8169. // Submeshes octree
  8170. /**
  8171. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8172. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8173. */
  8174. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8175. if (maxCapacity === void 0) { maxCapacity = 64; }
  8176. if (maxDepth === void 0) { maxDepth = 2; }
  8177. if (!this._submeshesOctree) {
  8178. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8179. }
  8180. this.computeWorldMatrix(true);
  8181. // Update octree
  8182. var bbox = this.getBoundingInfo().boundingBox;
  8183. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8184. return this._submeshesOctree;
  8185. };
  8186. // Collisions
  8187. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8188. this._generatePointsArray();
  8189. // Transformation
  8190. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8191. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8192. subMesh._lastColliderWorldVertices = [];
  8193. subMesh._trianglePlanes = [];
  8194. var start = subMesh.verticesStart;
  8195. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8196. for (var i = start; i < end; i++) {
  8197. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8198. }
  8199. }
  8200. // Collide
  8201. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8202. if (collider.collisionFound) {
  8203. collider.collidedMesh = this;
  8204. }
  8205. };
  8206. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8207. var subMeshes;
  8208. var len;
  8209. // Octrees
  8210. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8211. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8212. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8213. len = intersections.length;
  8214. subMeshes = intersections.data;
  8215. }
  8216. else {
  8217. subMeshes = this.subMeshes;
  8218. len = subMeshes.length;
  8219. }
  8220. for (var index = 0; index < len; index++) {
  8221. var subMesh = subMeshes[index];
  8222. // Bounding test
  8223. if (len > 1 && !subMesh._checkCollision(collider))
  8224. continue;
  8225. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8226. }
  8227. };
  8228. AbstractMesh.prototype._checkCollision = function (collider) {
  8229. // Bounding box test
  8230. if (!this._boundingInfo._checkCollision(collider))
  8231. return;
  8232. // Transformation matrix
  8233. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8234. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8235. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8236. };
  8237. // Picking
  8238. AbstractMesh.prototype._generatePointsArray = function () {
  8239. return false;
  8240. };
  8241. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8242. var pickingInfo = new BABYLON.PickingInfo();
  8243. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8244. return pickingInfo;
  8245. }
  8246. if (!this._generatePointsArray()) {
  8247. return pickingInfo;
  8248. }
  8249. var intersectInfo = null;
  8250. // Octrees
  8251. var subMeshes;
  8252. var len;
  8253. if (this._submeshesOctree && this.useOctreeForPicking) {
  8254. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8255. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8256. len = intersections.length;
  8257. subMeshes = intersections.data;
  8258. }
  8259. else {
  8260. subMeshes = this.subMeshes;
  8261. len = subMeshes.length;
  8262. }
  8263. for (var index = 0; index < len; index++) {
  8264. var subMesh = subMeshes[index];
  8265. // Bounding test
  8266. if (len > 1 && !subMesh.canIntersects(ray))
  8267. continue;
  8268. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8269. if (currentIntersectInfo) {
  8270. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8271. intersectInfo = currentIntersectInfo;
  8272. intersectInfo.subMeshId = index;
  8273. if (fastCheck) {
  8274. break;
  8275. }
  8276. }
  8277. }
  8278. }
  8279. if (intersectInfo) {
  8280. // Get picked point
  8281. var world = this.getWorldMatrix();
  8282. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8283. var direction = ray.direction.clone();
  8284. direction = direction.scale(intersectInfo.distance);
  8285. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8286. var pickedPoint = worldOrigin.add(worldDirection);
  8287. // Return result
  8288. pickingInfo.hit = true;
  8289. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8290. pickingInfo.pickedPoint = pickedPoint;
  8291. pickingInfo.pickedMesh = this;
  8292. pickingInfo.bu = intersectInfo.bu;
  8293. pickingInfo.bv = intersectInfo.bv;
  8294. pickingInfo.faceId = intersectInfo.faceId;
  8295. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8296. return pickingInfo;
  8297. }
  8298. return pickingInfo;
  8299. };
  8300. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8301. return null;
  8302. };
  8303. AbstractMesh.prototype.releaseSubMeshes = function () {
  8304. if (this.subMeshes) {
  8305. while (this.subMeshes.length) {
  8306. this.subMeshes[0].dispose();
  8307. }
  8308. }
  8309. else {
  8310. this.subMeshes = new Array();
  8311. }
  8312. };
  8313. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8314. var index;
  8315. // Animations
  8316. this.getScene().stopAnimation(this);
  8317. // Physics
  8318. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8319. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8320. }
  8321. // Intersections in progress
  8322. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8323. var other = this._intersectionsInProgress[index];
  8324. var pos = other._intersectionsInProgress.indexOf(this);
  8325. other._intersectionsInProgress.splice(pos, 1);
  8326. }
  8327. this._intersectionsInProgress = [];
  8328. // Edges
  8329. if (this._edgesRenderer) {
  8330. this._edgesRenderer.dispose();
  8331. this._edgesRenderer = null;
  8332. }
  8333. // SubMeshes
  8334. this.releaseSubMeshes();
  8335. // Remove from scene
  8336. this.getScene().removeMesh(this);
  8337. if (!doNotRecurse) {
  8338. // Particles
  8339. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8340. if (this.getScene().particleSystems[index].emitter === this) {
  8341. this.getScene().particleSystems[index].dispose();
  8342. index--;
  8343. }
  8344. }
  8345. // Children
  8346. var objects = this.getScene().meshes.slice(0);
  8347. for (index = 0; index < objects.length; index++) {
  8348. if (objects[index].parent === this) {
  8349. objects[index].dispose();
  8350. }
  8351. }
  8352. }
  8353. else {
  8354. for (index = 0; index < this.getScene().meshes.length; index++) {
  8355. var obj = this.getScene().meshes[index];
  8356. if (obj.parent === this) {
  8357. obj.parent = null;
  8358. obj.computeWorldMatrix(true);
  8359. }
  8360. }
  8361. }
  8362. this._onAfterWorldMatrixUpdate = [];
  8363. this._isDisposed = true;
  8364. // Callback
  8365. if (this.onDispose) {
  8366. this.onDispose();
  8367. }
  8368. };
  8369. // Statics
  8370. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8371. AbstractMesh._BILLBOARDMODE_X = 1;
  8372. AbstractMesh._BILLBOARDMODE_Y = 2;
  8373. AbstractMesh._BILLBOARDMODE_Z = 4;
  8374. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8375. return AbstractMesh;
  8376. })(BABYLON.Node);
  8377. BABYLON.AbstractMesh = AbstractMesh;
  8378. })(BABYLON || (BABYLON = {}));
  8379. var BABYLON;
  8380. (function (BABYLON) {
  8381. var Light = (function (_super) {
  8382. __extends(Light, _super);
  8383. function Light(name, scene) {
  8384. _super.call(this, name, scene);
  8385. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8386. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8387. this.intensity = 1.0;
  8388. this.range = Number.MAX_VALUE;
  8389. this.includeOnlyWithLayerMask = 0;
  8390. this.includedOnlyMeshes = new Array();
  8391. this.excludedMeshes = new Array();
  8392. this.excludeWithLayerMask = 0;
  8393. this._excludedMeshesIds = new Array();
  8394. this._includedOnlyMeshesIds = new Array();
  8395. scene.addLight(this);
  8396. }
  8397. Light.prototype.getShadowGenerator = function () {
  8398. return this._shadowGenerator;
  8399. };
  8400. Light.prototype.getAbsolutePosition = function () {
  8401. return BABYLON.Vector3.Zero();
  8402. };
  8403. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8404. };
  8405. Light.prototype._getWorldMatrix = function () {
  8406. return BABYLON.Matrix.Identity();
  8407. };
  8408. Light.prototype.canAffectMesh = function (mesh) {
  8409. if (!mesh) {
  8410. return true;
  8411. }
  8412. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8413. return false;
  8414. }
  8415. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8416. return false;
  8417. }
  8418. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8419. return false;
  8420. }
  8421. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8422. return false;
  8423. }
  8424. return true;
  8425. };
  8426. Light.prototype.getWorldMatrix = function () {
  8427. this._currentRenderId = this.getScene().getRenderId();
  8428. var worldMatrix = this._getWorldMatrix();
  8429. if (this.parent && this.parent.getWorldMatrix) {
  8430. if (!this._parentedWorldMatrix) {
  8431. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8432. }
  8433. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8434. this._markSyncedWithParent();
  8435. return this._parentedWorldMatrix;
  8436. }
  8437. return worldMatrix;
  8438. };
  8439. Light.prototype.dispose = function () {
  8440. if (this._shadowGenerator) {
  8441. this._shadowGenerator.dispose();
  8442. this._shadowGenerator = null;
  8443. }
  8444. // Animations
  8445. this.getScene().stopAnimation(this);
  8446. // Remove from scene
  8447. this.getScene().removeLight(this);
  8448. };
  8449. return Light;
  8450. })(BABYLON.Node);
  8451. BABYLON.Light = Light;
  8452. })(BABYLON || (BABYLON = {}));
  8453. var BABYLON;
  8454. (function (BABYLON) {
  8455. var PointLight = (function (_super) {
  8456. __extends(PointLight, _super);
  8457. function PointLight(name, position, scene) {
  8458. _super.call(this, name, scene);
  8459. this.position = position;
  8460. }
  8461. PointLight.prototype.getAbsolutePosition = function () {
  8462. return this.transformedPosition ? this.transformedPosition : this.position;
  8463. };
  8464. PointLight.prototype.computeTransformedPosition = function () {
  8465. if (this.parent && this.parent.getWorldMatrix) {
  8466. if (!this.transformedPosition) {
  8467. this.transformedPosition = BABYLON.Vector3.Zero();
  8468. }
  8469. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8470. return true;
  8471. }
  8472. return false;
  8473. };
  8474. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8475. if (this.parent && this.parent.getWorldMatrix) {
  8476. this.computeTransformedPosition();
  8477. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8478. return;
  8479. }
  8480. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8481. };
  8482. PointLight.prototype.needCube = function () {
  8483. return true;
  8484. };
  8485. PointLight.prototype.supportsVSM = function () {
  8486. return false;
  8487. };
  8488. PointLight.prototype.needRefreshPerFrame = function () {
  8489. return false;
  8490. };
  8491. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8492. switch (faceIndex) {
  8493. case 0:
  8494. return new BABYLON.Vector3(1, 0, 0);
  8495. case 1:
  8496. return new BABYLON.Vector3(-1, 0, 0);
  8497. case 2:
  8498. return new BABYLON.Vector3(0, -1, 0);
  8499. case 3:
  8500. return new BABYLON.Vector3(0, 1, 0);
  8501. case 4:
  8502. return new BABYLON.Vector3(0, 0, 1);
  8503. case 5:
  8504. return new BABYLON.Vector3(0, 0, -1);
  8505. }
  8506. return BABYLON.Vector3.Zero();
  8507. };
  8508. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8509. var activeCamera = this.getScene().activeCamera;
  8510. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8511. };
  8512. PointLight.prototype._getWorldMatrix = function () {
  8513. if (!this._worldMatrix) {
  8514. this._worldMatrix = BABYLON.Matrix.Identity();
  8515. }
  8516. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8517. return this._worldMatrix;
  8518. };
  8519. return PointLight;
  8520. })(BABYLON.Light);
  8521. BABYLON.PointLight = PointLight;
  8522. })(BABYLON || (BABYLON = {}));
  8523. var BABYLON;
  8524. (function (BABYLON) {
  8525. var SpotLight = (function (_super) {
  8526. __extends(SpotLight, _super);
  8527. function SpotLight(name, position, direction, angle, exponent, scene) {
  8528. _super.call(this, name, scene);
  8529. this.position = position;
  8530. this.direction = direction;
  8531. this.angle = angle;
  8532. this.exponent = exponent;
  8533. }
  8534. SpotLight.prototype.getAbsolutePosition = function () {
  8535. return this.transformedPosition ? this.transformedPosition : this.position;
  8536. };
  8537. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8538. var activeCamera = this.getScene().activeCamera;
  8539. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8540. };
  8541. SpotLight.prototype.needCube = function () {
  8542. return false;
  8543. };
  8544. SpotLight.prototype.supportsVSM = function () {
  8545. return true;
  8546. };
  8547. SpotLight.prototype.needRefreshPerFrame = function () {
  8548. return false;
  8549. };
  8550. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8551. return this.direction;
  8552. };
  8553. SpotLight.prototype.setDirectionToTarget = function (target) {
  8554. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8555. return this.direction;
  8556. };
  8557. SpotLight.prototype.computeTransformedPosition = function () {
  8558. if (this.parent && this.parent.getWorldMatrix) {
  8559. if (!this.transformedPosition) {
  8560. this.transformedPosition = BABYLON.Vector3.Zero();
  8561. }
  8562. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8563. return true;
  8564. }
  8565. return false;
  8566. };
  8567. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8568. var normalizeDirection;
  8569. if (this.parent && this.parent.getWorldMatrix) {
  8570. if (!this._transformedDirection) {
  8571. this._transformedDirection = BABYLON.Vector3.Zero();
  8572. }
  8573. this.computeTransformedPosition();
  8574. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8575. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8576. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8577. }
  8578. else {
  8579. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8580. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8581. }
  8582. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8583. };
  8584. SpotLight.prototype._getWorldMatrix = function () {
  8585. if (!this._worldMatrix) {
  8586. this._worldMatrix = BABYLON.Matrix.Identity();
  8587. }
  8588. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8589. return this._worldMatrix;
  8590. };
  8591. return SpotLight;
  8592. })(BABYLON.Light);
  8593. BABYLON.SpotLight = SpotLight;
  8594. })(BABYLON || (BABYLON = {}));
  8595. var BABYLON;
  8596. (function (BABYLON) {
  8597. var HemisphericLight = (function (_super) {
  8598. __extends(HemisphericLight, _super);
  8599. function HemisphericLight(name, direction, scene) {
  8600. _super.call(this, name, scene);
  8601. this.direction = direction;
  8602. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8603. }
  8604. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8605. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8606. return this.direction;
  8607. };
  8608. HemisphericLight.prototype.getShadowGenerator = function () {
  8609. return null;
  8610. };
  8611. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8612. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8613. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8614. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8615. };
  8616. HemisphericLight.prototype._getWorldMatrix = function () {
  8617. if (!this._worldMatrix) {
  8618. this._worldMatrix = BABYLON.Matrix.Identity();
  8619. }
  8620. return this._worldMatrix;
  8621. };
  8622. return HemisphericLight;
  8623. })(BABYLON.Light);
  8624. BABYLON.HemisphericLight = HemisphericLight;
  8625. })(BABYLON || (BABYLON = {}));
  8626. var BABYLON;
  8627. (function (BABYLON) {
  8628. var DirectionalLight = (function (_super) {
  8629. __extends(DirectionalLight, _super);
  8630. function DirectionalLight(name, direction, scene) {
  8631. _super.call(this, name, scene);
  8632. this.direction = direction;
  8633. this.shadowOrthoScale = 0.5;
  8634. this.autoUpdateExtends = true;
  8635. // Cache
  8636. this._orthoLeft = Number.MAX_VALUE;
  8637. this._orthoRight = Number.MIN_VALUE;
  8638. this._orthoTop = Number.MIN_VALUE;
  8639. this._orthoBottom = Number.MAX_VALUE;
  8640. this.position = direction.scale(-1);
  8641. }
  8642. DirectionalLight.prototype.getAbsolutePosition = function () {
  8643. return this.transformedPosition ? this.transformedPosition : this.position;
  8644. };
  8645. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8646. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8647. return this.direction;
  8648. };
  8649. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8650. var activeCamera = this.getScene().activeCamera;
  8651. // Check extends
  8652. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8653. var tempVector3 = BABYLON.Vector3.Zero();
  8654. this._orthoLeft = Number.MAX_VALUE;
  8655. this._orthoRight = Number.MIN_VALUE;
  8656. this._orthoTop = Number.MIN_VALUE;
  8657. this._orthoBottom = Number.MAX_VALUE;
  8658. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8659. var mesh = renderList[meshIndex];
  8660. if (!mesh) {
  8661. continue;
  8662. }
  8663. var boundingInfo = mesh.getBoundingInfo();
  8664. if (!boundingInfo) {
  8665. continue;
  8666. }
  8667. var boundingBox = boundingInfo.boundingBox;
  8668. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8669. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8670. if (tempVector3.x < this._orthoLeft)
  8671. this._orthoLeft = tempVector3.x;
  8672. if (tempVector3.y < this._orthoBottom)
  8673. this._orthoBottom = tempVector3.y;
  8674. if (tempVector3.x > this._orthoRight)
  8675. this._orthoRight = tempVector3.x;
  8676. if (tempVector3.y > this._orthoTop)
  8677. this._orthoTop = tempVector3.y;
  8678. }
  8679. }
  8680. }
  8681. var xOffset = this._orthoRight - this._orthoLeft;
  8682. var yOffset = this._orthoTop - this._orthoBottom;
  8683. 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);
  8684. };
  8685. DirectionalLight.prototype.supportsVSM = function () {
  8686. return true;
  8687. };
  8688. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8689. return true;
  8690. };
  8691. DirectionalLight.prototype.needCube = function () {
  8692. return false;
  8693. };
  8694. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8695. return this.direction;
  8696. };
  8697. DirectionalLight.prototype.computeTransformedPosition = function () {
  8698. if (this.parent && this.parent.getWorldMatrix) {
  8699. if (!this.transformedPosition) {
  8700. this.transformedPosition = BABYLON.Vector3.Zero();
  8701. }
  8702. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8703. return true;
  8704. }
  8705. return false;
  8706. };
  8707. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8708. if (this.parent && this.parent.getWorldMatrix) {
  8709. if (!this._transformedDirection) {
  8710. this._transformedDirection = BABYLON.Vector3.Zero();
  8711. }
  8712. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8713. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8714. return;
  8715. }
  8716. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8717. };
  8718. DirectionalLight.prototype._getWorldMatrix = function () {
  8719. if (!this._worldMatrix) {
  8720. this._worldMatrix = BABYLON.Matrix.Identity();
  8721. }
  8722. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8723. return this._worldMatrix;
  8724. };
  8725. return DirectionalLight;
  8726. })(BABYLON.Light);
  8727. BABYLON.DirectionalLight = DirectionalLight;
  8728. })(BABYLON || (BABYLON = {}));
  8729. var BABYLON;
  8730. (function (BABYLON) {
  8731. var ShadowGenerator = (function () {
  8732. function ShadowGenerator(mapSize, light) {
  8733. var _this = this;
  8734. // Members
  8735. this._filter = ShadowGenerator.FILTER_NONE;
  8736. this.blurScale = 2;
  8737. this._blurBoxOffset = 0;
  8738. this._bias = 0.00005;
  8739. this._lightDirection = BABYLON.Vector3.Zero();
  8740. this._darkness = 0;
  8741. this._transparencyShadow = false;
  8742. this._viewMatrix = BABYLON.Matrix.Zero();
  8743. this._projectionMatrix = BABYLON.Matrix.Zero();
  8744. this._transformMatrix = BABYLON.Matrix.Zero();
  8745. this._worldViewProjection = BABYLON.Matrix.Zero();
  8746. this._currentFaceIndex = 0;
  8747. this._currentFaceIndexCache = 0;
  8748. this._light = light;
  8749. this._scene = light.getScene();
  8750. this._mapSize = mapSize;
  8751. light._shadowGenerator = this;
  8752. // Render target
  8753. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8754. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8755. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8756. this._shadowMap.anisotropicFilteringLevel = 1;
  8757. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8758. this._shadowMap.renderParticles = false;
  8759. this._shadowMap.onBeforeRender = function (faceIndex) {
  8760. _this._currentFaceIndex = faceIndex;
  8761. };
  8762. this._shadowMap.onAfterUnbind = function () {
  8763. if (!_this.useBlurVarianceShadowMap) {
  8764. return;
  8765. }
  8766. if (!_this._shadowMap2) {
  8767. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8768. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8769. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8770. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8771. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8772. _this._downSamplePostprocess.onApply = function (effect) {
  8773. effect.setTexture("textureSampler", _this._shadowMap);
  8774. };
  8775. _this.blurBoxOffset = 1;
  8776. }
  8777. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8778. };
  8779. // Custom render function
  8780. var renderSubMesh = function (subMesh) {
  8781. var mesh = subMesh.getRenderingMesh();
  8782. var scene = _this._scene;
  8783. var engine = scene.getEngine();
  8784. // Culling
  8785. engine.setState(subMesh.getMaterial().backFaceCulling);
  8786. // Managing instances
  8787. var batch = mesh._getInstancesRenderList(subMesh._id);
  8788. if (batch.mustReturn) {
  8789. return;
  8790. }
  8791. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8792. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8793. engine.enableEffect(_this._effect);
  8794. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8795. var material = subMesh.getMaterial();
  8796. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8797. // Alpha test
  8798. if (material && material.needAlphaTesting()) {
  8799. var alphaTexture = material.getAlphaTestTexture();
  8800. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8801. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8802. }
  8803. // Bones
  8804. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8805. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8806. }
  8807. // Draw
  8808. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8809. }
  8810. else {
  8811. // Need to reset refresh rate of the shadowMap
  8812. _this._shadowMap.resetRefreshCounter();
  8813. }
  8814. };
  8815. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8816. var index;
  8817. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8818. renderSubMesh(opaqueSubMeshes.data[index]);
  8819. }
  8820. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8821. renderSubMesh(alphaTestSubMeshes.data[index]);
  8822. }
  8823. if (_this._transparencyShadow) {
  8824. for (index = 0; index < transparentSubMeshes.length; index++) {
  8825. renderSubMesh(transparentSubMeshes.data[index]);
  8826. }
  8827. }
  8828. };
  8829. this._shadowMap.onClear = function (engine) {
  8830. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8831. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8832. }
  8833. else {
  8834. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8835. }
  8836. };
  8837. }
  8838. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8839. // Static
  8840. get: function () {
  8841. return ShadowGenerator._FILTER_NONE;
  8842. },
  8843. enumerable: true,
  8844. configurable: true
  8845. });
  8846. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8847. get: function () {
  8848. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8849. },
  8850. enumerable: true,
  8851. configurable: true
  8852. });
  8853. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8854. get: function () {
  8855. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8856. },
  8857. enumerable: true,
  8858. configurable: true
  8859. });
  8860. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8861. get: function () {
  8862. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8863. },
  8864. enumerable: true,
  8865. configurable: true
  8866. });
  8867. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8868. get: function () {
  8869. return this._bias;
  8870. },
  8871. set: function (bias) {
  8872. this._bias = bias;
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8878. get: function () {
  8879. return this._blurBoxOffset;
  8880. },
  8881. set: function (value) {
  8882. var _this = this;
  8883. if (this._blurBoxOffset === value) {
  8884. return;
  8885. }
  8886. this._blurBoxOffset = value;
  8887. if (this._boxBlurPostprocess) {
  8888. this._boxBlurPostprocess.dispose();
  8889. }
  8890. 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);
  8891. this._boxBlurPostprocess.onApply = function (effect) {
  8892. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8893. };
  8894. },
  8895. enumerable: true,
  8896. configurable: true
  8897. });
  8898. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8899. get: function () {
  8900. return this._filter;
  8901. },
  8902. set: function (value) {
  8903. if (this._filter === value) {
  8904. return;
  8905. }
  8906. this._filter = value;
  8907. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8908. this._shadowMap.anisotropicFilteringLevel = 16;
  8909. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8910. }
  8911. else {
  8912. this._shadowMap.anisotropicFilteringLevel = 1;
  8913. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8914. }
  8915. },
  8916. enumerable: true,
  8917. configurable: true
  8918. });
  8919. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8920. get: function () {
  8921. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8922. },
  8923. set: function (value) {
  8924. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8925. },
  8926. enumerable: true,
  8927. configurable: true
  8928. });
  8929. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8930. get: function () {
  8931. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8932. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8933. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8934. },
  8935. set: function (value) {
  8936. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8942. get: function () {
  8943. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8944. },
  8945. set: function (value) {
  8946. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8947. },
  8948. enumerable: true,
  8949. configurable: true
  8950. });
  8951. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8952. var defines = [];
  8953. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8954. defines.push("#define VSM");
  8955. }
  8956. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8957. var mesh = subMesh.getMesh();
  8958. var material = subMesh.getMaterial();
  8959. // Alpha test
  8960. if (material && material.needAlphaTesting()) {
  8961. defines.push("#define ALPHATEST");
  8962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8963. attribs.push(BABYLON.VertexBuffer.UVKind);
  8964. defines.push("#define UV1");
  8965. }
  8966. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8967. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8968. defines.push("#define UV2");
  8969. }
  8970. }
  8971. // Bones
  8972. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8975. if (mesh.numBoneInfluencers > 4) {
  8976. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  8977. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  8978. }
  8979. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  8980. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8981. }
  8982. else {
  8983. defines.push("#define NUM_BONE_INFLUENCERS 0");
  8984. }
  8985. // Instances
  8986. if (useInstances) {
  8987. defines.push("#define INSTANCES");
  8988. attribs.push("world0");
  8989. attribs.push("world1");
  8990. attribs.push("world2");
  8991. attribs.push("world3");
  8992. }
  8993. // Get correct effect
  8994. var join = defines.join("\n");
  8995. if (this._cachedDefines !== join) {
  8996. this._cachedDefines = join;
  8997. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8998. }
  8999. return this._effect.isReady();
  9000. };
  9001. ShadowGenerator.prototype.getShadowMap = function () {
  9002. return this._shadowMap;
  9003. };
  9004. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9005. if (this._shadowMap2) {
  9006. return this._shadowMap2;
  9007. }
  9008. return this._shadowMap;
  9009. };
  9010. ShadowGenerator.prototype.getLight = function () {
  9011. return this._light;
  9012. };
  9013. // Methods
  9014. ShadowGenerator.prototype.getTransformMatrix = function () {
  9015. var scene = this._scene;
  9016. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9017. return this._transformMatrix;
  9018. }
  9019. this._currentRenderID = scene.getRenderId();
  9020. this._currentFaceIndexCache = this._currentFaceIndex;
  9021. var lightPosition = this._light.position;
  9022. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9023. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9024. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9025. }
  9026. if (this._light.computeTransformedPosition()) {
  9027. lightPosition = this._light.transformedPosition;
  9028. }
  9029. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9030. this._cachedPosition = lightPosition.clone();
  9031. this._cachedDirection = this._lightDirection.clone();
  9032. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9033. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9034. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9035. }
  9036. return this._transformMatrix;
  9037. };
  9038. ShadowGenerator.prototype.getDarkness = function () {
  9039. return this._darkness;
  9040. };
  9041. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9042. if (darkness >= 1.0)
  9043. this._darkness = 1.0;
  9044. else if (darkness <= 0.0)
  9045. this._darkness = 0.0;
  9046. else
  9047. this._darkness = darkness;
  9048. };
  9049. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9050. this._transparencyShadow = hasShadow;
  9051. };
  9052. ShadowGenerator.prototype._packHalf = function (depth) {
  9053. var scale = depth * 255.0;
  9054. var fract = scale - Math.floor(scale);
  9055. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9056. };
  9057. ShadowGenerator.prototype.dispose = function () {
  9058. this._shadowMap.dispose();
  9059. if (this._shadowMap2) {
  9060. this._shadowMap2.dispose();
  9061. }
  9062. if (this._downSamplePostprocess) {
  9063. this._downSamplePostprocess.dispose();
  9064. }
  9065. if (this._boxBlurPostprocess) {
  9066. this._boxBlurPostprocess.dispose();
  9067. }
  9068. };
  9069. ShadowGenerator._FILTER_NONE = 0;
  9070. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9071. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9072. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9073. return ShadowGenerator;
  9074. })();
  9075. BABYLON.ShadowGenerator = ShadowGenerator;
  9076. })(BABYLON || (BABYLON = {}));
  9077. var BABYLON;
  9078. (function (BABYLON) {
  9079. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9080. if (boxMin.x > sphereCenter.x + sphereRadius)
  9081. return false;
  9082. if (sphereCenter.x - sphereRadius > boxMax.x)
  9083. return false;
  9084. if (boxMin.y > sphereCenter.y + sphereRadius)
  9085. return false;
  9086. if (sphereCenter.y - sphereRadius > boxMax.y)
  9087. return false;
  9088. if (boxMin.z > sphereCenter.z + sphereRadius)
  9089. return false;
  9090. if (sphereCenter.z - sphereRadius > boxMax.z)
  9091. return false;
  9092. return true;
  9093. };
  9094. var getLowestRoot = function (a, b, c, maxR) {
  9095. var determinant = b * b - 4.0 * a * c;
  9096. var result = { root: 0, found: false };
  9097. if (determinant < 0)
  9098. return result;
  9099. var sqrtD = Math.sqrt(determinant);
  9100. var r1 = (-b - sqrtD) / (2.0 * a);
  9101. var r2 = (-b + sqrtD) / (2.0 * a);
  9102. if (r1 > r2) {
  9103. var temp = r2;
  9104. r2 = r1;
  9105. r1 = temp;
  9106. }
  9107. if (r1 > 0 && r1 < maxR) {
  9108. result.root = r1;
  9109. result.found = true;
  9110. return result;
  9111. }
  9112. if (r2 > 0 && r2 < maxR) {
  9113. result.root = r2;
  9114. result.found = true;
  9115. return result;
  9116. }
  9117. return result;
  9118. };
  9119. var Collider = (function () {
  9120. function Collider() {
  9121. this.radius = new BABYLON.Vector3(1, 1, 1);
  9122. this.retry = 0;
  9123. this.basePointWorld = BABYLON.Vector3.Zero();
  9124. this.velocityWorld = BABYLON.Vector3.Zero();
  9125. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9126. this._collisionPoint = BABYLON.Vector3.Zero();
  9127. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9128. this._tempVector = BABYLON.Vector3.Zero();
  9129. this._tempVector2 = BABYLON.Vector3.Zero();
  9130. this._tempVector3 = BABYLON.Vector3.Zero();
  9131. this._tempVector4 = BABYLON.Vector3.Zero();
  9132. this._edge = BABYLON.Vector3.Zero();
  9133. this._baseToVertex = BABYLON.Vector3.Zero();
  9134. this._destinationPoint = BABYLON.Vector3.Zero();
  9135. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9136. this._displacementVector = BABYLON.Vector3.Zero();
  9137. }
  9138. // Methods
  9139. Collider.prototype._initialize = function (source, dir, e) {
  9140. this.velocity = dir;
  9141. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9142. this.basePoint = source;
  9143. source.multiplyToRef(this.radius, this.basePointWorld);
  9144. dir.multiplyToRef(this.radius, this.velocityWorld);
  9145. this.velocityWorldLength = this.velocityWorld.length();
  9146. this.epsilon = e;
  9147. this.collisionFound = false;
  9148. };
  9149. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9150. pa.subtractToRef(point, this._tempVector);
  9151. pb.subtractToRef(point, this._tempVector2);
  9152. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9153. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9154. if (d < 0)
  9155. return false;
  9156. pc.subtractToRef(point, this._tempVector3);
  9157. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9158. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9159. if (d < 0)
  9160. return false;
  9161. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9162. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9163. return d >= 0;
  9164. };
  9165. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9166. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9167. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9168. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9169. return false;
  9170. }
  9171. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9172. return false;
  9173. return true;
  9174. };
  9175. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9176. var t0;
  9177. var embeddedInPlane = false;
  9178. //defensive programming, actually not needed.
  9179. if (!trianglePlaneArray) {
  9180. trianglePlaneArray = [];
  9181. }
  9182. if (!trianglePlaneArray[faceIndex]) {
  9183. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9184. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9185. }
  9186. var trianglePlane = trianglePlaneArray[faceIndex];
  9187. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9188. return;
  9189. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9190. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9191. if (normalDotVelocity == 0) {
  9192. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9193. return;
  9194. embeddedInPlane = true;
  9195. t0 = 0;
  9196. }
  9197. else {
  9198. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9199. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9200. if (t0 > t1) {
  9201. var temp = t1;
  9202. t1 = t0;
  9203. t0 = temp;
  9204. }
  9205. if (t0 > 1.0 || t1 < 0.0)
  9206. return;
  9207. if (t0 < 0)
  9208. t0 = 0;
  9209. if (t0 > 1.0)
  9210. t0 = 1.0;
  9211. }
  9212. this._collisionPoint.copyFromFloats(0, 0, 0);
  9213. var found = false;
  9214. var t = 1.0;
  9215. if (!embeddedInPlane) {
  9216. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9217. this.velocity.scaleToRef(t0, this._tempVector);
  9218. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9219. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9220. found = true;
  9221. t = t0;
  9222. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9223. }
  9224. }
  9225. if (!found) {
  9226. var velocitySquaredLength = this.velocity.lengthSquared();
  9227. var a = velocitySquaredLength;
  9228. this.basePoint.subtractToRef(p1, this._tempVector);
  9229. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9230. var c = this._tempVector.lengthSquared() - 1.0;
  9231. var lowestRoot = getLowestRoot(a, b, c, t);
  9232. if (lowestRoot.found) {
  9233. t = lowestRoot.root;
  9234. found = true;
  9235. this._collisionPoint.copyFrom(p1);
  9236. }
  9237. this.basePoint.subtractToRef(p2, this._tempVector);
  9238. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9239. c = this._tempVector.lengthSquared() - 1.0;
  9240. lowestRoot = getLowestRoot(a, b, c, t);
  9241. if (lowestRoot.found) {
  9242. t = lowestRoot.root;
  9243. found = true;
  9244. this._collisionPoint.copyFrom(p2);
  9245. }
  9246. this.basePoint.subtractToRef(p3, this._tempVector);
  9247. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9248. c = this._tempVector.lengthSquared() - 1.0;
  9249. lowestRoot = getLowestRoot(a, b, c, t);
  9250. if (lowestRoot.found) {
  9251. t = lowestRoot.root;
  9252. found = true;
  9253. this._collisionPoint.copyFrom(p3);
  9254. }
  9255. p2.subtractToRef(p1, this._edge);
  9256. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9257. var edgeSquaredLength = this._edge.lengthSquared();
  9258. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9259. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9260. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9261. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9262. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9263. lowestRoot = getLowestRoot(a, b, c, t);
  9264. if (lowestRoot.found) {
  9265. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9266. if (f >= 0.0 && f <= 1.0) {
  9267. t = lowestRoot.root;
  9268. found = true;
  9269. this._edge.scaleInPlace(f);
  9270. p1.addToRef(this._edge, this._collisionPoint);
  9271. }
  9272. }
  9273. p3.subtractToRef(p2, this._edge);
  9274. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9275. edgeSquaredLength = this._edge.lengthSquared();
  9276. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9277. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9278. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9279. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9280. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9281. lowestRoot = getLowestRoot(a, b, c, t);
  9282. if (lowestRoot.found) {
  9283. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9284. if (f >= 0.0 && f <= 1.0) {
  9285. t = lowestRoot.root;
  9286. found = true;
  9287. this._edge.scaleInPlace(f);
  9288. p2.addToRef(this._edge, this._collisionPoint);
  9289. }
  9290. }
  9291. p1.subtractToRef(p3, this._edge);
  9292. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9293. edgeSquaredLength = this._edge.lengthSquared();
  9294. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9295. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9296. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9297. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9298. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9299. lowestRoot = getLowestRoot(a, b, c, t);
  9300. if (lowestRoot.found) {
  9301. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9302. if (f >= 0.0 && f <= 1.0) {
  9303. t = lowestRoot.root;
  9304. found = true;
  9305. this._edge.scaleInPlace(f);
  9306. p3.addToRef(this._edge, this._collisionPoint);
  9307. }
  9308. }
  9309. }
  9310. if (found) {
  9311. var distToCollision = t * this.velocity.length();
  9312. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9313. if (!this.intersectionPoint) {
  9314. this.intersectionPoint = this._collisionPoint.clone();
  9315. }
  9316. else {
  9317. this.intersectionPoint.copyFrom(this._collisionPoint);
  9318. }
  9319. this.nearestDistance = distToCollision;
  9320. this.collisionFound = true;
  9321. }
  9322. }
  9323. };
  9324. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9325. for (var i = indexStart; i < indexEnd; i += 3) {
  9326. var p1 = pts[indices[i] - decal];
  9327. var p2 = pts[indices[i + 1] - decal];
  9328. var p3 = pts[indices[i + 2] - decal];
  9329. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9330. }
  9331. };
  9332. Collider.prototype._getResponse = function (pos, vel) {
  9333. pos.addToRef(vel, this._destinationPoint);
  9334. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9335. this.basePoint.addToRef(vel, pos);
  9336. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9337. this._slidePlaneNormal.normalize();
  9338. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9339. pos.addInPlace(this._displacementVector);
  9340. this.intersectionPoint.addInPlace(this._displacementVector);
  9341. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9342. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9343. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9344. };
  9345. return Collider;
  9346. })();
  9347. BABYLON.Collider = Collider;
  9348. })(BABYLON || (BABYLON = {}));
  9349. var BABYLON;
  9350. (function (BABYLON) {
  9351. //WebWorker code will be inserted to this variable.
  9352. BABYLON.CollisionWorker = "";
  9353. (function (WorkerTaskType) {
  9354. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9355. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9356. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9357. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9358. var WorkerTaskType = BABYLON.WorkerTaskType;
  9359. (function (WorkerReplyType) {
  9360. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9361. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9362. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9363. var WorkerReplyType = BABYLON.WorkerReplyType;
  9364. var CollisionCoordinatorWorker = (function () {
  9365. function CollisionCoordinatorWorker() {
  9366. var _this = this;
  9367. this._scaledPosition = BABYLON.Vector3.Zero();
  9368. this._scaledVelocity = BABYLON.Vector3.Zero();
  9369. this.onMeshUpdated = function (mesh) {
  9370. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9371. };
  9372. this.onGeometryUpdated = function (geometry) {
  9373. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9374. };
  9375. this._afterRender = function () {
  9376. if (!_this._init)
  9377. return;
  9378. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9379. return;
  9380. }
  9381. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9382. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9383. if (_this._runningUpdated > 4) {
  9384. return;
  9385. }
  9386. ++_this._runningUpdated;
  9387. var payload = {
  9388. updatedMeshes: _this._addUpdateMeshesList,
  9389. updatedGeometries: _this._addUpdateGeometriesList,
  9390. removedGeometries: _this._toRemoveGeometryArray,
  9391. removedMeshes: _this._toRemoveMeshesArray
  9392. };
  9393. var message = {
  9394. payload: payload,
  9395. taskType: WorkerTaskType.UPDATE
  9396. };
  9397. var serializable = [];
  9398. for (var id in payload.updatedGeometries) {
  9399. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9400. //prepare transferables
  9401. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9402. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9403. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9404. }
  9405. }
  9406. _this._worker.postMessage(message, serializable);
  9407. _this._addUpdateMeshesList = {};
  9408. _this._addUpdateGeometriesList = {};
  9409. _this._toRemoveGeometryArray = [];
  9410. _this._toRemoveMeshesArray = [];
  9411. };
  9412. this._onMessageFromWorker = function (e) {
  9413. var returnData = e.data;
  9414. if (returnData.error != WorkerReplyType.SUCCESS) {
  9415. //TODO what errors can be returned from the worker?
  9416. BABYLON.Tools.Warn("error returned from worker!");
  9417. return;
  9418. }
  9419. switch (returnData.taskType) {
  9420. case WorkerTaskType.INIT:
  9421. _this._init = true;
  9422. //Update the worked with ALL of the scene's current state
  9423. _this._scene.meshes.forEach(function (mesh) {
  9424. _this.onMeshAdded(mesh);
  9425. });
  9426. _this._scene.getGeometries().forEach(function (geometry) {
  9427. _this.onGeometryAdded(geometry);
  9428. });
  9429. break;
  9430. case WorkerTaskType.UPDATE:
  9431. _this._runningUpdated--;
  9432. break;
  9433. case WorkerTaskType.COLLIDE:
  9434. _this._runningCollisionTask = false;
  9435. var returnPayload = returnData.payload;
  9436. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9437. return;
  9438. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9439. //cleanup
  9440. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9441. break;
  9442. }
  9443. };
  9444. this._collisionsCallbackArray = [];
  9445. this._init = false;
  9446. this._runningUpdated = 0;
  9447. this._runningCollisionTask = false;
  9448. this._addUpdateMeshesList = {};
  9449. this._addUpdateGeometriesList = {};
  9450. this._toRemoveGeometryArray = [];
  9451. this._toRemoveMeshesArray = [];
  9452. }
  9453. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9454. if (!this._init)
  9455. return;
  9456. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9457. return;
  9458. position.divideToRef(collider.radius, this._scaledPosition);
  9459. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9460. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9461. var payload = {
  9462. collider: {
  9463. position: this._scaledPosition.asArray(),
  9464. velocity: this._scaledVelocity.asArray(),
  9465. radius: collider.radius.asArray()
  9466. },
  9467. collisionId: collisionIndex,
  9468. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9469. maximumRetry: maximumRetry
  9470. };
  9471. var message = {
  9472. payload: payload,
  9473. taskType: WorkerTaskType.COLLIDE
  9474. };
  9475. this._worker.postMessage(message);
  9476. };
  9477. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9478. this._scene = scene;
  9479. this._scene.registerAfterRender(this._afterRender);
  9480. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9481. this._worker = new Worker(workerUrl);
  9482. this._worker.onmessage = this._onMessageFromWorker;
  9483. var message = {
  9484. payload: {},
  9485. taskType: WorkerTaskType.INIT
  9486. };
  9487. this._worker.postMessage(message);
  9488. };
  9489. CollisionCoordinatorWorker.prototype.destroy = function () {
  9490. this._scene.unregisterAfterRender(this._afterRender);
  9491. this._worker.terminate();
  9492. };
  9493. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9494. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9495. this.onMeshUpdated(mesh);
  9496. };
  9497. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9498. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9499. };
  9500. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9501. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9502. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9503. this.onGeometryUpdated(geometry);
  9504. };
  9505. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9506. this._toRemoveGeometryArray.push(geometry.id);
  9507. };
  9508. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9509. var submeshes = [];
  9510. if (mesh.subMeshes) {
  9511. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9512. return {
  9513. position: idx,
  9514. verticesStart: sm.verticesStart,
  9515. verticesCount: sm.verticesCount,
  9516. indexStart: sm.indexStart,
  9517. indexCount: sm.indexCount,
  9518. hasMaterial: !!sm.getMaterial(),
  9519. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9520. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9521. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9522. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9523. };
  9524. });
  9525. }
  9526. var geometryId = null;
  9527. if (mesh instanceof BABYLON.Mesh) {
  9528. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9529. }
  9530. else if (mesh instanceof BABYLON.InstancedMesh) {
  9531. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9532. }
  9533. return {
  9534. uniqueId: mesh.uniqueId,
  9535. id: mesh.id,
  9536. name: mesh.name,
  9537. geometryId: geometryId,
  9538. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9539. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9540. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9541. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9542. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9543. subMeshes: submeshes,
  9544. checkCollisions: mesh.checkCollisions
  9545. };
  9546. };
  9547. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9548. return {
  9549. id: geometry.id,
  9550. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9551. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9552. indices: new Int32Array(geometry.getIndices() || []),
  9553. };
  9554. };
  9555. return CollisionCoordinatorWorker;
  9556. })();
  9557. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9558. var CollisionCoordinatorLegacy = (function () {
  9559. function CollisionCoordinatorLegacy() {
  9560. this._scaledPosition = BABYLON.Vector3.Zero();
  9561. this._scaledVelocity = BABYLON.Vector3.Zero();
  9562. this._finalPosition = BABYLON.Vector3.Zero();
  9563. }
  9564. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9565. position.divideToRef(collider.radius, this._scaledPosition);
  9566. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9567. collider.collidedMesh = null;
  9568. collider.retry = 0;
  9569. collider.initialVelocity = this._scaledVelocity;
  9570. collider.initialPosition = this._scaledPosition;
  9571. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9572. this._finalPosition.multiplyInPlace(collider.radius);
  9573. //run the callback
  9574. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9575. };
  9576. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9577. this._scene = scene;
  9578. };
  9579. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9580. //Legacy need no destruction method.
  9581. };
  9582. //No update in legacy mode
  9583. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9584. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9585. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9586. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9587. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9588. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9589. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9590. if (excludedMesh === void 0) { excludedMesh = null; }
  9591. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9592. if (collider.retry >= maximumRetry) {
  9593. finalPosition.copyFrom(position);
  9594. return;
  9595. }
  9596. collider._initialize(position, velocity, closeDistance);
  9597. // Check all meshes
  9598. for (var index = 0; index < this._scene.meshes.length; index++) {
  9599. var mesh = this._scene.meshes[index];
  9600. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9601. mesh._checkCollision(collider);
  9602. }
  9603. }
  9604. if (!collider.collisionFound) {
  9605. position.addToRef(velocity, finalPosition);
  9606. return;
  9607. }
  9608. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9609. collider._getResponse(position, velocity);
  9610. }
  9611. if (velocity.length() <= closeDistance) {
  9612. finalPosition.copyFrom(position);
  9613. return;
  9614. }
  9615. collider.retry++;
  9616. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9617. };
  9618. return CollisionCoordinatorLegacy;
  9619. })();
  9620. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9621. })(BABYLON || (BABYLON = {}));
  9622. var BABYLON;
  9623. (function (BABYLON) {
  9624. var VRCameraMetrics = (function () {
  9625. function VRCameraMetrics() {
  9626. this.compensateDistortion = true;
  9627. }
  9628. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9629. get: function () {
  9630. return this.hResolution / (2 * this.vResolution);
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9636. get: function () {
  9637. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9643. get: function () {
  9644. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9645. var h = (4 * meters) / this.hScreenSize;
  9646. return BABYLON.Matrix.Translation(h, 0, 0);
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9652. get: function () {
  9653. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9654. var h = (4 * meters) / this.hScreenSize;
  9655. return BABYLON.Matrix.Translation(-h, 0, 0);
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9661. get: function () {
  9662. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9668. get: function () {
  9669. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. VRCameraMetrics.GetDefault = function () {
  9675. var result = new VRCameraMetrics();
  9676. result.hResolution = 1280;
  9677. result.vResolution = 800;
  9678. result.hScreenSize = 0.149759993;
  9679. result.vScreenSize = 0.0935999975;
  9680. result.vScreenCenter = 0.0467999987,
  9681. result.eyeToScreenDistance = 0.0410000011;
  9682. result.lensSeparationDistance = 0.0635000020;
  9683. result.interpupillaryDistance = 0.0640000030;
  9684. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9685. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9686. result.postProcessScaleFactor = 1.714605507808412;
  9687. result.lensCenterOffset = 0.151976421;
  9688. return result;
  9689. };
  9690. return VRCameraMetrics;
  9691. })();
  9692. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9693. var Camera = (function (_super) {
  9694. __extends(Camera, _super);
  9695. function Camera(name, position, scene) {
  9696. _super.call(this, name, scene);
  9697. this.position = position;
  9698. // Members
  9699. this.upVector = BABYLON.Vector3.Up();
  9700. this.orthoLeft = null;
  9701. this.orthoRight = null;
  9702. this.orthoBottom = null;
  9703. this.orthoTop = null;
  9704. this.fov = 0.8;
  9705. this.minZ = 1.0;
  9706. this.maxZ = 10000.0;
  9707. this.inertia = 0.9;
  9708. this.mode = Camera.PERSPECTIVE_CAMERA;
  9709. this.isIntermediate = false;
  9710. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9711. this.layerMask = 0x0FFFFFFF;
  9712. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9713. // Camera rig members
  9714. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9715. this._rigCameras = new Array();
  9716. // Cache
  9717. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9718. this._projectionMatrix = new BABYLON.Matrix();
  9719. this._postProcesses = new Array();
  9720. this._postProcessesTakenIndices = [];
  9721. this._activeMeshes = new BABYLON.SmartArray(256);
  9722. this._globalPosition = BABYLON.Vector3.Zero();
  9723. scene.addCamera(this);
  9724. if (!scene.activeCamera) {
  9725. scene.activeCamera = this;
  9726. }
  9727. }
  9728. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9729. get: function () {
  9730. return Camera._PERSPECTIVE_CAMERA;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9736. get: function () {
  9737. return Camera._ORTHOGRAPHIC_CAMERA;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9743. get: function () {
  9744. return Camera._FOVMODE_VERTICAL_FIXED;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9750. get: function () {
  9751. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9757. get: function () {
  9758. return Camera._RIG_MODE_NONE;
  9759. },
  9760. enumerable: true,
  9761. configurable: true
  9762. });
  9763. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9764. get: function () {
  9765. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9771. get: function () {
  9772. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9778. get: function () {
  9779. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9785. get: function () {
  9786. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9792. get: function () {
  9793. return Camera._RIG_MODE_VR;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(Camera.prototype, "globalPosition", {
  9799. get: function () {
  9800. return this._globalPosition;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Camera.prototype.getActiveMeshes = function () {
  9806. return this._activeMeshes;
  9807. };
  9808. Camera.prototype.isActiveMesh = function (mesh) {
  9809. return (this._activeMeshes.indexOf(mesh) !== -1);
  9810. };
  9811. //Cache
  9812. Camera.prototype._initCache = function () {
  9813. _super.prototype._initCache.call(this);
  9814. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9815. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9816. this._cache.mode = undefined;
  9817. this._cache.minZ = undefined;
  9818. this._cache.maxZ = undefined;
  9819. this._cache.fov = undefined;
  9820. this._cache.aspectRatio = undefined;
  9821. this._cache.orthoLeft = undefined;
  9822. this._cache.orthoRight = undefined;
  9823. this._cache.orthoBottom = undefined;
  9824. this._cache.orthoTop = undefined;
  9825. this._cache.renderWidth = undefined;
  9826. this._cache.renderHeight = undefined;
  9827. };
  9828. Camera.prototype._updateCache = function (ignoreParentClass) {
  9829. if (!ignoreParentClass) {
  9830. _super.prototype._updateCache.call(this);
  9831. }
  9832. var engine = this.getEngine();
  9833. this._cache.position.copyFrom(this.position);
  9834. this._cache.upVector.copyFrom(this.upVector);
  9835. this._cache.mode = this.mode;
  9836. this._cache.minZ = this.minZ;
  9837. this._cache.maxZ = this.maxZ;
  9838. this._cache.fov = this.fov;
  9839. this._cache.aspectRatio = engine.getAspectRatio(this);
  9840. this._cache.orthoLeft = this.orthoLeft;
  9841. this._cache.orthoRight = this.orthoRight;
  9842. this._cache.orthoBottom = this.orthoBottom;
  9843. this._cache.orthoTop = this.orthoTop;
  9844. this._cache.renderWidth = engine.getRenderWidth();
  9845. this._cache.renderHeight = engine.getRenderHeight();
  9846. };
  9847. Camera.prototype._updateFromScene = function () {
  9848. this.updateCache();
  9849. this._update();
  9850. };
  9851. // Synchronized
  9852. Camera.prototype._isSynchronized = function () {
  9853. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9854. };
  9855. Camera.prototype._isSynchronizedViewMatrix = function () {
  9856. if (!_super.prototype._isSynchronized.call(this))
  9857. return false;
  9858. return this._cache.position.equals(this.position)
  9859. && this._cache.upVector.equals(this.upVector)
  9860. && this.isSynchronizedWithParent();
  9861. };
  9862. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9863. var check = this._cache.mode === this.mode
  9864. && this._cache.minZ === this.minZ
  9865. && this._cache.maxZ === this.maxZ;
  9866. if (!check) {
  9867. return false;
  9868. }
  9869. var engine = this.getEngine();
  9870. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9871. check = this._cache.fov === this.fov
  9872. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9873. }
  9874. else {
  9875. check = this._cache.orthoLeft === this.orthoLeft
  9876. && this._cache.orthoRight === this.orthoRight
  9877. && this._cache.orthoBottom === this.orthoBottom
  9878. && this._cache.orthoTop === this.orthoTop
  9879. && this._cache.renderWidth === engine.getRenderWidth()
  9880. && this._cache.renderHeight === engine.getRenderHeight();
  9881. }
  9882. return check;
  9883. };
  9884. // Controls
  9885. Camera.prototype.attachControl = function (element) {
  9886. };
  9887. Camera.prototype.detachControl = function (element) {
  9888. };
  9889. Camera.prototype._update = function () {
  9890. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9891. this._updateRigCameras();
  9892. }
  9893. this._checkInputs();
  9894. };
  9895. Camera.prototype._checkInputs = function () {
  9896. };
  9897. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9898. if (insertAt === void 0) { insertAt = null; }
  9899. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9900. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9901. return 0;
  9902. }
  9903. if (insertAt == null || insertAt < 0) {
  9904. this._postProcesses.push(postProcess);
  9905. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9906. return this._postProcesses.length - 1;
  9907. }
  9908. var add = 0;
  9909. var i;
  9910. var start;
  9911. if (this._postProcesses[insertAt]) {
  9912. start = this._postProcesses.length - 1;
  9913. for (i = start; i >= insertAt + 1; --i) {
  9914. this._postProcesses[i + 1] = this._postProcesses[i];
  9915. }
  9916. add = 1;
  9917. }
  9918. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9919. if (this._postProcessesTakenIndices[i] < insertAt) {
  9920. continue;
  9921. }
  9922. start = this._postProcessesTakenIndices.length - 1;
  9923. for (var j = start; j >= i; --j) {
  9924. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9925. }
  9926. this._postProcessesTakenIndices[i] = insertAt;
  9927. break;
  9928. }
  9929. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9930. this._postProcessesTakenIndices.push(insertAt);
  9931. }
  9932. var result = insertAt + add;
  9933. this._postProcesses[result] = postProcess;
  9934. return result;
  9935. };
  9936. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9937. if (atIndices === void 0) { atIndices = null; }
  9938. var result = [];
  9939. var i;
  9940. var index;
  9941. if (!atIndices) {
  9942. var length = this._postProcesses.length;
  9943. for (i = 0; i < length; i++) {
  9944. if (this._postProcesses[i] !== postProcess) {
  9945. continue;
  9946. }
  9947. delete this._postProcesses[i];
  9948. index = this._postProcessesTakenIndices.indexOf(i);
  9949. this._postProcessesTakenIndices.splice(index, 1);
  9950. }
  9951. }
  9952. else {
  9953. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9954. for (i = 0; i < atIndices.length; i++) {
  9955. var foundPostProcess = this._postProcesses[atIndices[i]];
  9956. if (foundPostProcess !== postProcess) {
  9957. result.push(i);
  9958. continue;
  9959. }
  9960. delete this._postProcesses[atIndices[i]];
  9961. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9962. this._postProcessesTakenIndices.splice(index, 1);
  9963. }
  9964. }
  9965. return result;
  9966. };
  9967. Camera.prototype.getWorldMatrix = function () {
  9968. if (!this._worldMatrix) {
  9969. this._worldMatrix = BABYLON.Matrix.Identity();
  9970. }
  9971. var viewMatrix = this.getViewMatrix();
  9972. viewMatrix.invertToRef(this._worldMatrix);
  9973. return this._worldMatrix;
  9974. };
  9975. Camera.prototype._getViewMatrix = function () {
  9976. return BABYLON.Matrix.Identity();
  9977. };
  9978. Camera.prototype.getViewMatrix = function (force) {
  9979. this._computedViewMatrix = this._computeViewMatrix(force);
  9980. if (!force && this._isSynchronizedViewMatrix()) {
  9981. return this._computedViewMatrix;
  9982. }
  9983. if (!this.parent || !this.parent.getWorldMatrix) {
  9984. this._globalPosition.copyFrom(this.position);
  9985. }
  9986. else {
  9987. if (!this._worldMatrix) {
  9988. this._worldMatrix = BABYLON.Matrix.Identity();
  9989. }
  9990. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9991. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9992. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9993. this._computedViewMatrix.invert();
  9994. this._markSyncedWithParent();
  9995. }
  9996. this._currentRenderId = this.getScene().getRenderId();
  9997. return this._computedViewMatrix;
  9998. };
  9999. Camera.prototype._computeViewMatrix = function (force) {
  10000. if (!force && this._isSynchronizedViewMatrix()) {
  10001. return this._computedViewMatrix;
  10002. }
  10003. this._computedViewMatrix = this._getViewMatrix();
  10004. this._currentRenderId = this.getScene().getRenderId();
  10005. return this._computedViewMatrix;
  10006. };
  10007. Camera.prototype.getProjectionMatrix = function (force) {
  10008. if (!force && this._isSynchronizedProjectionMatrix()) {
  10009. return this._projectionMatrix;
  10010. }
  10011. var engine = this.getEngine();
  10012. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10013. if (this.minZ <= 0) {
  10014. this.minZ = 0.1;
  10015. }
  10016. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10017. return this._projectionMatrix;
  10018. }
  10019. var halfWidth = engine.getRenderWidth() / 2.0;
  10020. var halfHeight = engine.getRenderHeight() / 2.0;
  10021. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10022. return this._projectionMatrix;
  10023. };
  10024. Camera.prototype.dispose = function () {
  10025. // Animations
  10026. this.getScene().stopAnimation(this);
  10027. // Remove from scene
  10028. this.getScene().removeCamera(this);
  10029. while (this._rigCameras.length > 0) {
  10030. this._rigCameras.pop().dispose();
  10031. }
  10032. // Postprocesses
  10033. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10034. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10035. }
  10036. };
  10037. // ---- Camera rigs section ----
  10038. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10039. while (this._rigCameras.length > 0) {
  10040. this._rigCameras.pop().dispose();
  10041. }
  10042. this.cameraRigMode = mode;
  10043. this._cameraRigParams = {};
  10044. switch (this.cameraRigMode) {
  10045. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10046. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10047. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10048. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10049. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10050. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10051. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10052. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10053. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10054. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10055. break;
  10056. }
  10057. var postProcesses = new Array();
  10058. switch (this.cameraRigMode) {
  10059. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10060. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10061. this._rigCameras[0].isIntermediate = true;
  10062. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10063. postProcesses[1].onApply = function (effect) {
  10064. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10065. };
  10066. break;
  10067. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10068. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10069. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10070. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10071. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10072. var secondCamIndex = 1 - firstCamIndex;
  10073. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10074. this._rigCameras[firstCamIndex].isIntermediate = true;
  10075. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10076. break;
  10077. case Camera.RIG_MODE_VR:
  10078. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10079. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10080. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10081. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10082. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10083. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10084. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10085. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10086. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10087. if (metrics.compensateDistortion) {
  10088. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10089. }
  10090. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10091. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10092. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10093. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10094. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10095. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10096. if (metrics.compensateDistortion) {
  10097. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10098. }
  10099. break;
  10100. }
  10101. this._update();
  10102. };
  10103. Camera.prototype._getVRProjectionMatrix = function () {
  10104. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10105. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10106. return this._projectionMatrix;
  10107. };
  10108. Camera.prototype.setCameraRigParameter = function (name, value) {
  10109. this._cameraRigParams[name] = value;
  10110. //provisionnally:
  10111. if (name === "interaxialDistance") {
  10112. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10113. }
  10114. };
  10115. /**
  10116. * May needs to be overridden by children so sub has required properties to be copied
  10117. */
  10118. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10119. return null;
  10120. };
  10121. /**
  10122. * May needs to be overridden by children
  10123. */
  10124. Camera.prototype._updateRigCameras = function () {
  10125. for (var i = 0; i < this._rigCameras.length; i++) {
  10126. this._rigCameras[i].minZ = this.minZ;
  10127. this._rigCameras[i].maxZ = this.maxZ;
  10128. this._rigCameras[i].fov = this.fov;
  10129. }
  10130. // only update viewport when ANAGLYPH
  10131. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10132. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10133. }
  10134. };
  10135. // Statics
  10136. Camera._PERSPECTIVE_CAMERA = 0;
  10137. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10138. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10139. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10140. Camera._RIG_MODE_NONE = 0;
  10141. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10142. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10143. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10144. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10145. Camera._RIG_MODE_VR = 20;
  10146. return Camera;
  10147. })(BABYLON.Node);
  10148. BABYLON.Camera = Camera;
  10149. })(BABYLON || (BABYLON = {}));
  10150. var BABYLON;
  10151. (function (BABYLON) {
  10152. var TargetCamera = (function (_super) {
  10153. __extends(TargetCamera, _super);
  10154. function TargetCamera(name, position, scene) {
  10155. _super.call(this, name, position, scene);
  10156. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10157. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10158. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10159. this.speed = 2.0;
  10160. this.noRotationConstraint = false;
  10161. this.lockedTarget = null;
  10162. this._currentTarget = BABYLON.Vector3.Zero();
  10163. this._viewMatrix = BABYLON.Matrix.Zero();
  10164. this._camMatrix = BABYLON.Matrix.Zero();
  10165. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10166. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10167. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10168. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10169. this._lookAtTemp = BABYLON.Matrix.Zero();
  10170. this._tempMatrix = BABYLON.Matrix.Zero();
  10171. }
  10172. TargetCamera.prototype.getFrontPosition = function (distance) {
  10173. var direction = this.getTarget().subtract(this.position);
  10174. direction.normalize();
  10175. direction.scaleInPlace(distance);
  10176. return this.globalPosition.add(direction);
  10177. };
  10178. TargetCamera.prototype._getLockedTargetPosition = function () {
  10179. if (!this.lockedTarget) {
  10180. return null;
  10181. }
  10182. return this.lockedTarget.position || this.lockedTarget;
  10183. };
  10184. // Cache
  10185. TargetCamera.prototype._initCache = function () {
  10186. _super.prototype._initCache.call(this);
  10187. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10188. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10189. };
  10190. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10191. if (!ignoreParentClass) {
  10192. _super.prototype._updateCache.call(this);
  10193. }
  10194. var lockedTargetPosition = this._getLockedTargetPosition();
  10195. if (!lockedTargetPosition) {
  10196. this._cache.lockedTarget = null;
  10197. }
  10198. else {
  10199. if (!this._cache.lockedTarget) {
  10200. this._cache.lockedTarget = lockedTargetPosition.clone();
  10201. }
  10202. else {
  10203. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10204. }
  10205. }
  10206. this._cache.rotation.copyFrom(this.rotation);
  10207. };
  10208. // Synchronized
  10209. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10210. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10211. return false;
  10212. }
  10213. var lockedTargetPosition = this._getLockedTargetPosition();
  10214. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10215. && this._cache.rotation.equals(this.rotation);
  10216. };
  10217. // Methods
  10218. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10219. var engine = this.getEngine();
  10220. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10221. };
  10222. // Target
  10223. TargetCamera.prototype.setTarget = function (target) {
  10224. this.upVector.normalize();
  10225. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10226. this._camMatrix.invert();
  10227. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10228. var vDir = target.subtract(this.position);
  10229. if (vDir.x >= 0.0) {
  10230. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10231. }
  10232. else {
  10233. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10234. }
  10235. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10236. if (isNaN(this.rotation.x)) {
  10237. this.rotation.x = 0;
  10238. }
  10239. if (isNaN(this.rotation.y)) {
  10240. this.rotation.y = 0;
  10241. }
  10242. if (isNaN(this.rotation.z)) {
  10243. this.rotation.z = 0;
  10244. }
  10245. };
  10246. TargetCamera.prototype.getTarget = function () {
  10247. return this._currentTarget;
  10248. };
  10249. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10250. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10251. };
  10252. TargetCamera.prototype._updatePosition = function () {
  10253. this.position.addInPlace(this.cameraDirection);
  10254. };
  10255. TargetCamera.prototype._checkInputs = function () {
  10256. var needToMove = this._decideIfNeedsToMove();
  10257. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10258. // Move
  10259. if (needToMove) {
  10260. this._updatePosition();
  10261. }
  10262. // Rotate
  10263. if (needToRotate) {
  10264. this.rotation.x += this.cameraRotation.x;
  10265. this.rotation.y += this.cameraRotation.y;
  10266. if (!this.noRotationConstraint) {
  10267. var limit = (Math.PI / 2) * 0.95;
  10268. if (this.rotation.x > limit)
  10269. this.rotation.x = limit;
  10270. if (this.rotation.x < -limit)
  10271. this.rotation.x = -limit;
  10272. }
  10273. }
  10274. // Inertia
  10275. if (needToMove) {
  10276. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10277. this.cameraDirection.x = 0;
  10278. }
  10279. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10280. this.cameraDirection.y = 0;
  10281. }
  10282. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10283. this.cameraDirection.z = 0;
  10284. }
  10285. this.cameraDirection.scaleInPlace(this.inertia);
  10286. }
  10287. if (needToRotate) {
  10288. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10289. this.cameraRotation.x = 0;
  10290. }
  10291. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10292. this.cameraRotation.y = 0;
  10293. }
  10294. this.cameraRotation.scaleInPlace(this.inertia);
  10295. }
  10296. _super.prototype._checkInputs.call(this);
  10297. };
  10298. TargetCamera.prototype._getViewMatrix = function () {
  10299. if (!this.lockedTarget) {
  10300. // Compute
  10301. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10302. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10303. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10304. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10305. this._lookAtTemp.invert();
  10306. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10307. }
  10308. else {
  10309. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10310. }
  10311. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10312. // Computing target and final matrix
  10313. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10314. }
  10315. else {
  10316. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10317. }
  10318. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10319. return this._viewMatrix;
  10320. };
  10321. TargetCamera.prototype._getVRViewMatrix = function () {
  10322. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10323. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10324. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10325. // Computing target and final matrix
  10326. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10327. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10328. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10329. return this._viewMatrix;
  10330. };
  10331. /**
  10332. * @override
  10333. * Override Camera.createRigCamera
  10334. */
  10335. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10336. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10337. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10338. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10339. rigCamera._cameraRigParams = {};
  10340. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10341. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10342. }
  10343. return rigCamera;
  10344. }
  10345. return null;
  10346. };
  10347. /**
  10348. * @override
  10349. * Override Camera._updateRigCameras
  10350. */
  10351. TargetCamera.prototype._updateRigCameras = function () {
  10352. switch (this.cameraRigMode) {
  10353. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10354. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10355. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10356. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10357. case BABYLON.Camera.RIG_MODE_VR:
  10358. var camLeft = this._rigCameras[0];
  10359. var camRight = this._rigCameras[1];
  10360. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10361. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10362. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10363. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10364. camLeft.position.copyFrom(this.position);
  10365. camRight.position.copyFrom(this.position);
  10366. }
  10367. else {
  10368. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10369. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10370. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10371. camLeft.setTarget(this.getTarget());
  10372. camRight.setTarget(this.getTarget());
  10373. }
  10374. break;
  10375. }
  10376. _super.prototype._updateRigCameras.call(this);
  10377. };
  10378. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10379. if (!this._rigCamTransformMatrix) {
  10380. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10381. }
  10382. var target = this.getTarget();
  10383. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10384. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10385. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10386. };
  10387. return TargetCamera;
  10388. })(BABYLON.Camera);
  10389. BABYLON.TargetCamera = TargetCamera;
  10390. })(BABYLON || (BABYLON = {}));
  10391. var BABYLON;
  10392. (function (BABYLON) {
  10393. var FreeCamera = (function (_super) {
  10394. __extends(FreeCamera, _super);
  10395. function FreeCamera(name, position, scene) {
  10396. var _this = this;
  10397. _super.call(this, name, position, scene);
  10398. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10399. this.keysUp = [38];
  10400. this.keysDown = [40];
  10401. this.keysLeft = [37];
  10402. this.keysRight = [39];
  10403. this.checkCollisions = false;
  10404. this.applyGravity = false;
  10405. this.angularSensibility = 2000.0;
  10406. this._keys = [];
  10407. this._collider = new BABYLON.Collider();
  10408. this._needMoveForGravity = false;
  10409. this._oldPosition = BABYLON.Vector3.Zero();
  10410. this._diffPosition = BABYLON.Vector3.Zero();
  10411. this._newPosition = BABYLON.Vector3.Zero();
  10412. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10413. if (collidedMesh === void 0) { collidedMesh = null; }
  10414. //TODO move this to the collision coordinator!
  10415. if (_this.getScene().workerCollisions)
  10416. newPosition.multiplyInPlace(_this._collider.radius);
  10417. var updatePosition = function (newPos) {
  10418. _this._newPosition.copyFrom(newPos);
  10419. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10420. var oldPosition = _this.position.clone();
  10421. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10422. _this.position.addInPlace(_this._diffPosition);
  10423. if (_this.onCollide && collidedMesh) {
  10424. _this.onCollide(collidedMesh);
  10425. }
  10426. }
  10427. };
  10428. updatePosition(newPosition);
  10429. };
  10430. }
  10431. // Controls
  10432. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10433. var _this = this;
  10434. var previousPosition;
  10435. var engine = this.getEngine();
  10436. if (this._attachedElement) {
  10437. return;
  10438. }
  10439. this._attachedElement = element;
  10440. if (this._onMouseDown === undefined) {
  10441. this._onMouseDown = function (evt) {
  10442. previousPosition = {
  10443. x: evt.clientX,
  10444. y: evt.clientY
  10445. };
  10446. if (!noPreventDefault) {
  10447. evt.preventDefault();
  10448. }
  10449. };
  10450. this._onMouseUp = function (evt) {
  10451. previousPosition = null;
  10452. if (!noPreventDefault) {
  10453. evt.preventDefault();
  10454. }
  10455. };
  10456. this._onMouseOut = function (evt) {
  10457. previousPosition = null;
  10458. _this._keys = [];
  10459. if (!noPreventDefault) {
  10460. evt.preventDefault();
  10461. }
  10462. };
  10463. this._onMouseMove = function (evt) {
  10464. if (!previousPosition && !engine.isPointerLock) {
  10465. return;
  10466. }
  10467. var offsetX;
  10468. var offsetY;
  10469. if (!engine.isPointerLock) {
  10470. offsetX = evt.clientX - previousPosition.x;
  10471. offsetY = evt.clientY - previousPosition.y;
  10472. }
  10473. else {
  10474. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10475. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10476. }
  10477. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10478. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10479. previousPosition = {
  10480. x: evt.clientX,
  10481. y: evt.clientY
  10482. };
  10483. if (!noPreventDefault) {
  10484. evt.preventDefault();
  10485. }
  10486. };
  10487. this._onKeyDown = function (evt) {
  10488. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10489. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10490. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10491. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10492. var index = _this._keys.indexOf(evt.keyCode);
  10493. if (index === -1) {
  10494. _this._keys.push(evt.keyCode);
  10495. }
  10496. if (!noPreventDefault) {
  10497. evt.preventDefault();
  10498. }
  10499. }
  10500. };
  10501. this._onKeyUp = function (evt) {
  10502. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10503. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10504. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10505. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10506. var index = _this._keys.indexOf(evt.keyCode);
  10507. if (index >= 0) {
  10508. _this._keys.splice(index, 1);
  10509. }
  10510. if (!noPreventDefault) {
  10511. evt.preventDefault();
  10512. }
  10513. }
  10514. };
  10515. this._onLostFocus = function () {
  10516. _this._keys = [];
  10517. };
  10518. this._reset = function () {
  10519. _this._keys = [];
  10520. previousPosition = null;
  10521. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10522. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10523. };
  10524. }
  10525. element.addEventListener("mousedown", this._onMouseDown, false);
  10526. element.addEventListener("mouseup", this._onMouseUp, false);
  10527. element.addEventListener("mouseout", this._onMouseOut, false);
  10528. element.addEventListener("mousemove", this._onMouseMove, false);
  10529. BABYLON.Tools.RegisterTopRootEvents([
  10530. { name: "keydown", handler: this._onKeyDown },
  10531. { name: "keyup", handler: this._onKeyUp },
  10532. { name: "blur", handler: this._onLostFocus }
  10533. ]);
  10534. };
  10535. FreeCamera.prototype.detachControl = function (element) {
  10536. if (this._attachedElement != element) {
  10537. return;
  10538. }
  10539. element.removeEventListener("mousedown", this._onMouseDown);
  10540. element.removeEventListener("mouseup", this._onMouseUp);
  10541. element.removeEventListener("mouseout", this._onMouseOut);
  10542. element.removeEventListener("mousemove", this._onMouseMove);
  10543. BABYLON.Tools.UnregisterTopRootEvents([
  10544. { name: "keydown", handler: this._onKeyDown },
  10545. { name: "keyup", handler: this._onKeyUp },
  10546. { name: "blur", handler: this._onLostFocus }
  10547. ]);
  10548. this._attachedElement = null;
  10549. if (this._reset) {
  10550. this._reset();
  10551. }
  10552. };
  10553. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10554. var globalPosition;
  10555. if (this.parent) {
  10556. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10557. }
  10558. else {
  10559. globalPosition = this.position;
  10560. }
  10561. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10562. this._collider.radius = this.ellipsoid;
  10563. //no need for clone, as long as gravity is not on.
  10564. var actualVelocity = velocity;
  10565. //add gravity to the velocity to prevent the dual-collision checking
  10566. if (this.applyGravity) {
  10567. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10568. actualVelocity = velocity.add(this.getScene().gravity);
  10569. }
  10570. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10571. };
  10572. FreeCamera.prototype._checkInputs = function () {
  10573. if (!this._localDirection) {
  10574. this._localDirection = BABYLON.Vector3.Zero();
  10575. this._transformedDirection = BABYLON.Vector3.Zero();
  10576. }
  10577. // Keyboard
  10578. for (var index = 0; index < this._keys.length; index++) {
  10579. var keyCode = this._keys[index];
  10580. var speed = this._computeLocalCameraSpeed();
  10581. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10582. this._localDirection.copyFromFloats(-speed, 0, 0);
  10583. }
  10584. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10585. this._localDirection.copyFromFloats(0, 0, speed);
  10586. }
  10587. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10588. this._localDirection.copyFromFloats(speed, 0, 0);
  10589. }
  10590. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10591. this._localDirection.copyFromFloats(0, 0, -speed);
  10592. }
  10593. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10594. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10595. this.cameraDirection.addInPlace(this._transformedDirection);
  10596. }
  10597. _super.prototype._checkInputs.call(this);
  10598. };
  10599. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10600. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10601. };
  10602. FreeCamera.prototype._updatePosition = function () {
  10603. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10604. this._collideWithWorld(this.cameraDirection);
  10605. }
  10606. else {
  10607. this.position.addInPlace(this.cameraDirection);
  10608. }
  10609. };
  10610. return FreeCamera;
  10611. })(BABYLON.TargetCamera);
  10612. BABYLON.FreeCamera = FreeCamera;
  10613. })(BABYLON || (BABYLON = {}));
  10614. var BABYLON;
  10615. (function (BABYLON) {
  10616. var FollowCamera = (function (_super) {
  10617. __extends(FollowCamera, _super);
  10618. function FollowCamera(name, position, scene) {
  10619. _super.call(this, name, position, scene);
  10620. this.radius = 12;
  10621. this.rotationOffset = 0;
  10622. this.heightOffset = 4;
  10623. this.cameraAcceleration = 0.05;
  10624. this.maxCameraSpeed = 20;
  10625. }
  10626. FollowCamera.prototype.getRadians = function (degrees) {
  10627. return degrees * Math.PI / 180;
  10628. };
  10629. FollowCamera.prototype.follow = function (cameraTarget) {
  10630. if (!cameraTarget)
  10631. return;
  10632. var yRotation;
  10633. if (cameraTarget.rotationQuaternion) {
  10634. var rotMatrix = new BABYLON.Matrix();
  10635. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10636. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10637. }
  10638. else {
  10639. yRotation = cameraTarget.rotation.y;
  10640. }
  10641. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10642. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10643. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10644. var dx = targetX - this.position.x;
  10645. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10646. var dz = (targetZ) - this.position.z;
  10647. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10648. var vy = dy * this.cameraAcceleration;
  10649. var vz = dz * this.cameraAcceleration * 2;
  10650. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10651. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10652. }
  10653. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10654. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10655. }
  10656. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10657. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10658. }
  10659. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10660. this.setTarget(cameraTarget.position);
  10661. };
  10662. FollowCamera.prototype._checkInputs = function () {
  10663. _super.prototype._checkInputs.call(this);
  10664. this.follow(this.target);
  10665. };
  10666. return FollowCamera;
  10667. })(BABYLON.TargetCamera);
  10668. BABYLON.FollowCamera = FollowCamera;
  10669. var ArcFollowCamera = (function (_super) {
  10670. __extends(ArcFollowCamera, _super);
  10671. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10672. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10673. this.alpha = alpha;
  10674. this.beta = beta;
  10675. this.radius = radius;
  10676. this.target = target;
  10677. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10678. this.follow();
  10679. }
  10680. ArcFollowCamera.prototype.follow = function () {
  10681. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10682. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10683. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10684. this.position = this.target.position.add(this._cartesianCoordinates);
  10685. this.setTarget(this.target.position);
  10686. };
  10687. ArcFollowCamera.prototype._checkInputs = function () {
  10688. _super.prototype._checkInputs.call(this);
  10689. this.follow();
  10690. };
  10691. return ArcFollowCamera;
  10692. })(BABYLON.TargetCamera);
  10693. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10694. })(BABYLON || (BABYLON = {}));
  10695. var BABYLON;
  10696. (function (BABYLON) {
  10697. // We're mainly based on the logic defined into the FreeCamera code
  10698. var TouchCamera = (function (_super) {
  10699. __extends(TouchCamera, _super);
  10700. function TouchCamera(name, position, scene) {
  10701. _super.call(this, name, position, scene);
  10702. this._offsetX = null;
  10703. this._offsetY = null;
  10704. this._pointerCount = 0;
  10705. this._pointerPressed = [];
  10706. this.angularSensibility = 200000.0;
  10707. this.moveSensibility = 500.0;
  10708. }
  10709. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10710. var _this = this;
  10711. var previousPosition;
  10712. if (this._attachedCanvas) {
  10713. return;
  10714. }
  10715. this._attachedCanvas = canvas;
  10716. if (this._onPointerDown === undefined) {
  10717. this._onPointerDown = function (evt) {
  10718. if (!noPreventDefault) {
  10719. evt.preventDefault();
  10720. }
  10721. _this._pointerPressed.push(evt.pointerId);
  10722. if (_this._pointerPressed.length !== 1) {
  10723. return;
  10724. }
  10725. previousPosition = {
  10726. x: evt.clientX,
  10727. y: evt.clientY
  10728. };
  10729. };
  10730. this._onPointerUp = function (evt) {
  10731. if (!noPreventDefault) {
  10732. evt.preventDefault();
  10733. }
  10734. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10735. if (index === -1) {
  10736. return;
  10737. }
  10738. _this._pointerPressed.splice(index, 1);
  10739. if (index != 0) {
  10740. return;
  10741. }
  10742. previousPosition = null;
  10743. _this._offsetX = null;
  10744. _this._offsetY = null;
  10745. };
  10746. this._onPointerMove = function (evt) {
  10747. if (!noPreventDefault) {
  10748. evt.preventDefault();
  10749. }
  10750. if (!previousPosition) {
  10751. return;
  10752. }
  10753. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10754. if (index != 0) {
  10755. return;
  10756. }
  10757. _this._offsetX = evt.clientX - previousPosition.x;
  10758. _this._offsetY = -(evt.clientY - previousPosition.y);
  10759. };
  10760. this._onLostFocus = function () {
  10761. _this._offsetX = null;
  10762. _this._offsetY = null;
  10763. };
  10764. }
  10765. canvas.addEventListener("pointerdown", this._onPointerDown);
  10766. canvas.addEventListener("pointerup", this._onPointerUp);
  10767. canvas.addEventListener("pointerout", this._onPointerUp);
  10768. canvas.addEventListener("pointermove", this._onPointerMove);
  10769. BABYLON.Tools.RegisterTopRootEvents([
  10770. { name: "blur", handler: this._onLostFocus }
  10771. ]);
  10772. };
  10773. TouchCamera.prototype.detachControl = function (canvas) {
  10774. if (this._attachedCanvas != canvas) {
  10775. return;
  10776. }
  10777. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10778. canvas.removeEventListener("pointerup", this._onPointerUp);
  10779. canvas.removeEventListener("pointerout", this._onPointerUp);
  10780. canvas.removeEventListener("pointermove", this._onPointerMove);
  10781. BABYLON.Tools.UnregisterTopRootEvents([
  10782. { name: "blur", handler: this._onLostFocus }
  10783. ]);
  10784. this._attachedCanvas = null;
  10785. };
  10786. TouchCamera.prototype._checkInputs = function () {
  10787. if (this._offsetX) {
  10788. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10789. if (this._pointerPressed.length > 1) {
  10790. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10791. }
  10792. else {
  10793. var speed = this._computeLocalCameraSpeed();
  10794. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10795. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10796. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10797. }
  10798. }
  10799. _super.prototype._checkInputs.call(this);
  10800. };
  10801. return TouchCamera;
  10802. })(BABYLON.FreeCamera);
  10803. BABYLON.TouchCamera = TouchCamera;
  10804. })(BABYLON || (BABYLON = {}));
  10805. var BABYLON;
  10806. (function (BABYLON) {
  10807. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10808. var ArcRotateCamera = (function (_super) {
  10809. __extends(ArcRotateCamera, _super);
  10810. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10811. var _this = this;
  10812. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10813. this.alpha = alpha;
  10814. this.beta = beta;
  10815. this.radius = radius;
  10816. this.target = target;
  10817. this.inertialAlphaOffset = 0;
  10818. this.inertialBetaOffset = 0;
  10819. this.inertialRadiusOffset = 0;
  10820. this.lowerAlphaLimit = null;
  10821. this.upperAlphaLimit = null;
  10822. this.lowerBetaLimit = 0.01;
  10823. this.upperBetaLimit = Math.PI;
  10824. this.lowerRadiusLimit = null;
  10825. this.upperRadiusLimit = null;
  10826. this.angularSensibilityX = 1000.0;
  10827. this.angularSensibilityY = 1000.0;
  10828. this.wheelPrecision = 3.0;
  10829. this.pinchPrecision = 2.0;
  10830. this.panningSensibility = 50.0;
  10831. this.inertialPanningX = 0;
  10832. this.inertialPanningY = 0;
  10833. this.keysUp = [38];
  10834. this.keysDown = [40];
  10835. this.keysLeft = [37];
  10836. this.keysRight = [39];
  10837. this.zoomOnFactor = 1;
  10838. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10839. this.pinchInwards = true;
  10840. this.allowUpsideDown = true;
  10841. this._keys = [];
  10842. this._viewMatrix = new BABYLON.Matrix();
  10843. this._isRightClick = false;
  10844. this._isCtrlPushed = false;
  10845. this.checkCollisions = false;
  10846. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10847. this._collider = new BABYLON.Collider();
  10848. this._previousPosition = BABYLON.Vector3.Zero();
  10849. this._collisionVelocity = BABYLON.Vector3.Zero();
  10850. this._newPosition = BABYLON.Vector3.Zero();
  10851. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10852. if (collidedMesh === void 0) { collidedMesh = null; }
  10853. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10854. newPosition.multiplyInPlace(_this._collider.radius);
  10855. }
  10856. if (!collidedMesh) {
  10857. _this._previousPosition.copyFrom(_this.position);
  10858. }
  10859. else {
  10860. _this.setPosition(_this.position);
  10861. if (_this.onCollide) {
  10862. _this.onCollide(collidedMesh);
  10863. }
  10864. }
  10865. // Recompute because of constraints
  10866. var cosa = Math.cos(_this.alpha);
  10867. var sina = Math.sin(_this.alpha);
  10868. var cosb = Math.cos(_this.beta);
  10869. var sinb = Math.sin(_this.beta);
  10870. var target = _this._getTargetPosition();
  10871. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10872. _this.position.copyFrom(_this._newPosition);
  10873. var up = _this.upVector;
  10874. if (_this.allowUpsideDown && _this.beta < 0) {
  10875. up = up.clone();
  10876. up = up.negate();
  10877. }
  10878. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10879. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10880. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10881. _this._collisionTriggered = false;
  10882. };
  10883. if (!this.target) {
  10884. this.target = BABYLON.Vector3.Zero();
  10885. }
  10886. this.getViewMatrix();
  10887. }
  10888. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10889. //deprecated angularSensibility support
  10890. get: function () {
  10891. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10892. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10893. },
  10894. //deprecated angularSensibility support
  10895. set: function (value) {
  10896. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10897. this.angularSensibilityX = value;
  10898. this.angularSensibilityY = value;
  10899. },
  10900. enumerable: true,
  10901. configurable: true
  10902. });
  10903. ArcRotateCamera.prototype._getTargetPosition = function () {
  10904. return this.target.position || this.target;
  10905. };
  10906. // Cache
  10907. ArcRotateCamera.prototype._initCache = function () {
  10908. _super.prototype._initCache.call(this);
  10909. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10910. this._cache.alpha = undefined;
  10911. this._cache.beta = undefined;
  10912. this._cache.radius = undefined;
  10913. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10914. };
  10915. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10916. if (!ignoreParentClass) {
  10917. _super.prototype._updateCache.call(this);
  10918. }
  10919. this._cache.target.copyFrom(this._getTargetPosition());
  10920. this._cache.alpha = this.alpha;
  10921. this._cache.beta = this.beta;
  10922. this._cache.radius = this.radius;
  10923. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10924. };
  10925. // Synchronized
  10926. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10927. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10928. return false;
  10929. return this._cache.target.equals(this._getTargetPosition())
  10930. && this._cache.alpha === this.alpha
  10931. && this._cache.beta === this.beta
  10932. && this._cache.radius === this.radius
  10933. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10934. };
  10935. // Methods
  10936. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10937. var _this = this;
  10938. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10939. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10940. var previousPinchDistance = 0;
  10941. var pointers = new BABYLON.SmartCollection();
  10942. if (this._attachedElement) {
  10943. return;
  10944. }
  10945. this._attachedElement = element;
  10946. var engine = this.getEngine();
  10947. if (this._onPointerDown === undefined) {
  10948. this._onPointerDown = function (evt) {
  10949. // Manage panning with right click
  10950. _this._isRightClick = evt.button === 2;
  10951. // manage pointers
  10952. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10953. cacheSoloPointer = pointers.item(evt.pointerId);
  10954. if (!noPreventDefault) {
  10955. evt.preventDefault();
  10956. }
  10957. };
  10958. this._onPointerUp = function (evt) {
  10959. cacheSoloPointer = null;
  10960. previousPinchDistance = 0;
  10961. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10962. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10963. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10964. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10965. pointers.empty();
  10966. if (!noPreventDefault) {
  10967. evt.preventDefault();
  10968. }
  10969. };
  10970. this._onContextMenu = function (evt) {
  10971. evt.preventDefault();
  10972. };
  10973. this._onPointerMove = function (evt) {
  10974. if (!noPreventDefault) {
  10975. evt.preventDefault();
  10976. }
  10977. switch (pointers.count) {
  10978. case 1:
  10979. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10980. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10981. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10982. }
  10983. else {
  10984. var offsetX = evt.clientX - cacheSoloPointer.x;
  10985. var offsetY = evt.clientY - cacheSoloPointer.y;
  10986. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10987. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10988. }
  10989. cacheSoloPointer.x = evt.clientX;
  10990. cacheSoloPointer.y = evt.clientY;
  10991. break;
  10992. case 2:
  10993. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10994. pointers.item(evt.pointerId).x = evt.clientX;
  10995. pointers.item(evt.pointerId).y = evt.clientY;
  10996. var direction = _this.pinchInwards ? 1 : -1;
  10997. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10998. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10999. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11000. if (previousPinchDistance === 0) {
  11001. previousPinchDistance = pinchSquaredDistance;
  11002. return;
  11003. }
  11004. if (pinchSquaredDistance !== previousPinchDistance) {
  11005. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11006. previousPinchDistance = pinchSquaredDistance;
  11007. }
  11008. break;
  11009. default:
  11010. if (pointers.item(evt.pointerId)) {
  11011. pointers.item(evt.pointerId).x = evt.clientX;
  11012. pointers.item(evt.pointerId).y = evt.clientY;
  11013. }
  11014. }
  11015. };
  11016. this._onMouseMove = function (evt) {
  11017. if (!engine.isPointerLock) {
  11018. return;
  11019. }
  11020. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11021. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11022. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11023. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11024. if (!noPreventDefault) {
  11025. evt.preventDefault();
  11026. }
  11027. };
  11028. this._wheel = function (event) {
  11029. var delta = 0;
  11030. if (event.wheelDelta) {
  11031. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11032. }
  11033. else if (event.detail) {
  11034. delta = -event.detail / _this.wheelPrecision;
  11035. }
  11036. if (delta)
  11037. _this.inertialRadiusOffset += delta;
  11038. if (event.preventDefault) {
  11039. if (!noPreventDefault) {
  11040. event.preventDefault();
  11041. }
  11042. }
  11043. };
  11044. this._onKeyDown = function (evt) {
  11045. _this._isCtrlPushed = evt.ctrlKey;
  11046. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11047. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11048. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11049. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11050. var index = _this._keys.indexOf(evt.keyCode);
  11051. if (index === -1) {
  11052. _this._keys.push(evt.keyCode);
  11053. }
  11054. if (evt.preventDefault) {
  11055. if (!noPreventDefault) {
  11056. evt.preventDefault();
  11057. }
  11058. }
  11059. }
  11060. };
  11061. this._onKeyUp = function (evt) {
  11062. _this._isCtrlPushed = evt.ctrlKey;
  11063. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11064. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11065. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11066. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11067. var index = _this._keys.indexOf(evt.keyCode);
  11068. if (index >= 0) {
  11069. _this._keys.splice(index, 1);
  11070. }
  11071. if (evt.preventDefault) {
  11072. if (!noPreventDefault) {
  11073. evt.preventDefault();
  11074. }
  11075. }
  11076. }
  11077. };
  11078. this._onLostFocus = function () {
  11079. _this._keys = [];
  11080. pointers.empty();
  11081. previousPinchDistance = 0;
  11082. cacheSoloPointer = null;
  11083. };
  11084. this._onGestureStart = function (e) {
  11085. if (window.MSGesture === undefined) {
  11086. return;
  11087. }
  11088. if (!_this._MSGestureHandler) {
  11089. _this._MSGestureHandler = new MSGesture();
  11090. _this._MSGestureHandler.target = element;
  11091. }
  11092. _this._MSGestureHandler.addPointer(e.pointerId);
  11093. };
  11094. this._onGesture = function (e) {
  11095. _this.radius *= e.scale;
  11096. if (e.preventDefault) {
  11097. if (!noPreventDefault) {
  11098. e.stopPropagation();
  11099. e.preventDefault();
  11100. }
  11101. }
  11102. };
  11103. this._reset = function () {
  11104. _this._keys = [];
  11105. _this.inertialAlphaOffset = 0;
  11106. _this.inertialBetaOffset = 0;
  11107. _this.inertialRadiusOffset = 0;
  11108. pointers.empty();
  11109. previousPinchDistance = 0;
  11110. cacheSoloPointer = null;
  11111. };
  11112. }
  11113. if (!useCtrlForPanning) {
  11114. element.addEventListener("contextmenu", this._onContextMenu, false);
  11115. }
  11116. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11117. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11118. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11119. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11120. element.addEventListener("mousemove", this._onMouseMove, false);
  11121. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11122. element.addEventListener("MSGestureChange", this._onGesture, false);
  11123. element.addEventListener('mousewheel', this._wheel, false);
  11124. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11125. BABYLON.Tools.RegisterTopRootEvents([
  11126. { name: "keydown", handler: this._onKeyDown },
  11127. { name: "keyup", handler: this._onKeyUp },
  11128. { name: "blur", handler: this._onLostFocus }
  11129. ]);
  11130. };
  11131. ArcRotateCamera.prototype.detachControl = function (element) {
  11132. if (this._attachedElement !== element) {
  11133. return;
  11134. }
  11135. element.removeEventListener("contextmenu", this._onContextMenu);
  11136. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11137. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11138. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11139. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11140. element.removeEventListener("mousemove", this._onMouseMove);
  11141. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11142. element.removeEventListener("MSGestureChange", this._onGesture);
  11143. element.removeEventListener('mousewheel', this._wheel);
  11144. element.removeEventListener('DOMMouseScroll', this._wheel);
  11145. BABYLON.Tools.UnregisterTopRootEvents([
  11146. { name: "keydown", handler: this._onKeyDown },
  11147. { name: "keyup", handler: this._onKeyUp },
  11148. { name: "blur", handler: this._onLostFocus }
  11149. ]);
  11150. this._MSGestureHandler = null;
  11151. this._attachedElement = null;
  11152. if (this._reset) {
  11153. this._reset();
  11154. }
  11155. };
  11156. ArcRotateCamera.prototype._checkInputs = function () {
  11157. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11158. if (this._collisionTriggered) {
  11159. return;
  11160. }
  11161. // Keyboard
  11162. for (var index = 0; index < this._keys.length; index++) {
  11163. var keyCode = this._keys[index];
  11164. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11165. this.inertialAlphaOffset -= 0.01;
  11166. }
  11167. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11168. this.inertialBetaOffset -= 0.01;
  11169. }
  11170. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11171. this.inertialAlphaOffset += 0.01;
  11172. }
  11173. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11174. this.inertialBetaOffset += 0.01;
  11175. }
  11176. }
  11177. // Inertia
  11178. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11179. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11180. this.beta += this.inertialBetaOffset;
  11181. this.radius -= this.inertialRadiusOffset;
  11182. this.inertialAlphaOffset *= this.inertia;
  11183. this.inertialBetaOffset *= this.inertia;
  11184. this.inertialRadiusOffset *= this.inertia;
  11185. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11186. this.inertialAlphaOffset = 0;
  11187. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11188. this.inertialBetaOffset = 0;
  11189. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11190. this.inertialRadiusOffset = 0;
  11191. }
  11192. // Panning inertia
  11193. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11194. if (!this._localDirection) {
  11195. this._localDirection = BABYLON.Vector3.Zero();
  11196. this._transformedDirection = BABYLON.Vector3.Zero();
  11197. }
  11198. this.inertialPanningX *= this.inertia;
  11199. this.inertialPanningY *= this.inertia;
  11200. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11201. this.inertialPanningX = 0;
  11202. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11203. this.inertialPanningY = 0;
  11204. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11205. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11206. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11207. this.target.addInPlace(this._transformedDirection);
  11208. }
  11209. // Limits
  11210. this._checkLimits();
  11211. _super.prototype._checkInputs.call(this);
  11212. };
  11213. ArcRotateCamera.prototype._checkLimits = function () {
  11214. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11215. if (this.allowUpsideDown && this.beta > Math.PI) {
  11216. this.beta = this.beta - (2 * Math.PI);
  11217. }
  11218. }
  11219. else {
  11220. if (this.beta < this.lowerBetaLimit) {
  11221. this.beta = this.lowerBetaLimit;
  11222. }
  11223. }
  11224. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11225. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11226. this.beta = this.beta + (2 * Math.PI);
  11227. }
  11228. }
  11229. else {
  11230. if (this.beta > this.upperBetaLimit) {
  11231. this.beta = this.upperBetaLimit;
  11232. }
  11233. }
  11234. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11235. this.alpha = this.lowerAlphaLimit;
  11236. }
  11237. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11238. this.alpha = this.upperAlphaLimit;
  11239. }
  11240. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11241. this.radius = this.lowerRadiusLimit;
  11242. }
  11243. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11244. this.radius = this.upperRadiusLimit;
  11245. }
  11246. };
  11247. ArcRotateCamera.prototype.setPosition = function (position) {
  11248. if (this.position.equals(position)) {
  11249. return;
  11250. }
  11251. var radiusv3 = position.subtract(this._getTargetPosition());
  11252. this.radius = radiusv3.length();
  11253. // Alpha
  11254. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11255. if (radiusv3.z < 0) {
  11256. this.alpha = 2 * Math.PI - this.alpha;
  11257. }
  11258. // Beta
  11259. this.beta = Math.acos(radiusv3.y / this.radius);
  11260. this._checkLimits();
  11261. };
  11262. ArcRotateCamera.prototype.setTarget = function (target) {
  11263. this.target = target;
  11264. };
  11265. ArcRotateCamera.prototype._getViewMatrix = function () {
  11266. // Compute
  11267. var cosa = Math.cos(this.alpha);
  11268. var sina = Math.sin(this.alpha);
  11269. var cosb = Math.cos(this.beta);
  11270. var sinb = Math.sin(this.beta);
  11271. var target = this._getTargetPosition();
  11272. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11273. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11274. this._collider.radius = this.collisionRadius;
  11275. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11276. this._collisionTriggered = true;
  11277. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11278. }
  11279. else {
  11280. this.position.copyFrom(this._newPosition);
  11281. var up = this.upVector;
  11282. if (this.allowUpsideDown && this.beta < 0) {
  11283. up = up.clone();
  11284. up = up.negate();
  11285. }
  11286. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11287. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11288. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11289. }
  11290. return this._viewMatrix;
  11291. };
  11292. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11293. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11294. meshes = meshes || this.getScene().meshes;
  11295. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11296. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11297. this.radius = distance * this.zoomOnFactor;
  11298. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11299. };
  11300. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11301. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11302. var meshesOrMinMaxVector;
  11303. var distance;
  11304. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11305. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11306. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11307. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11308. }
  11309. else {
  11310. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11311. distance = meshesOrMinMaxVectorAndDistance.distance;
  11312. }
  11313. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11314. if (!doNotUpdateMaxZ) {
  11315. this.maxZ = distance * 2;
  11316. }
  11317. };
  11318. /**
  11319. * @override
  11320. * Override Camera.createRigCamera
  11321. */
  11322. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11323. switch (this.cameraRigMode) {
  11324. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11326. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11327. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11328. case BABYLON.Camera.RIG_MODE_VR:
  11329. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11330. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11331. }
  11332. return null;
  11333. };
  11334. /**
  11335. * @override
  11336. * Override Camera._updateRigCameras
  11337. */
  11338. ArcRotateCamera.prototype._updateRigCameras = function () {
  11339. switch (this.cameraRigMode) {
  11340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11342. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11344. case BABYLON.Camera.RIG_MODE_VR:
  11345. var camLeft = this._rigCameras[0];
  11346. var camRight = this._rigCameras[1];
  11347. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11348. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11349. camLeft.beta = camRight.beta = this.beta;
  11350. camLeft.radius = camRight.radius = this.radius;
  11351. break;
  11352. }
  11353. _super.prototype._updateRigCameras.call(this);
  11354. };
  11355. return ArcRotateCamera;
  11356. })(BABYLON.TargetCamera);
  11357. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11358. })(BABYLON || (BABYLON = {}));
  11359. var BABYLON;
  11360. (function (BABYLON) {
  11361. var RenderingManager = (function () {
  11362. function RenderingManager(scene) {
  11363. this._renderingGroups = new Array();
  11364. this._scene = scene;
  11365. }
  11366. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11367. if (this._scene._activeParticleSystems.length === 0) {
  11368. return;
  11369. }
  11370. // Particles
  11371. var activeCamera = this._scene.activeCamera;
  11372. var beforeParticlesDate = BABYLON.Tools.Now;
  11373. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11374. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11375. if (particleSystem.renderingGroupId !== index) {
  11376. continue;
  11377. }
  11378. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11379. continue;
  11380. }
  11381. this._clearDepthBuffer();
  11382. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11383. this._scene._activeParticles += particleSystem.render();
  11384. }
  11385. }
  11386. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11387. };
  11388. RenderingManager.prototype._renderSprites = function (index) {
  11389. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11390. return;
  11391. }
  11392. // Sprites
  11393. var activeCamera = this._scene.activeCamera;
  11394. var beforeSpritessDate = BABYLON.Tools.Now;
  11395. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11396. var spriteManager = this._scene.spriteManagers[id];
  11397. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11398. this._clearDepthBuffer();
  11399. spriteManager.render();
  11400. }
  11401. }
  11402. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11403. };
  11404. RenderingManager.prototype._clearDepthBuffer = function () {
  11405. if (this._depthBufferAlreadyCleaned) {
  11406. return;
  11407. }
  11408. this._scene.getEngine().clear(0, false, true);
  11409. this._depthBufferAlreadyCleaned = true;
  11410. };
  11411. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11412. if (this._currentRenderSprites) {
  11413. this._renderSprites(this._currentIndex);
  11414. }
  11415. if (this._currentRenderParticles) {
  11416. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11417. }
  11418. };
  11419. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11420. this._currentActiveMeshes = activeMeshes;
  11421. this._currentRenderParticles = renderParticles;
  11422. this._currentRenderSprites = renderSprites;
  11423. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11424. this._depthBufferAlreadyCleaned = false;
  11425. var renderingGroup = this._renderingGroups[index];
  11426. var needToStepBack = false;
  11427. this._currentIndex = index;
  11428. if (renderingGroup) {
  11429. this._clearDepthBuffer();
  11430. if (!renderingGroup.onBeforeTransparentRendering) {
  11431. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11432. }
  11433. if (!renderingGroup.render(customRenderFunction)) {
  11434. this._renderingGroups.splice(index, 1);
  11435. needToStepBack = true;
  11436. this._renderSpritesAndParticles();
  11437. }
  11438. }
  11439. else {
  11440. this._renderSpritesAndParticles();
  11441. }
  11442. if (needToStepBack) {
  11443. index--;
  11444. }
  11445. }
  11446. };
  11447. RenderingManager.prototype.reset = function () {
  11448. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11449. if (renderingGroup) {
  11450. renderingGroup.prepare();
  11451. }
  11452. });
  11453. };
  11454. RenderingManager.prototype.dispatch = function (subMesh) {
  11455. var mesh = subMesh.getMesh();
  11456. var renderingGroupId = mesh.renderingGroupId || 0;
  11457. if (!this._renderingGroups[renderingGroupId]) {
  11458. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11459. }
  11460. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11461. };
  11462. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11463. return RenderingManager;
  11464. })();
  11465. BABYLON.RenderingManager = RenderingManager;
  11466. })(BABYLON || (BABYLON = {}));
  11467. var BABYLON;
  11468. (function (BABYLON) {
  11469. var RenderingGroup = (function () {
  11470. function RenderingGroup(index, scene) {
  11471. this.index = index;
  11472. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11473. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11474. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11475. this._scene = scene;
  11476. }
  11477. RenderingGroup.prototype.render = function (customRenderFunction) {
  11478. if (customRenderFunction) {
  11479. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11480. return true;
  11481. }
  11482. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11483. if (this.onBeforeTransparentRendering) {
  11484. this.onBeforeTransparentRendering();
  11485. }
  11486. return false;
  11487. }
  11488. var engine = this._scene.getEngine();
  11489. // Opaque
  11490. var subIndex;
  11491. var submesh;
  11492. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11493. submesh = this._opaqueSubMeshes.data[subIndex];
  11494. submesh.render(false);
  11495. }
  11496. // Alpha test
  11497. engine.setAlphaTesting(true);
  11498. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11499. submesh = this._alphaTestSubMeshes.data[subIndex];
  11500. submesh.render(false);
  11501. }
  11502. engine.setAlphaTesting(false);
  11503. if (this.onBeforeTransparentRendering) {
  11504. this.onBeforeTransparentRendering();
  11505. }
  11506. // Transparent
  11507. if (this._transparentSubMeshes.length) {
  11508. // Sorting
  11509. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11510. submesh = this._transparentSubMeshes.data[subIndex];
  11511. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11512. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11513. }
  11514. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11515. sortedArray.sort(function (a, b) {
  11516. // Alpha index first
  11517. if (a._alphaIndex > b._alphaIndex) {
  11518. return 1;
  11519. }
  11520. if (a._alphaIndex < b._alphaIndex) {
  11521. return -1;
  11522. }
  11523. // Then distance to camera
  11524. if (a._distanceToCamera < b._distanceToCamera) {
  11525. return 1;
  11526. }
  11527. if (a._distanceToCamera > b._distanceToCamera) {
  11528. return -1;
  11529. }
  11530. return 0;
  11531. });
  11532. // Rendering
  11533. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11534. submesh = sortedArray[subIndex];
  11535. submesh.render(true);
  11536. }
  11537. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11538. }
  11539. return true;
  11540. };
  11541. RenderingGroup.prototype.prepare = function () {
  11542. this._opaqueSubMeshes.reset();
  11543. this._transparentSubMeshes.reset();
  11544. this._alphaTestSubMeshes.reset();
  11545. };
  11546. RenderingGroup.prototype.dispatch = function (subMesh) {
  11547. var material = subMesh.getMaterial();
  11548. var mesh = subMesh.getMesh();
  11549. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11550. this._transparentSubMeshes.push(subMesh);
  11551. }
  11552. else if (material.needAlphaTesting()) {
  11553. this._alphaTestSubMeshes.push(subMesh);
  11554. }
  11555. else {
  11556. this._opaqueSubMeshes.push(subMesh); // Opaque
  11557. }
  11558. };
  11559. return RenderingGroup;
  11560. })();
  11561. BABYLON.RenderingGroup = RenderingGroup;
  11562. })(BABYLON || (BABYLON = {}));
  11563. var BABYLON;
  11564. (function (BABYLON) {
  11565. /**
  11566. * Represents a scene to be rendered by the engine.
  11567. * @see http://doc.babylonjs.com/page.php?p=21911
  11568. */
  11569. var Scene = (function () {
  11570. /**
  11571. * @constructor
  11572. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11573. */
  11574. function Scene(engine) {
  11575. // Members
  11576. this.autoClear = true;
  11577. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11578. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11579. this.forceWireframe = false;
  11580. this.forcePointsCloud = false;
  11581. this.forceShowBoundingBoxes = false;
  11582. this.animationsEnabled = true;
  11583. this.constantlyUpdateMeshUnderPointer = false;
  11584. 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
  11585. // Fog
  11586. /**
  11587. * is fog enabled on this scene.
  11588. * @type {boolean}
  11589. */
  11590. this.fogEnabled = true;
  11591. this.fogMode = Scene.FOGMODE_NONE;
  11592. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11593. this.fogDensity = 0.1;
  11594. this.fogStart = 0;
  11595. this.fogEnd = 1000.0;
  11596. // Lights
  11597. /**
  11598. * is shadow enabled on this scene.
  11599. * @type {boolean}
  11600. */
  11601. this.shadowsEnabled = true;
  11602. /**
  11603. * is light enabled on this scene.
  11604. * @type {boolean}
  11605. */
  11606. this.lightsEnabled = true;
  11607. /**
  11608. * All of the lights added to this scene.
  11609. * @see BABYLON.Light
  11610. * @type {BABYLON.Light[]}
  11611. */
  11612. this.lights = new Array();
  11613. // Cameras
  11614. /**
  11615. * All of the cameras added to this scene.
  11616. * @see BABYLON.Camera
  11617. * @type {BABYLON.Camera[]}
  11618. */
  11619. this.cameras = new Array();
  11620. this.activeCameras = new Array();
  11621. // Meshes
  11622. /**
  11623. * All of the (abstract) meshes added to this scene.
  11624. * @see BABYLON.AbstractMesh
  11625. * @type {BABYLON.AbstractMesh[]}
  11626. */
  11627. this.meshes = new Array();
  11628. // Geometries
  11629. this._geometries = new Array();
  11630. this.materials = new Array();
  11631. this.multiMaterials = new Array();
  11632. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11633. // Textures
  11634. this.texturesEnabled = true;
  11635. this.textures = new Array();
  11636. // Particles
  11637. this.particlesEnabled = true;
  11638. this.particleSystems = new Array();
  11639. // Sprites
  11640. this.spritesEnabled = true;
  11641. this.spriteManagers = new Array();
  11642. // Layers
  11643. this.layers = new Array();
  11644. // Skeletons
  11645. this.skeletonsEnabled = true;
  11646. this.skeletons = new Array();
  11647. // Lens flares
  11648. this.lensFlaresEnabled = true;
  11649. this.lensFlareSystems = new Array();
  11650. // Collisions
  11651. this.collisionsEnabled = true;
  11652. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11653. // Postprocesses
  11654. this.postProcessesEnabled = true;
  11655. // Customs render targets
  11656. this.renderTargetsEnabled = true;
  11657. this.dumpNextRenderTargets = false;
  11658. this.customRenderTargets = new Array();
  11659. // Imported meshes
  11660. this.importedMeshesFiles = new Array();
  11661. // Probes
  11662. this.probesEnabled = true;
  11663. this.reflectionProbes = new Array();
  11664. this._actionManagers = new Array();
  11665. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11666. // Procedural textures
  11667. this.proceduralTexturesEnabled = true;
  11668. this._proceduralTextures = new Array();
  11669. this.soundTracks = new Array();
  11670. this._audioEnabled = true;
  11671. this._headphone = false;
  11672. this._totalVertices = 0;
  11673. this._activeIndices = 0;
  11674. this._activeParticles = 0;
  11675. this._lastFrameDuration = 0;
  11676. this._evaluateActiveMeshesDuration = 0;
  11677. this._renderTargetsDuration = 0;
  11678. this._particlesDuration = 0;
  11679. this._renderDuration = 0;
  11680. this._spritesDuration = 0;
  11681. this._animationRatio = 0;
  11682. this._renderId = 0;
  11683. this._executeWhenReadyTimeoutId = -1;
  11684. this._toBeDisposed = new BABYLON.SmartArray(256);
  11685. this._onReadyCallbacks = new Array();
  11686. this._pendingData = []; //ANY
  11687. this._onBeforeRenderCallbacks = new Array();
  11688. this._onAfterRenderCallbacks = new Array();
  11689. this._activeMeshes = new BABYLON.SmartArray(256);
  11690. this._processedMaterials = new BABYLON.SmartArray(256);
  11691. this._renderTargets = new BABYLON.SmartArray(256);
  11692. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11693. this._activeSkeletons = new BABYLON.SmartArray(32);
  11694. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11695. this._activeBones = 0;
  11696. this._activeAnimatables = new Array();
  11697. this._transformMatrix = BABYLON.Matrix.Zero();
  11698. this._edgesRenderers = new BABYLON.SmartArray(16);
  11699. this._uniqueIdCounter = 0;
  11700. this._engine = engine;
  11701. engine.scenes.push(this);
  11702. this._renderingManager = new BABYLON.RenderingManager(this);
  11703. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11704. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11705. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11706. if (BABYLON.OutlineRenderer) {
  11707. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11708. }
  11709. this.attachControl();
  11710. this._debugLayer = new BABYLON.DebugLayer(this);
  11711. if (BABYLON.SoundTrack) {
  11712. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11713. }
  11714. //simplification queue
  11715. if (BABYLON.SimplificationQueue) {
  11716. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11717. }
  11718. //collision coordinator initialization. For now legacy per default.
  11719. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11720. }
  11721. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11722. get: function () {
  11723. return Scene._FOGMODE_NONE;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11729. get: function () {
  11730. return Scene._FOGMODE_EXP;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11736. get: function () {
  11737. return Scene._FOGMODE_EXP2;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11743. get: function () {
  11744. return Scene._FOGMODE_LINEAR;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Scene.prototype, "debugLayer", {
  11750. // Properties
  11751. get: function () {
  11752. return this._debugLayer;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11758. get: function () {
  11759. return this._workerCollisions;
  11760. },
  11761. set: function (enabled) {
  11762. enabled = (enabled && !!Worker);
  11763. this._workerCollisions = enabled;
  11764. if (this.collisionCoordinator) {
  11765. this.collisionCoordinator.destroy();
  11766. }
  11767. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11768. this.collisionCoordinator.init(this);
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11774. get: function () {
  11775. return this._selectionOctree;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11781. /**
  11782. * The mesh that is currently under the pointer.
  11783. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11784. */
  11785. get: function () {
  11786. return this._meshUnderPointer;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Scene.prototype, "pointerX", {
  11792. /**
  11793. * Current on-screen X position of the pointer
  11794. * @return {number} X position of the pointer
  11795. */
  11796. get: function () {
  11797. return this._pointerX;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Scene.prototype, "pointerY", {
  11803. /**
  11804. * Current on-screen Y position of the pointer
  11805. * @return {number} Y position of the pointer
  11806. */
  11807. get: function () {
  11808. return this._pointerY;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Scene.prototype.getCachedMaterial = function () {
  11814. return this._cachedMaterial;
  11815. };
  11816. Scene.prototype.getBoundingBoxRenderer = function () {
  11817. return this._boundingBoxRenderer;
  11818. };
  11819. Scene.prototype.getOutlineRenderer = function () {
  11820. return this._outlineRenderer;
  11821. };
  11822. Scene.prototype.getEngine = function () {
  11823. return this._engine;
  11824. };
  11825. Scene.prototype.getTotalVertices = function () {
  11826. return this._totalVertices;
  11827. };
  11828. Scene.prototype.getActiveIndices = function () {
  11829. return this._activeIndices;
  11830. };
  11831. Scene.prototype.getActiveParticles = function () {
  11832. return this._activeParticles;
  11833. };
  11834. Scene.prototype.getActiveBones = function () {
  11835. return this._activeBones;
  11836. };
  11837. // Stats
  11838. Scene.prototype.getLastFrameDuration = function () {
  11839. return this._lastFrameDuration;
  11840. };
  11841. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11842. return this._evaluateActiveMeshesDuration;
  11843. };
  11844. Scene.prototype.getActiveMeshes = function () {
  11845. return this._activeMeshes;
  11846. };
  11847. Scene.prototype.getRenderTargetsDuration = function () {
  11848. return this._renderTargetsDuration;
  11849. };
  11850. Scene.prototype.getRenderDuration = function () {
  11851. return this._renderDuration;
  11852. };
  11853. Scene.prototype.getParticlesDuration = function () {
  11854. return this._particlesDuration;
  11855. };
  11856. Scene.prototype.getSpritesDuration = function () {
  11857. return this._spritesDuration;
  11858. };
  11859. Scene.prototype.getAnimationRatio = function () {
  11860. return this._animationRatio;
  11861. };
  11862. Scene.prototype.getRenderId = function () {
  11863. return this._renderId;
  11864. };
  11865. Scene.prototype.incrementRenderId = function () {
  11866. this._renderId++;
  11867. };
  11868. Scene.prototype._updatePointerPosition = function (evt) {
  11869. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11870. this._pointerX = evt.clientX - canvasRect.left;
  11871. this._pointerY = evt.clientY - canvasRect.top;
  11872. if (this.cameraToUseForPointers) {
  11873. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11874. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11875. }
  11876. };
  11877. // Pointers handling
  11878. Scene.prototype.attachControl = function () {
  11879. var _this = this;
  11880. var spritePredicate = function (sprite) {
  11881. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11882. };
  11883. this._onPointerMove = function (evt) {
  11884. var canvas = _this._engine.getRenderingCanvas();
  11885. _this._updatePointerPosition(evt);
  11886. // Meshes
  11887. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  11888. if (pickResult.hit && pickResult.pickedMesh) {
  11889. _this._meshUnderPointer = pickResult.pickedMesh;
  11890. _this.setPointerOverMesh(pickResult.pickedMesh);
  11891. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11892. canvas.style.cursor = "pointer";
  11893. }
  11894. else {
  11895. canvas.style.cursor = "";
  11896. }
  11897. }
  11898. else {
  11899. // Sprites
  11900. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11901. if (pickResult.hit && pickResult.pickedSprite) {
  11902. canvas.style.cursor = "pointer";
  11903. }
  11904. else {
  11905. // Restore pointer
  11906. _this.setPointerOverMesh(null);
  11907. canvas.style.cursor = "";
  11908. _this._meshUnderPointer = null;
  11909. }
  11910. }
  11911. if (_this.onPointerMove) {
  11912. _this.onPointerMove(evt, pickResult);
  11913. }
  11914. };
  11915. this._onPointerDown = function (evt) {
  11916. _this._updatePointerPosition(evt);
  11917. var predicate = null;
  11918. // Meshes
  11919. if (!_this.onPointerDown) {
  11920. predicate = function (mesh) {
  11921. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11922. };
  11923. }
  11924. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11925. if (pickResult.hit && pickResult.pickedMesh) {
  11926. if (pickResult.pickedMesh.actionManager) {
  11927. switch (evt.button) {
  11928. case 0:
  11929. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11930. break;
  11931. case 1:
  11932. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11933. break;
  11934. case 2:
  11935. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11936. break;
  11937. }
  11938. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11939. }
  11940. }
  11941. if (_this.onPointerDown) {
  11942. _this.onPointerDown(evt, pickResult);
  11943. }
  11944. // Sprites
  11945. if (_this.spriteManagers.length > 0) {
  11946. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11947. if (pickResult.hit && pickResult.pickedSprite) {
  11948. if (pickResult.pickedSprite.actionManager) {
  11949. switch (evt.button) {
  11950. case 0:
  11951. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11952. break;
  11953. case 1:
  11954. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11955. break;
  11956. case 2:
  11957. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11958. break;
  11959. }
  11960. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11961. }
  11962. }
  11963. }
  11964. };
  11965. this._onPointerUp = function (evt) {
  11966. var predicate = null;
  11967. _this._updatePointerPosition(evt);
  11968. if (!_this.onPointerUp) {
  11969. predicate = function (mesh) {
  11970. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11971. };
  11972. }
  11973. // Meshes
  11974. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11975. if (pickResult.hit && pickResult.pickedMesh) {
  11976. if (pickResult.pickedMesh.actionManager) {
  11977. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11978. }
  11979. }
  11980. if (_this.onPointerUp) {
  11981. _this.onPointerUp(evt, pickResult);
  11982. }
  11983. // Sprites
  11984. if (_this.spriteManagers.length > 0) {
  11985. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11986. if (pickResult.hit && pickResult.pickedSprite) {
  11987. if (pickResult.pickedSprite.actionManager) {
  11988. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11989. }
  11990. }
  11991. }
  11992. };
  11993. this._onKeyDown = function (evt) {
  11994. if (_this.actionManager) {
  11995. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11996. }
  11997. };
  11998. this._onKeyUp = function (evt) {
  11999. if (_this.actionManager) {
  12000. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12001. }
  12002. };
  12003. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12004. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12005. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12006. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12007. // Wheel
  12008. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12009. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12010. BABYLON.Tools.RegisterTopRootEvents([
  12011. { name: "keydown", handler: this._onKeyDown },
  12012. { name: "keyup", handler: this._onKeyUp }
  12013. ]);
  12014. };
  12015. Scene.prototype.detachControl = function () {
  12016. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12017. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12018. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12019. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12020. // Wheel
  12021. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12022. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12023. BABYLON.Tools.UnregisterTopRootEvents([
  12024. { name: "keydown", handler: this._onKeyDown },
  12025. { name: "keyup", handler: this._onKeyUp }
  12026. ]);
  12027. };
  12028. // Ready
  12029. Scene.prototype.isReady = function () {
  12030. if (this._pendingData.length > 0) {
  12031. return false;
  12032. }
  12033. var index;
  12034. for (index = 0; index < this._geometries.length; index++) {
  12035. var geometry = this._geometries[index];
  12036. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12037. return false;
  12038. }
  12039. }
  12040. for (index = 0; index < this.meshes.length; index++) {
  12041. var mesh = this.meshes[index];
  12042. if (!mesh.isReady()) {
  12043. return false;
  12044. }
  12045. var mat = mesh.material;
  12046. if (mat) {
  12047. if (!mat.isReady(mesh)) {
  12048. return false;
  12049. }
  12050. }
  12051. }
  12052. return true;
  12053. };
  12054. Scene.prototype.resetCachedMaterial = function () {
  12055. this._cachedMaterial = null;
  12056. };
  12057. Scene.prototype.registerBeforeRender = function (func) {
  12058. this._onBeforeRenderCallbacks.push(func);
  12059. };
  12060. Scene.prototype.unregisterBeforeRender = function (func) {
  12061. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12062. if (index > -1) {
  12063. this._onBeforeRenderCallbacks.splice(index, 1);
  12064. }
  12065. };
  12066. Scene.prototype.registerAfterRender = function (func) {
  12067. this._onAfterRenderCallbacks.push(func);
  12068. };
  12069. Scene.prototype.unregisterAfterRender = function (func) {
  12070. var index = this._onAfterRenderCallbacks.indexOf(func);
  12071. if (index > -1) {
  12072. this._onAfterRenderCallbacks.splice(index, 1);
  12073. }
  12074. };
  12075. Scene.prototype._addPendingData = function (data) {
  12076. this._pendingData.push(data);
  12077. };
  12078. Scene.prototype._removePendingData = function (data) {
  12079. var index = this._pendingData.indexOf(data);
  12080. if (index !== -1) {
  12081. this._pendingData.splice(index, 1);
  12082. }
  12083. };
  12084. Scene.prototype.getWaitingItemsCount = function () {
  12085. return this._pendingData.length;
  12086. };
  12087. /**
  12088. * Registers a function to be executed when the scene is ready.
  12089. * @param {Function} func - the function to be executed.
  12090. */
  12091. Scene.prototype.executeWhenReady = function (func) {
  12092. var _this = this;
  12093. this._onReadyCallbacks.push(func);
  12094. if (this._executeWhenReadyTimeoutId !== -1) {
  12095. return;
  12096. }
  12097. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12098. _this._checkIsReady();
  12099. }, 150);
  12100. };
  12101. Scene.prototype._checkIsReady = function () {
  12102. var _this = this;
  12103. if (this.isReady()) {
  12104. this._onReadyCallbacks.forEach(function (func) {
  12105. func();
  12106. });
  12107. this._onReadyCallbacks = [];
  12108. this._executeWhenReadyTimeoutId = -1;
  12109. return;
  12110. }
  12111. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12112. _this._checkIsReady();
  12113. }, 150);
  12114. };
  12115. // Animations
  12116. /**
  12117. * Will start the animation sequence of a given target
  12118. * @param target - the target
  12119. * @param {number} from - from which frame should animation start
  12120. * @param {number} to - till which frame should animation run.
  12121. * @param {boolean} [loop] - should the animation loop
  12122. * @param {number} [speedRatio] - the speed in which to run the animation
  12123. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12124. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12125. * @return {BABYLON.Animatable} the animatable object created for this animation
  12126. * @see BABYLON.Animatable
  12127. * @see http://doc.babylonjs.com/page.php?p=22081
  12128. */
  12129. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12130. if (speedRatio === void 0) { speedRatio = 1.0; }
  12131. this.stopAnimation(target);
  12132. if (!animatable) {
  12133. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12134. }
  12135. // Local animations
  12136. if (target.animations) {
  12137. animatable.appendAnimations(target, target.animations);
  12138. }
  12139. // Children animations
  12140. if (target.getAnimatables) {
  12141. var animatables = target.getAnimatables();
  12142. for (var index = 0; index < animatables.length; index++) {
  12143. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12144. }
  12145. }
  12146. return animatable;
  12147. };
  12148. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12149. if (speedRatio === undefined) {
  12150. speedRatio = 1.0;
  12151. }
  12152. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12153. return animatable;
  12154. };
  12155. Scene.prototype.getAnimatableByTarget = function (target) {
  12156. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12157. if (this._activeAnimatables[index].target === target) {
  12158. return this._activeAnimatables[index];
  12159. }
  12160. }
  12161. return null;
  12162. };
  12163. /**
  12164. * Will stop the animation of the given target
  12165. * @param target - the target
  12166. * @see beginAnimation
  12167. */
  12168. Scene.prototype.stopAnimation = function (target) {
  12169. var animatable = this.getAnimatableByTarget(target);
  12170. if (animatable) {
  12171. animatable.stop();
  12172. }
  12173. };
  12174. Scene.prototype._animate = function () {
  12175. if (!this.animationsEnabled) {
  12176. return;
  12177. }
  12178. if (!this._animationStartDate) {
  12179. this._animationStartDate = BABYLON.Tools.Now;
  12180. }
  12181. // Getting time
  12182. var now = BABYLON.Tools.Now;
  12183. var delay = now - this._animationStartDate;
  12184. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12185. this._activeAnimatables[index]._animate(delay);
  12186. }
  12187. };
  12188. // Matrix
  12189. Scene.prototype.getViewMatrix = function () {
  12190. return this._viewMatrix;
  12191. };
  12192. Scene.prototype.getProjectionMatrix = function () {
  12193. return this._projectionMatrix;
  12194. };
  12195. Scene.prototype.getTransformMatrix = function () {
  12196. return this._transformMatrix;
  12197. };
  12198. Scene.prototype.setTransformMatrix = function (view, projection) {
  12199. this._viewMatrix = view;
  12200. this._projectionMatrix = projection;
  12201. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12202. };
  12203. // Methods
  12204. Scene.prototype.addMesh = function (newMesh) {
  12205. newMesh.uniqueId = this._uniqueIdCounter++;
  12206. var position = this.meshes.push(newMesh);
  12207. //notify the collision coordinator
  12208. this.collisionCoordinator.onMeshAdded(newMesh);
  12209. if (this.onNewMeshAdded) {
  12210. this.onNewMeshAdded(newMesh, position, this);
  12211. }
  12212. };
  12213. Scene.prototype.removeMesh = function (toRemove) {
  12214. var index = this.meshes.indexOf(toRemove);
  12215. if (index !== -1) {
  12216. // Remove from the scene if mesh found
  12217. this.meshes.splice(index, 1);
  12218. }
  12219. //notify the collision coordinator
  12220. this.collisionCoordinator.onMeshRemoved(toRemove);
  12221. if (this.onMeshRemoved) {
  12222. this.onMeshRemoved(toRemove);
  12223. }
  12224. return index;
  12225. };
  12226. Scene.prototype.removeSkeleton = function (toRemove) {
  12227. var index = this.skeletons.indexOf(toRemove);
  12228. if (index !== -1) {
  12229. // Remove from the scene if mesh found
  12230. this.skeletons.splice(index, 1);
  12231. }
  12232. return index;
  12233. };
  12234. Scene.prototype.removeLight = function (toRemove) {
  12235. var index = this.lights.indexOf(toRemove);
  12236. if (index !== -1) {
  12237. // Remove from the scene if mesh found
  12238. this.lights.splice(index, 1);
  12239. }
  12240. if (this.onLightRemoved) {
  12241. this.onLightRemoved(toRemove);
  12242. }
  12243. return index;
  12244. };
  12245. Scene.prototype.removeCamera = function (toRemove) {
  12246. var index = this.cameras.indexOf(toRemove);
  12247. if (index !== -1) {
  12248. // Remove from the scene if mesh found
  12249. this.cameras.splice(index, 1);
  12250. }
  12251. // Remove from activeCameras
  12252. var index2 = this.activeCameras.indexOf(toRemove);
  12253. if (index2 !== -1) {
  12254. // Remove from the scene if mesh found
  12255. this.activeCameras.splice(index2, 1);
  12256. }
  12257. // Reset the activeCamera
  12258. if (this.activeCamera === toRemove) {
  12259. if (this.cameras.length > 0) {
  12260. this.activeCamera = this.cameras[0];
  12261. }
  12262. else {
  12263. this.activeCamera = null;
  12264. }
  12265. }
  12266. if (this.onCameraRemoved) {
  12267. this.onCameraRemoved(toRemove);
  12268. }
  12269. return index;
  12270. };
  12271. Scene.prototype.addLight = function (newLight) {
  12272. newLight.uniqueId = this._uniqueIdCounter++;
  12273. var position = this.lights.push(newLight);
  12274. if (this.onNewLightAdded) {
  12275. this.onNewLightAdded(newLight, position, this);
  12276. }
  12277. };
  12278. Scene.prototype.addCamera = function (newCamera) {
  12279. newCamera.uniqueId = this._uniqueIdCounter++;
  12280. var position = this.cameras.push(newCamera);
  12281. if (this.onNewCameraAdded) {
  12282. this.onNewCameraAdded(newCamera, position, this);
  12283. }
  12284. };
  12285. /**
  12286. * sets the active camera of the scene using its ID
  12287. * @param {string} id - the camera's ID
  12288. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12289. * @see activeCamera
  12290. */
  12291. Scene.prototype.setActiveCameraByID = function (id) {
  12292. var camera = this.getCameraByID(id);
  12293. if (camera) {
  12294. this.activeCamera = camera;
  12295. return camera;
  12296. }
  12297. return null;
  12298. };
  12299. /**
  12300. * sets the active camera of the scene using its name
  12301. * @param {string} name - the camera's name
  12302. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12303. * @see activeCamera
  12304. */
  12305. Scene.prototype.setActiveCameraByName = function (name) {
  12306. var camera = this.getCameraByName(name);
  12307. if (camera) {
  12308. this.activeCamera = camera;
  12309. return camera;
  12310. }
  12311. return null;
  12312. };
  12313. /**
  12314. * get a material using its id
  12315. * @param {string} the material's ID
  12316. * @return {BABYLON.Material|null} the material or null if none found.
  12317. */
  12318. Scene.prototype.getMaterialByID = function (id) {
  12319. for (var index = 0; index < this.materials.length; index++) {
  12320. if (this.materials[index].id === id) {
  12321. return this.materials[index];
  12322. }
  12323. }
  12324. return null;
  12325. };
  12326. /**
  12327. * get a material using its name
  12328. * @param {string} the material's name
  12329. * @return {BABYLON.Material|null} the material or null if none found.
  12330. */
  12331. Scene.prototype.getMaterialByName = function (name) {
  12332. for (var index = 0; index < this.materials.length; index++) {
  12333. if (this.materials[index].name === name) {
  12334. return this.materials[index];
  12335. }
  12336. }
  12337. return null;
  12338. };
  12339. Scene.prototype.getLensFlareSystemByName = function (name) {
  12340. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12341. if (this.lensFlareSystems[index].name === name) {
  12342. return this.lensFlareSystems[index];
  12343. }
  12344. }
  12345. return null;
  12346. };
  12347. Scene.prototype.getCameraByID = function (id) {
  12348. for (var index = 0; index < this.cameras.length; index++) {
  12349. if (this.cameras[index].id === id) {
  12350. return this.cameras[index];
  12351. }
  12352. }
  12353. return null;
  12354. };
  12355. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12356. for (var index = 0; index < this.cameras.length; index++) {
  12357. if (this.cameras[index].uniqueId === uniqueId) {
  12358. return this.cameras[index];
  12359. }
  12360. }
  12361. return null;
  12362. };
  12363. /**
  12364. * get a camera using its name
  12365. * @param {string} the camera's name
  12366. * @return {BABYLON.Camera|null} the camera or null if none found.
  12367. */
  12368. Scene.prototype.getCameraByName = function (name) {
  12369. for (var index = 0; index < this.cameras.length; index++) {
  12370. if (this.cameras[index].name === name) {
  12371. return this.cameras[index];
  12372. }
  12373. }
  12374. return null;
  12375. };
  12376. /**
  12377. * get a light node using its name
  12378. * @param {string} the light's name
  12379. * @return {BABYLON.Light|null} the light or null if none found.
  12380. */
  12381. Scene.prototype.getLightByName = function (name) {
  12382. for (var index = 0; index < this.lights.length; index++) {
  12383. if (this.lights[index].name === name) {
  12384. return this.lights[index];
  12385. }
  12386. }
  12387. return null;
  12388. };
  12389. /**
  12390. * get a light node using its ID
  12391. * @param {string} the light's id
  12392. * @return {BABYLON.Light|null} the light or null if none found.
  12393. */
  12394. Scene.prototype.getLightByID = function (id) {
  12395. for (var index = 0; index < this.lights.length; index++) {
  12396. if (this.lights[index].id === id) {
  12397. return this.lights[index];
  12398. }
  12399. }
  12400. return null;
  12401. };
  12402. /**
  12403. * get a light node using its scene-generated unique ID
  12404. * @param {number} the light's unique id
  12405. * @return {BABYLON.Light|null} the light or null if none found.
  12406. */
  12407. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12408. for (var index = 0; index < this.lights.length; index++) {
  12409. if (this.lights[index].uniqueId === uniqueId) {
  12410. return this.lights[index];
  12411. }
  12412. }
  12413. return null;
  12414. };
  12415. /**
  12416. * get a geometry using its ID
  12417. * @param {string} the geometry's id
  12418. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12419. */
  12420. Scene.prototype.getGeometryByID = function (id) {
  12421. for (var index = 0; index < this._geometries.length; index++) {
  12422. if (this._geometries[index].id === id) {
  12423. return this._geometries[index];
  12424. }
  12425. }
  12426. return null;
  12427. };
  12428. /**
  12429. * add a new geometry to this scene.
  12430. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12431. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12432. * @return {boolean} was the geometry added or not
  12433. */
  12434. Scene.prototype.pushGeometry = function (geometry, force) {
  12435. if (!force && this.getGeometryByID(geometry.id)) {
  12436. return false;
  12437. }
  12438. this._geometries.push(geometry);
  12439. //notify the collision coordinator
  12440. this.collisionCoordinator.onGeometryAdded(geometry);
  12441. if (this.onGeometryAdded) {
  12442. this.onGeometryAdded(geometry);
  12443. }
  12444. return true;
  12445. };
  12446. /**
  12447. * Removes an existing geometry
  12448. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12449. * @return {boolean} was the geometry removed or not
  12450. */
  12451. Scene.prototype.removeGeometry = function (geometry) {
  12452. var index = this._geometries.indexOf(geometry);
  12453. if (index > -1) {
  12454. this._geometries.splice(index, 1);
  12455. //notify the collision coordinator
  12456. this.collisionCoordinator.onGeometryDeleted(geometry);
  12457. if (this.onGeometryRemoved) {
  12458. this.onGeometryRemoved(geometry);
  12459. }
  12460. return true;
  12461. }
  12462. return false;
  12463. };
  12464. Scene.prototype.getGeometries = function () {
  12465. return this._geometries;
  12466. };
  12467. /**
  12468. * Get the first added mesh found of a given ID
  12469. * @param {string} id - the id to search for
  12470. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12471. */
  12472. Scene.prototype.getMeshByID = function (id) {
  12473. for (var index = 0; index < this.meshes.length; index++) {
  12474. if (this.meshes[index].id === id) {
  12475. return this.meshes[index];
  12476. }
  12477. }
  12478. return null;
  12479. };
  12480. /**
  12481. * Get a mesh with its auto-generated unique id
  12482. * @param {number} uniqueId - the unique id to search for
  12483. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12484. */
  12485. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12486. for (var index = 0; index < this.meshes.length; index++) {
  12487. if (this.meshes[index].uniqueId === uniqueId) {
  12488. return this.meshes[index];
  12489. }
  12490. }
  12491. return null;
  12492. };
  12493. /**
  12494. * Get a the last added mesh found of a given ID
  12495. * @param {string} id - the id to search for
  12496. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12497. */
  12498. Scene.prototype.getLastMeshByID = function (id) {
  12499. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12500. if (this.meshes[index].id === id) {
  12501. return this.meshes[index];
  12502. }
  12503. }
  12504. return null;
  12505. };
  12506. /**
  12507. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12508. * @param {string} id - the id to search for
  12509. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12510. */
  12511. Scene.prototype.getLastEntryByID = function (id) {
  12512. var index;
  12513. for (index = this.meshes.length - 1; index >= 0; index--) {
  12514. if (this.meshes[index].id === id) {
  12515. return this.meshes[index];
  12516. }
  12517. }
  12518. for (index = this.cameras.length - 1; index >= 0; index--) {
  12519. if (this.cameras[index].id === id) {
  12520. return this.cameras[index];
  12521. }
  12522. }
  12523. for (index = this.lights.length - 1; index >= 0; index--) {
  12524. if (this.lights[index].id === id) {
  12525. return this.lights[index];
  12526. }
  12527. }
  12528. return null;
  12529. };
  12530. Scene.prototype.getNodeByID = function (id) {
  12531. var mesh = this.getMeshByID(id);
  12532. if (mesh) {
  12533. return mesh;
  12534. }
  12535. var light = this.getLightByID(id);
  12536. if (light) {
  12537. return light;
  12538. }
  12539. return this.getCameraByID(id);
  12540. };
  12541. Scene.prototype.getNodeByName = function (name) {
  12542. var mesh = this.getMeshByName(name);
  12543. if (mesh) {
  12544. return mesh;
  12545. }
  12546. var light = this.getLightByName(name);
  12547. if (light) {
  12548. return light;
  12549. }
  12550. return this.getCameraByName(name);
  12551. };
  12552. Scene.prototype.getMeshByName = function (name) {
  12553. for (var index = 0; index < this.meshes.length; index++) {
  12554. if (this.meshes[index].name === name) {
  12555. return this.meshes[index];
  12556. }
  12557. }
  12558. return null;
  12559. };
  12560. Scene.prototype.getSoundByName = function (name) {
  12561. var index;
  12562. if (BABYLON.AudioEngine) {
  12563. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12564. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12565. return this.mainSoundTrack.soundCollection[index];
  12566. }
  12567. }
  12568. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12569. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12570. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12571. return this.soundTracks[sdIndex].soundCollection[index];
  12572. }
  12573. }
  12574. }
  12575. }
  12576. return null;
  12577. };
  12578. Scene.prototype.getLastSkeletonByID = function (id) {
  12579. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12580. if (this.skeletons[index].id === id) {
  12581. return this.skeletons[index];
  12582. }
  12583. }
  12584. return null;
  12585. };
  12586. Scene.prototype.getSkeletonById = function (id) {
  12587. for (var index = 0; index < this.skeletons.length; index++) {
  12588. if (this.skeletons[index].id === id) {
  12589. return this.skeletons[index];
  12590. }
  12591. }
  12592. return null;
  12593. };
  12594. Scene.prototype.getSkeletonByName = function (name) {
  12595. for (var index = 0; index < this.skeletons.length; index++) {
  12596. if (this.skeletons[index].name === name) {
  12597. return this.skeletons[index];
  12598. }
  12599. }
  12600. return null;
  12601. };
  12602. Scene.prototype.isActiveMesh = function (mesh) {
  12603. return (this._activeMeshes.indexOf(mesh) !== -1);
  12604. };
  12605. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12606. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12607. var material = subMesh.getMaterial();
  12608. if (mesh.showSubMeshesBoundingBox) {
  12609. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12610. }
  12611. if (material) {
  12612. // Render targets
  12613. if (material.getRenderTargetTextures) {
  12614. if (this._processedMaterials.indexOf(material) === -1) {
  12615. this._processedMaterials.push(material);
  12616. this._renderTargets.concat(material.getRenderTargetTextures());
  12617. }
  12618. }
  12619. // Dispatch
  12620. this._activeIndices += subMesh.indexCount;
  12621. this._renderingManager.dispatch(subMesh);
  12622. }
  12623. }
  12624. };
  12625. Scene.prototype._evaluateActiveMeshes = function () {
  12626. this.activeCamera._activeMeshes.reset();
  12627. this._activeMeshes.reset();
  12628. this._renderingManager.reset();
  12629. this._processedMaterials.reset();
  12630. this._activeParticleSystems.reset();
  12631. this._activeSkeletons.reset();
  12632. this._softwareSkinnedMeshes.reset();
  12633. this._boundingBoxRenderer.reset();
  12634. this._edgesRenderers.reset();
  12635. if (!this._frustumPlanes) {
  12636. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12637. }
  12638. else {
  12639. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12640. }
  12641. // Meshes
  12642. var meshes;
  12643. var len;
  12644. if (this._selectionOctree) {
  12645. var selection = this._selectionOctree.select(this._frustumPlanes);
  12646. meshes = selection.data;
  12647. len = selection.length;
  12648. }
  12649. else {
  12650. len = this.meshes.length;
  12651. meshes = this.meshes;
  12652. }
  12653. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12654. var mesh = meshes[meshIndex];
  12655. if (mesh.isBlocked) {
  12656. continue;
  12657. }
  12658. this._totalVertices += mesh.getTotalVertices();
  12659. if (!mesh.isReady() || !mesh.isEnabled()) {
  12660. continue;
  12661. }
  12662. mesh.computeWorldMatrix();
  12663. // Intersections
  12664. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12665. this._meshesForIntersections.pushNoDuplicate(mesh);
  12666. }
  12667. // Switch to current LOD
  12668. var meshLOD = mesh.getLOD(this.activeCamera);
  12669. if (!meshLOD) {
  12670. continue;
  12671. }
  12672. mesh._preActivate();
  12673. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12674. this._activeMeshes.push(mesh);
  12675. this.activeCamera._activeMeshes.push(mesh);
  12676. mesh._activate(this._renderId);
  12677. this._activeMesh(meshLOD);
  12678. }
  12679. }
  12680. // Particle systems
  12681. var beforeParticlesDate = BABYLON.Tools.Now;
  12682. if (this.particlesEnabled) {
  12683. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12684. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12685. var particleSystem = this.particleSystems[particleIndex];
  12686. if (!particleSystem.isStarted()) {
  12687. continue;
  12688. }
  12689. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12690. this._activeParticleSystems.push(particleSystem);
  12691. particleSystem.animate();
  12692. }
  12693. }
  12694. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12695. }
  12696. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12697. };
  12698. Scene.prototype._activeMesh = function (mesh) {
  12699. if (mesh.skeleton && this.skeletonsEnabled) {
  12700. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12701. if (!mesh.computeBonesUsingShaders) {
  12702. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12703. }
  12704. }
  12705. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12706. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12707. }
  12708. if (mesh._edgesRenderer) {
  12709. this._edgesRenderers.push(mesh._edgesRenderer);
  12710. }
  12711. if (mesh && mesh.subMeshes) {
  12712. // Submeshes Octrees
  12713. var len;
  12714. var subMeshes;
  12715. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12716. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12717. len = intersections.length;
  12718. subMeshes = intersections.data;
  12719. }
  12720. else {
  12721. subMeshes = mesh.subMeshes;
  12722. len = subMeshes.length;
  12723. }
  12724. for (var subIndex = 0; subIndex < len; subIndex++) {
  12725. var subMesh = subMeshes[subIndex];
  12726. this._evaluateSubMesh(subMesh, mesh);
  12727. }
  12728. }
  12729. };
  12730. Scene.prototype.updateTransformMatrix = function (force) {
  12731. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12732. };
  12733. Scene.prototype._renderForCamera = function (camera) {
  12734. var engine = this._engine;
  12735. this.activeCamera = camera;
  12736. if (!this.activeCamera)
  12737. throw new Error("Active camera not set");
  12738. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12739. // Viewport
  12740. engine.setViewport(this.activeCamera.viewport);
  12741. // Camera
  12742. this.resetCachedMaterial();
  12743. this._renderId++;
  12744. this.updateTransformMatrix();
  12745. if (this.beforeCameraRender) {
  12746. this.beforeCameraRender(this.activeCamera);
  12747. }
  12748. // Meshes
  12749. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12750. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12751. this._evaluateActiveMeshes();
  12752. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12753. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12754. // Skeletons
  12755. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12756. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12757. skeleton.prepare();
  12758. }
  12759. // Software skinning
  12760. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12761. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12762. mesh.applySkeleton(mesh.skeleton);
  12763. }
  12764. // Render targets
  12765. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12766. if (this.renderTargetsEnabled) {
  12767. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12768. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12769. var renderTarget = this._renderTargets.data[renderIndex];
  12770. if (renderTarget._shouldRender()) {
  12771. this._renderId++;
  12772. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12773. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12774. }
  12775. }
  12776. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12777. this._renderId++;
  12778. }
  12779. if (this._renderTargets.length > 0) {
  12780. engine.restoreDefaultFramebuffer();
  12781. }
  12782. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12783. // Prepare Frame
  12784. this.postProcessManager._prepareFrame();
  12785. var beforeRenderDate = BABYLON.Tools.Now;
  12786. // Backgrounds
  12787. var layerIndex;
  12788. var layer;
  12789. if (this.layers.length) {
  12790. engine.setDepthBuffer(false);
  12791. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12792. layer = this.layers[layerIndex];
  12793. if (layer.isBackground) {
  12794. layer.render();
  12795. }
  12796. }
  12797. engine.setDepthBuffer(true);
  12798. }
  12799. // Render
  12800. BABYLON.Tools.StartPerformanceCounter("Main render");
  12801. this._renderingManager.render(null, null, true, true);
  12802. BABYLON.Tools.EndPerformanceCounter("Main render");
  12803. // Bounding boxes
  12804. this._boundingBoxRenderer.render();
  12805. // Edges
  12806. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12807. this._edgesRenderers.data[edgesRendererIndex].render();
  12808. }
  12809. // Lens flares
  12810. if (this.lensFlaresEnabled) {
  12811. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12812. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12813. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12814. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12815. lensFlareSystem.render();
  12816. }
  12817. }
  12818. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12819. }
  12820. // Foregrounds
  12821. if (this.layers.length) {
  12822. engine.setDepthBuffer(false);
  12823. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12824. layer = this.layers[layerIndex];
  12825. if (!layer.isBackground) {
  12826. layer.render();
  12827. }
  12828. }
  12829. engine.setDepthBuffer(true);
  12830. }
  12831. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12832. // Finalize frame
  12833. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12834. // Update camera
  12835. this.activeCamera._updateFromScene();
  12836. // Reset some special arrays
  12837. this._renderTargets.reset();
  12838. if (this.afterCameraRender) {
  12839. this.afterCameraRender(this.activeCamera);
  12840. }
  12841. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12842. };
  12843. Scene.prototype._processSubCameras = function (camera) {
  12844. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12845. this._renderForCamera(camera);
  12846. return;
  12847. }
  12848. // rig cameras
  12849. for (var index = 0; index < camera._rigCameras.length; index++) {
  12850. this._renderForCamera(camera._rigCameras[index]);
  12851. }
  12852. this.activeCamera = camera;
  12853. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12854. // Update camera
  12855. this.activeCamera._updateFromScene();
  12856. };
  12857. Scene.prototype._checkIntersections = function () {
  12858. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12859. var sourceMesh = this._meshesForIntersections.data[index];
  12860. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12861. var action = sourceMesh.actionManager.actions[actionIndex];
  12862. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12863. var parameters = action.getTriggerParameter();
  12864. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12865. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12866. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12867. if (areIntersecting && currentIntersectionInProgress === -1) {
  12868. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12869. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12870. sourceMesh._intersectionsInProgress.push(otherMesh);
  12871. }
  12872. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12873. sourceMesh._intersectionsInProgress.push(otherMesh);
  12874. }
  12875. }
  12876. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12877. //They intersected, and now they don't.
  12878. //is this trigger an exit trigger? execute an event.
  12879. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12880. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12881. }
  12882. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12883. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12884. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12885. }
  12886. }
  12887. }
  12888. }
  12889. }
  12890. };
  12891. Scene.prototype.render = function () {
  12892. var startDate = BABYLON.Tools.Now;
  12893. this._particlesDuration = 0;
  12894. this._spritesDuration = 0;
  12895. this._activeParticles = 0;
  12896. this._renderDuration = 0;
  12897. this._renderTargetsDuration = 0;
  12898. this._evaluateActiveMeshesDuration = 0;
  12899. this._totalVertices = 0;
  12900. this._activeIndices = 0;
  12901. this._activeBones = 0;
  12902. this.getEngine().resetDrawCalls();
  12903. this._meshesForIntersections.reset();
  12904. this.resetCachedMaterial();
  12905. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12906. // Actions
  12907. if (this.actionManager) {
  12908. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12909. }
  12910. //Simplification Queue
  12911. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12912. this.simplificationQueue.executeNext();
  12913. }
  12914. // Animations
  12915. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12916. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12917. this._animate();
  12918. // Physics
  12919. if (this._physicsEngine) {
  12920. BABYLON.Tools.StartPerformanceCounter("Physics");
  12921. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12922. BABYLON.Tools.EndPerformanceCounter("Physics");
  12923. }
  12924. // Before render
  12925. if (this.beforeRender) {
  12926. this.beforeRender();
  12927. }
  12928. var callbackIndex;
  12929. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12930. this._onBeforeRenderCallbacks[callbackIndex]();
  12931. }
  12932. // Customs render targets
  12933. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12934. var engine = this.getEngine();
  12935. var currentActiveCamera = this.activeCamera;
  12936. if (this.renderTargetsEnabled) {
  12937. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12938. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12939. var renderTarget = this.customRenderTargets[customIndex];
  12940. if (renderTarget._shouldRender()) {
  12941. this._renderId++;
  12942. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12943. if (!this.activeCamera)
  12944. throw new Error("Active camera not set");
  12945. // Viewport
  12946. engine.setViewport(this.activeCamera.viewport);
  12947. // Camera
  12948. this.updateTransformMatrix();
  12949. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12950. }
  12951. }
  12952. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12953. this._renderId++;
  12954. }
  12955. if (this.customRenderTargets.length > 0) {
  12956. engine.restoreDefaultFramebuffer();
  12957. }
  12958. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12959. this.activeCamera = currentActiveCamera;
  12960. // Procedural textures
  12961. if (this.proceduralTexturesEnabled) {
  12962. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12963. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12964. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12965. if (proceduralTexture._shouldRender()) {
  12966. proceduralTexture.render();
  12967. }
  12968. }
  12969. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12970. }
  12971. // Clear
  12972. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12973. // Shadows
  12974. if (this.shadowsEnabled) {
  12975. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12976. var light = this.lights[lightIndex];
  12977. var shadowGenerator = light.getShadowGenerator();
  12978. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12979. this._renderTargets.push(shadowGenerator.getShadowMap());
  12980. }
  12981. }
  12982. }
  12983. // Depth renderer
  12984. if (this._depthRenderer) {
  12985. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12986. }
  12987. // RenderPipeline
  12988. this.postProcessRenderPipelineManager.update();
  12989. // Multi-cameras?
  12990. if (this.activeCameras.length > 0) {
  12991. var currentRenderId = this._renderId;
  12992. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12993. this._renderId = currentRenderId;
  12994. this._processSubCameras(this.activeCameras[cameraIndex]);
  12995. }
  12996. }
  12997. else {
  12998. if (!this.activeCamera) {
  12999. throw new Error("No camera defined");
  13000. }
  13001. this._processSubCameras(this.activeCamera);
  13002. }
  13003. // Intersection checks
  13004. this._checkIntersections();
  13005. // Update the audio listener attached to the camera
  13006. if (BABYLON.AudioEngine) {
  13007. this._updateAudioParameters();
  13008. }
  13009. // After render
  13010. if (this.afterRender) {
  13011. this.afterRender();
  13012. }
  13013. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13014. this._onAfterRenderCallbacks[callbackIndex]();
  13015. }
  13016. // Cleaning
  13017. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13018. this._toBeDisposed.data[index].dispose();
  13019. this._toBeDisposed[index] = null;
  13020. }
  13021. this._toBeDisposed.reset();
  13022. if (this.dumpNextRenderTargets) {
  13023. this.dumpNextRenderTargets = false;
  13024. }
  13025. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13026. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13027. };
  13028. Scene.prototype._updateAudioParameters = function () {
  13029. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13030. return;
  13031. }
  13032. var listeningCamera;
  13033. var audioEngine = BABYLON.Engine.audioEngine;
  13034. if (this.activeCameras.length > 0) {
  13035. listeningCamera = this.activeCameras[0];
  13036. }
  13037. else {
  13038. listeningCamera = this.activeCamera;
  13039. }
  13040. if (listeningCamera && audioEngine.canUseWebAudio) {
  13041. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13042. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13043. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13044. cameraDirection.normalize();
  13045. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13046. var i;
  13047. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13048. var sound = this.mainSoundTrack.soundCollection[i];
  13049. if (sound.useCustomAttenuation) {
  13050. sound.updateDistanceFromListener();
  13051. }
  13052. }
  13053. for (i = 0; i < this.soundTracks.length; i++) {
  13054. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13055. sound = this.soundTracks[i].soundCollection[j];
  13056. if (sound.useCustomAttenuation) {
  13057. sound.updateDistanceFromListener();
  13058. }
  13059. }
  13060. }
  13061. }
  13062. };
  13063. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13064. // Audio
  13065. get: function () {
  13066. return this._audioEnabled;
  13067. },
  13068. set: function (value) {
  13069. this._audioEnabled = value;
  13070. if (BABYLON.AudioEngine) {
  13071. if (this._audioEnabled) {
  13072. this._enableAudio();
  13073. }
  13074. else {
  13075. this._disableAudio();
  13076. }
  13077. }
  13078. },
  13079. enumerable: true,
  13080. configurable: true
  13081. });
  13082. Scene.prototype._disableAudio = function () {
  13083. var i;
  13084. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13085. this.mainSoundTrack.soundCollection[i].pause();
  13086. }
  13087. for (i = 0; i < this.soundTracks.length; i++) {
  13088. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13089. this.soundTracks[i].soundCollection[j].pause();
  13090. }
  13091. }
  13092. };
  13093. Scene.prototype._enableAudio = function () {
  13094. var i;
  13095. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13096. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13097. this.mainSoundTrack.soundCollection[i].play();
  13098. }
  13099. }
  13100. for (i = 0; i < this.soundTracks.length; i++) {
  13101. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13102. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13103. this.soundTracks[i].soundCollection[j].play();
  13104. }
  13105. }
  13106. }
  13107. };
  13108. Object.defineProperty(Scene.prototype, "headphone", {
  13109. get: function () {
  13110. return this._headphone;
  13111. },
  13112. set: function (value) {
  13113. this._headphone = value;
  13114. if (BABYLON.AudioEngine) {
  13115. if (this._headphone) {
  13116. this._switchAudioModeForHeadphones();
  13117. }
  13118. else {
  13119. this._switchAudioModeForNormalSpeakers();
  13120. }
  13121. }
  13122. },
  13123. enumerable: true,
  13124. configurable: true
  13125. });
  13126. Scene.prototype._switchAudioModeForHeadphones = function () {
  13127. this.mainSoundTrack.switchPanningModelToHRTF();
  13128. for (var i = 0; i < this.soundTracks.length; i++) {
  13129. this.soundTracks[i].switchPanningModelToHRTF();
  13130. }
  13131. };
  13132. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13133. this.mainSoundTrack.switchPanningModelToEqualPower();
  13134. for (var i = 0; i < this.soundTracks.length; i++) {
  13135. this.soundTracks[i].switchPanningModelToEqualPower();
  13136. }
  13137. };
  13138. Scene.prototype.enableDepthRenderer = function () {
  13139. if (this._depthRenderer) {
  13140. return this._depthRenderer;
  13141. }
  13142. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13143. return this._depthRenderer;
  13144. };
  13145. Scene.prototype.disableDepthRenderer = function () {
  13146. if (!this._depthRenderer) {
  13147. return;
  13148. }
  13149. this._depthRenderer.dispose();
  13150. this._depthRenderer = null;
  13151. };
  13152. Scene.prototype.dispose = function () {
  13153. this.beforeRender = null;
  13154. this.afterRender = null;
  13155. this.skeletons = [];
  13156. this._boundingBoxRenderer.dispose();
  13157. if (this._depthRenderer) {
  13158. this._depthRenderer.dispose();
  13159. }
  13160. // Debug layer
  13161. this.debugLayer.hide();
  13162. // Events
  13163. if (this.onDispose) {
  13164. this.onDispose();
  13165. }
  13166. this._onBeforeRenderCallbacks = [];
  13167. this._onAfterRenderCallbacks = [];
  13168. this.detachControl();
  13169. // Release sounds & sounds tracks
  13170. if (BABYLON.AudioEngine) {
  13171. this.disposeSounds();
  13172. }
  13173. // Detach cameras
  13174. var canvas = this._engine.getRenderingCanvas();
  13175. var index;
  13176. for (index = 0; index < this.cameras.length; index++) {
  13177. this.cameras[index].detachControl(canvas);
  13178. }
  13179. // Release lights
  13180. while (this.lights.length) {
  13181. this.lights[0].dispose();
  13182. }
  13183. // Release meshes
  13184. while (this.meshes.length) {
  13185. this.meshes[0].dispose(true);
  13186. }
  13187. // Release cameras
  13188. while (this.cameras.length) {
  13189. this.cameras[0].dispose();
  13190. }
  13191. // Release materials
  13192. while (this.materials.length) {
  13193. this.materials[0].dispose();
  13194. }
  13195. // Release particles
  13196. while (this.particleSystems.length) {
  13197. this.particleSystems[0].dispose();
  13198. }
  13199. // Release sprites
  13200. while (this.spriteManagers.length) {
  13201. this.spriteManagers[0].dispose();
  13202. }
  13203. // Release layers
  13204. while (this.layers.length) {
  13205. this.layers[0].dispose();
  13206. }
  13207. // Release textures
  13208. while (this.textures.length) {
  13209. this.textures[0].dispose();
  13210. }
  13211. // Post-processes
  13212. this.postProcessManager.dispose();
  13213. // Physics
  13214. if (this._physicsEngine) {
  13215. this.disablePhysicsEngine();
  13216. }
  13217. // Remove from engine
  13218. index = this._engine.scenes.indexOf(this);
  13219. if (index > -1) {
  13220. this._engine.scenes.splice(index, 1);
  13221. }
  13222. this._engine.wipeCaches();
  13223. };
  13224. // Release sounds & sounds tracks
  13225. Scene.prototype.disposeSounds = function () {
  13226. this.mainSoundTrack.dispose();
  13227. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13228. this.soundTracks[scIndex].dispose();
  13229. }
  13230. };
  13231. // Octrees
  13232. Scene.prototype.getWorldExtends = function () {
  13233. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13234. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13235. for (var index = 0; index < this.meshes.length; index++) {
  13236. var mesh = this.meshes[index];
  13237. mesh.computeWorldMatrix(true);
  13238. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13239. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13240. BABYLON.Tools.CheckExtends(minBox, min, max);
  13241. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13242. }
  13243. return {
  13244. min: min,
  13245. max: max
  13246. };
  13247. };
  13248. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13249. if (maxCapacity === void 0) { maxCapacity = 64; }
  13250. if (maxDepth === void 0) { maxDepth = 2; }
  13251. if (!this._selectionOctree) {
  13252. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13253. }
  13254. var worldExtends = this.getWorldExtends();
  13255. // Update octree
  13256. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13257. return this._selectionOctree;
  13258. };
  13259. // Picking
  13260. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13261. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13262. var engine = this._engine;
  13263. if (!camera) {
  13264. if (!this.activeCamera)
  13265. throw new Error("Active camera not set");
  13266. camera = this.activeCamera;
  13267. }
  13268. var cameraViewport = camera.viewport;
  13269. var viewport = cameraViewport.toGlobal(engine);
  13270. // Moving coordinates to local viewport world
  13271. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13272. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13273. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13274. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13275. };
  13276. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13277. var engine = this._engine;
  13278. if (!camera) {
  13279. if (!this.activeCamera)
  13280. throw new Error("Active camera not set");
  13281. camera = this.activeCamera;
  13282. }
  13283. var cameraViewport = camera.viewport;
  13284. var viewport = cameraViewport.toGlobal(engine);
  13285. var identity = BABYLON.Matrix.Identity();
  13286. // Moving coordinates to local viewport world
  13287. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13288. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13289. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13290. };
  13291. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13292. var pickingInfo = null;
  13293. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13294. var mesh = this.meshes[meshIndex];
  13295. if (predicate) {
  13296. if (!predicate(mesh)) {
  13297. continue;
  13298. }
  13299. }
  13300. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13301. continue;
  13302. }
  13303. var world = mesh.getWorldMatrix();
  13304. var ray = rayFunction(world);
  13305. var result = mesh.intersects(ray, fastCheck);
  13306. if (!result || !result.hit)
  13307. continue;
  13308. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13309. continue;
  13310. pickingInfo = result;
  13311. if (fastCheck) {
  13312. break;
  13313. }
  13314. }
  13315. return pickingInfo || new BABYLON.PickingInfo();
  13316. };
  13317. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13318. var pickingInfo = null;
  13319. camera = camera || this.activeCamera;
  13320. if (this.spriteManagers.length > 0) {
  13321. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13322. var spriteManager = this.spriteManagers[spriteIndex];
  13323. if (!spriteManager.isPickable) {
  13324. continue;
  13325. }
  13326. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13327. if (!result || !result.hit)
  13328. continue;
  13329. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13330. continue;
  13331. pickingInfo = result;
  13332. if (fastCheck) {
  13333. break;
  13334. }
  13335. }
  13336. }
  13337. return pickingInfo || new BABYLON.PickingInfo();
  13338. };
  13339. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13340. var _this = this;
  13341. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13342. /// <param name="x">X position on screen</param>
  13343. /// <param name="y">Y position on screen</param>
  13344. /// <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>
  13345. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13346. /// <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>
  13347. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13348. };
  13349. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13350. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13351. /// <param name="x">X position on screen</param>
  13352. /// <param name="y">Y position on screen</param>
  13353. /// <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>
  13354. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13355. /// <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>
  13356. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13357. };
  13358. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13359. var _this = this;
  13360. return this._internalPick(function (world) {
  13361. if (!_this._pickWithRayInverseMatrix) {
  13362. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13363. }
  13364. world.invertToRef(_this._pickWithRayInverseMatrix);
  13365. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13366. }, predicate, fastCheck);
  13367. };
  13368. Scene.prototype.setPointerOverMesh = function (mesh) {
  13369. if (this._pointerOverMesh === mesh) {
  13370. return;
  13371. }
  13372. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13373. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13374. }
  13375. this._pointerOverMesh = mesh;
  13376. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13377. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13378. }
  13379. };
  13380. Scene.prototype.getPointerOverMesh = function () {
  13381. return this._pointerOverMesh;
  13382. };
  13383. // Physics
  13384. Scene.prototype.getPhysicsEngine = function () {
  13385. return this._physicsEngine;
  13386. };
  13387. /**
  13388. * Enables physics to the current scene
  13389. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13390. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13391. * @return {boolean} was the physics engine initialized
  13392. */
  13393. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13394. if (this._physicsEngine) {
  13395. return true;
  13396. }
  13397. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13398. if (!this._physicsEngine.isSupported()) {
  13399. this._physicsEngine = null;
  13400. return false;
  13401. }
  13402. this._physicsEngine._initialize(gravity);
  13403. return true;
  13404. };
  13405. Scene.prototype.disablePhysicsEngine = function () {
  13406. if (!this._physicsEngine) {
  13407. return;
  13408. }
  13409. this._physicsEngine.dispose();
  13410. this._physicsEngine = undefined;
  13411. };
  13412. Scene.prototype.isPhysicsEnabled = function () {
  13413. return this._physicsEngine !== undefined;
  13414. };
  13415. /**
  13416. * Sets the gravity of the physics engine (and NOT of the scene)
  13417. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13418. */
  13419. Scene.prototype.setGravity = function (gravity) {
  13420. if (!this._physicsEngine) {
  13421. return;
  13422. }
  13423. this._physicsEngine._setGravity(gravity);
  13424. };
  13425. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13426. if (parts.parts) {
  13427. options = parts;
  13428. parts = parts.parts;
  13429. }
  13430. if (!this._physicsEngine) {
  13431. return null;
  13432. }
  13433. for (var index = 0; index < parts.length; index++) {
  13434. var mesh = parts[index].mesh;
  13435. mesh._physicImpostor = parts[index].impostor;
  13436. mesh._physicsMass = options.mass / parts.length;
  13437. mesh._physicsFriction = options.friction;
  13438. mesh._physicRestitution = options.restitution;
  13439. }
  13440. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13441. };
  13442. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13443. for (var index = 0; index < compound.parts.length; index++) {
  13444. var mesh = compound.parts[index].mesh;
  13445. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13446. this._physicsEngine._unregisterMesh(mesh);
  13447. }
  13448. };
  13449. // Misc.
  13450. Scene.prototype.createDefaultCameraOrLight = function () {
  13451. // Light
  13452. if (this.lights.length === 0) {
  13453. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13454. }
  13455. // Camera
  13456. if (!this.activeCamera) {
  13457. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13458. // Compute position
  13459. var worldExtends = this.getWorldExtends();
  13460. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13461. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13462. camera.setTarget(worldCenter);
  13463. this.activeCamera = camera;
  13464. }
  13465. };
  13466. // Tags
  13467. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13468. if (tagsQuery === undefined) {
  13469. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13470. return list;
  13471. }
  13472. var listByTags = [];
  13473. forEach = forEach || (function (item) { return; });
  13474. for (var i in list) {
  13475. var item = list[i];
  13476. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13477. listByTags.push(item);
  13478. forEach(item);
  13479. }
  13480. }
  13481. return listByTags;
  13482. };
  13483. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13484. return this._getByTags(this.meshes, tagsQuery, forEach);
  13485. };
  13486. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13487. return this._getByTags(this.cameras, tagsQuery, forEach);
  13488. };
  13489. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13490. return this._getByTags(this.lights, tagsQuery, forEach);
  13491. };
  13492. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13493. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13494. };
  13495. // Statics
  13496. Scene._FOGMODE_NONE = 0;
  13497. Scene._FOGMODE_EXP = 1;
  13498. Scene._FOGMODE_EXP2 = 2;
  13499. Scene._FOGMODE_LINEAR = 3;
  13500. Scene.MinDeltaTime = 1.0;
  13501. Scene.MaxDeltaTime = 1000.0;
  13502. return Scene;
  13503. })();
  13504. BABYLON.Scene = Scene;
  13505. })(BABYLON || (BABYLON = {}));
  13506. var BABYLON;
  13507. (function (BABYLON) {
  13508. var VertexBuffer = (function () {
  13509. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13510. if (engine instanceof BABYLON.Mesh) {
  13511. this._engine = engine.getScene().getEngine();
  13512. }
  13513. else {
  13514. this._engine = engine;
  13515. }
  13516. this._updatable = updatable;
  13517. this._data = data;
  13518. if (!postponeInternalCreation) {
  13519. this.create();
  13520. }
  13521. this._kind = kind;
  13522. if (stride) {
  13523. this._strideSize = stride;
  13524. return;
  13525. }
  13526. // Deduce stride from kind
  13527. switch (kind) {
  13528. case VertexBuffer.PositionKind:
  13529. this._strideSize = 3;
  13530. break;
  13531. case VertexBuffer.NormalKind:
  13532. this._strideSize = 3;
  13533. break;
  13534. case VertexBuffer.UVKind:
  13535. case VertexBuffer.UV2Kind:
  13536. case VertexBuffer.UV3Kind:
  13537. case VertexBuffer.UV4Kind:
  13538. case VertexBuffer.UV5Kind:
  13539. case VertexBuffer.UV6Kind:
  13540. this._strideSize = 2;
  13541. break;
  13542. case VertexBuffer.ColorKind:
  13543. this._strideSize = 4;
  13544. break;
  13545. case VertexBuffer.MatricesIndicesKind:
  13546. case VertexBuffer.MatricesIndicesExtraKind:
  13547. this._strideSize = 4;
  13548. break;
  13549. case VertexBuffer.MatricesWeightsKind:
  13550. case VertexBuffer.MatricesWeightsExtraKind:
  13551. this._strideSize = 4;
  13552. break;
  13553. }
  13554. }
  13555. // Properties
  13556. VertexBuffer.prototype.isUpdatable = function () {
  13557. return this._updatable;
  13558. };
  13559. VertexBuffer.prototype.getData = function () {
  13560. return this._data;
  13561. };
  13562. VertexBuffer.prototype.getBuffer = function () {
  13563. return this._buffer;
  13564. };
  13565. VertexBuffer.prototype.getStrideSize = function () {
  13566. return this._strideSize;
  13567. };
  13568. // Methods
  13569. VertexBuffer.prototype.create = function (data) {
  13570. if (!data && this._buffer) {
  13571. return; // nothing to do
  13572. }
  13573. data = data || this._data;
  13574. if (!this._buffer) {
  13575. if (this._updatable) {
  13576. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13577. }
  13578. else {
  13579. this._buffer = this._engine.createVertexBuffer(data);
  13580. }
  13581. }
  13582. if (this._updatable) {
  13583. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13584. this._data = data;
  13585. }
  13586. };
  13587. VertexBuffer.prototype.update = function (data) {
  13588. this.create(data);
  13589. };
  13590. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13591. if (!this._buffer) {
  13592. return;
  13593. }
  13594. if (this._updatable) {
  13595. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13596. this._data = null;
  13597. }
  13598. };
  13599. VertexBuffer.prototype.dispose = function () {
  13600. if (!this._buffer) {
  13601. return;
  13602. }
  13603. if (this._engine._releaseBuffer(this._buffer)) {
  13604. this._buffer = null;
  13605. }
  13606. };
  13607. Object.defineProperty(VertexBuffer, "PositionKind", {
  13608. get: function () {
  13609. return VertexBuffer._PositionKind;
  13610. },
  13611. enumerable: true,
  13612. configurable: true
  13613. });
  13614. Object.defineProperty(VertexBuffer, "NormalKind", {
  13615. get: function () {
  13616. return VertexBuffer._NormalKind;
  13617. },
  13618. enumerable: true,
  13619. configurable: true
  13620. });
  13621. Object.defineProperty(VertexBuffer, "UVKind", {
  13622. get: function () {
  13623. return VertexBuffer._UVKind;
  13624. },
  13625. enumerable: true,
  13626. configurable: true
  13627. });
  13628. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13629. get: function () {
  13630. return VertexBuffer._UV2Kind;
  13631. },
  13632. enumerable: true,
  13633. configurable: true
  13634. });
  13635. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13636. get: function () {
  13637. return VertexBuffer._UV3Kind;
  13638. },
  13639. enumerable: true,
  13640. configurable: true
  13641. });
  13642. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13643. get: function () {
  13644. return VertexBuffer._UV4Kind;
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13650. get: function () {
  13651. return VertexBuffer._UV5Kind;
  13652. },
  13653. enumerable: true,
  13654. configurable: true
  13655. });
  13656. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13657. get: function () {
  13658. return VertexBuffer._UV6Kind;
  13659. },
  13660. enumerable: true,
  13661. configurable: true
  13662. });
  13663. Object.defineProperty(VertexBuffer, "ColorKind", {
  13664. get: function () {
  13665. return VertexBuffer._ColorKind;
  13666. },
  13667. enumerable: true,
  13668. configurable: true
  13669. });
  13670. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13671. get: function () {
  13672. return VertexBuffer._MatricesIndicesKind;
  13673. },
  13674. enumerable: true,
  13675. configurable: true
  13676. });
  13677. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13678. get: function () {
  13679. return VertexBuffer._MatricesWeightsKind;
  13680. },
  13681. enumerable: true,
  13682. configurable: true
  13683. });
  13684. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  13685. get: function () {
  13686. return VertexBuffer._MatricesIndicesExtraKind;
  13687. },
  13688. enumerable: true,
  13689. configurable: true
  13690. });
  13691. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  13692. get: function () {
  13693. return VertexBuffer._MatricesWeightsExtraKind;
  13694. },
  13695. enumerable: true,
  13696. configurable: true
  13697. });
  13698. // Enums
  13699. VertexBuffer._PositionKind = "position";
  13700. VertexBuffer._NormalKind = "normal";
  13701. VertexBuffer._UVKind = "uv";
  13702. VertexBuffer._UV2Kind = "uv2";
  13703. VertexBuffer._UV3Kind = "uv3";
  13704. VertexBuffer._UV4Kind = "uv4";
  13705. VertexBuffer._UV5Kind = "uv5";
  13706. VertexBuffer._UV6Kind = "uv6";
  13707. VertexBuffer._ColorKind = "color";
  13708. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13709. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13710. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  13711. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  13712. return VertexBuffer;
  13713. })();
  13714. BABYLON.VertexBuffer = VertexBuffer;
  13715. })(BABYLON || (BABYLON = {}));
  13716. var BABYLON;
  13717. (function (BABYLON) {
  13718. /**
  13719. * Creates an instance based on a source mesh.
  13720. */
  13721. var InstancedMesh = (function (_super) {
  13722. __extends(InstancedMesh, _super);
  13723. function InstancedMesh(name, source) {
  13724. _super.call(this, name, source.getScene());
  13725. source.instances.push(this);
  13726. this._sourceMesh = source;
  13727. this.position.copyFrom(source.position);
  13728. this.rotation.copyFrom(source.rotation);
  13729. this.scaling.copyFrom(source.scaling);
  13730. if (source.rotationQuaternion) {
  13731. this.rotationQuaternion = source.rotationQuaternion.clone();
  13732. }
  13733. this.infiniteDistance = source.infiniteDistance;
  13734. this.setPivotMatrix(source.getPivotMatrix());
  13735. this.refreshBoundingInfo();
  13736. this._syncSubMeshes();
  13737. }
  13738. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13739. // Methods
  13740. get: function () {
  13741. return this._sourceMesh.receiveShadows;
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. Object.defineProperty(InstancedMesh.prototype, "material", {
  13747. get: function () {
  13748. return this._sourceMesh.material;
  13749. },
  13750. enumerable: true,
  13751. configurable: true
  13752. });
  13753. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13754. get: function () {
  13755. return this._sourceMesh.visibility;
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13761. get: function () {
  13762. return this._sourceMesh.skeleton;
  13763. },
  13764. enumerable: true,
  13765. configurable: true
  13766. });
  13767. InstancedMesh.prototype.getTotalVertices = function () {
  13768. return this._sourceMesh.getTotalVertices();
  13769. };
  13770. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13771. get: function () {
  13772. return this._sourceMesh;
  13773. },
  13774. enumerable: true,
  13775. configurable: true
  13776. });
  13777. InstancedMesh.prototype.getVerticesData = function (kind) {
  13778. return this._sourceMesh.getVerticesData(kind);
  13779. };
  13780. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13781. return this._sourceMesh.isVerticesDataPresent(kind);
  13782. };
  13783. InstancedMesh.prototype.getIndices = function () {
  13784. return this._sourceMesh.getIndices();
  13785. };
  13786. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13787. get: function () {
  13788. return this._sourceMesh._positions;
  13789. },
  13790. enumerable: true,
  13791. configurable: true
  13792. });
  13793. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13794. var meshBB = this._sourceMesh.getBoundingInfo();
  13795. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13796. this._updateBoundingInfo();
  13797. };
  13798. InstancedMesh.prototype._preActivate = function () {
  13799. if (this._currentLOD) {
  13800. this._currentLOD._preActivate();
  13801. }
  13802. };
  13803. InstancedMesh.prototype._activate = function (renderId) {
  13804. if (this._currentLOD) {
  13805. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13806. }
  13807. };
  13808. InstancedMesh.prototype.getLOD = function (camera) {
  13809. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13810. if (this._currentLOD === this.sourceMesh) {
  13811. return this;
  13812. }
  13813. return this._currentLOD;
  13814. };
  13815. InstancedMesh.prototype._syncSubMeshes = function () {
  13816. this.releaseSubMeshes();
  13817. if (this._sourceMesh.subMeshes) {
  13818. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13819. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13820. }
  13821. }
  13822. };
  13823. InstancedMesh.prototype._generatePointsArray = function () {
  13824. return this._sourceMesh._generatePointsArray();
  13825. };
  13826. // Clone
  13827. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13828. var result = this._sourceMesh.createInstance(name);
  13829. // Deep copy
  13830. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13831. // Bounding info
  13832. this.refreshBoundingInfo();
  13833. // Parent
  13834. if (newParent) {
  13835. result.parent = newParent;
  13836. }
  13837. if (!doNotCloneChildren) {
  13838. // Children
  13839. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13840. var mesh = this.getScene().meshes[index];
  13841. if (mesh.parent === this) {
  13842. mesh.clone(mesh.name, result);
  13843. }
  13844. }
  13845. }
  13846. result.computeWorldMatrix(true);
  13847. return result;
  13848. };
  13849. // Dispoe
  13850. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13851. // Remove from mesh
  13852. var index = this._sourceMesh.instances.indexOf(this);
  13853. this._sourceMesh.instances.splice(index, 1);
  13854. _super.prototype.dispose.call(this, doNotRecurse);
  13855. };
  13856. return InstancedMesh;
  13857. })(BABYLON.AbstractMesh);
  13858. BABYLON.InstancedMesh = InstancedMesh;
  13859. })(BABYLON || (BABYLON = {}));
  13860. var BABYLON;
  13861. (function (BABYLON) {
  13862. var _InstancesBatch = (function () {
  13863. function _InstancesBatch() {
  13864. this.mustReturn = false;
  13865. this.visibleInstances = new Array();
  13866. this.renderSelf = new Array();
  13867. }
  13868. return _InstancesBatch;
  13869. })();
  13870. BABYLON._InstancesBatch = _InstancesBatch;
  13871. var Mesh = (function (_super) {
  13872. __extends(Mesh, _super);
  13873. /**
  13874. * @constructor
  13875. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13876. * @param {Scene} scene - The scene to add this mesh to.
  13877. * @param {Node} parent - The parent of this mesh, if it has one
  13878. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13879. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13880. * When false, achieved by calling a clone(), also passing False.
  13881. * This will make creation of children, recursive.
  13882. */
  13883. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13884. if (parent === void 0) { parent = null; }
  13885. _super.call(this, name, scene);
  13886. // Members
  13887. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13888. this.instances = new Array();
  13889. this._LODLevels = new Array();
  13890. this._onBeforeRenderCallbacks = new Array();
  13891. this._onAfterRenderCallbacks = new Array();
  13892. this._visibleInstances = {};
  13893. this._renderIdForInstances = new Array();
  13894. this._batchCache = new _InstancesBatch();
  13895. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13896. this._sideOrientation = Mesh._DEFAULTSIDE;
  13897. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13898. if (source) {
  13899. // Geometry
  13900. if (source._geometry) {
  13901. source._geometry.applyToMesh(this);
  13902. }
  13903. // Deep copy
  13904. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13905. this.id = name + "." + source.id;
  13906. // Material
  13907. this.material = source.material;
  13908. var index;
  13909. if (!doNotCloneChildren) {
  13910. // Children
  13911. for (index = 0; index < scene.meshes.length; index++) {
  13912. var mesh = scene.meshes[index];
  13913. if (mesh.parent === source) {
  13914. // doNotCloneChildren is always going to be False
  13915. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13916. }
  13917. }
  13918. }
  13919. // Particles
  13920. for (index = 0; index < scene.particleSystems.length; index++) {
  13921. var system = scene.particleSystems[index];
  13922. if (system.emitter === source) {
  13923. system.clone(system.name, this);
  13924. }
  13925. }
  13926. this.computeWorldMatrix(true);
  13927. }
  13928. // Parent
  13929. if (parent !== null) {
  13930. this.parent = parent;
  13931. }
  13932. }
  13933. Object.defineProperty(Mesh, "FRONTSIDE", {
  13934. get: function () {
  13935. return Mesh._FRONTSIDE;
  13936. },
  13937. enumerable: true,
  13938. configurable: true
  13939. });
  13940. Object.defineProperty(Mesh, "BACKSIDE", {
  13941. get: function () {
  13942. return Mesh._BACKSIDE;
  13943. },
  13944. enumerable: true,
  13945. configurable: true
  13946. });
  13947. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13948. get: function () {
  13949. return Mesh._DOUBLESIDE;
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13955. get: function () {
  13956. return Mesh._DEFAULTSIDE;
  13957. },
  13958. enumerable: true,
  13959. configurable: true
  13960. });
  13961. Object.defineProperty(Mesh, "NO_CAP", {
  13962. get: function () {
  13963. return Mesh._NO_CAP;
  13964. },
  13965. enumerable: true,
  13966. configurable: true
  13967. });
  13968. Object.defineProperty(Mesh, "CAP_START", {
  13969. get: function () {
  13970. return Mesh._CAP_START;
  13971. },
  13972. enumerable: true,
  13973. configurable: true
  13974. });
  13975. Object.defineProperty(Mesh, "CAP_END", {
  13976. get: function () {
  13977. return Mesh._CAP_END;
  13978. },
  13979. enumerable: true,
  13980. configurable: true
  13981. });
  13982. Object.defineProperty(Mesh, "CAP_ALL", {
  13983. get: function () {
  13984. return Mesh._CAP_ALL;
  13985. },
  13986. enumerable: true,
  13987. configurable: true
  13988. });
  13989. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13990. // Methods
  13991. get: function () {
  13992. return this._LODLevels.length > 0;
  13993. },
  13994. enumerable: true,
  13995. configurable: true
  13996. });
  13997. Mesh.prototype._sortLODLevels = function () {
  13998. this._LODLevels.sort(function (a, b) {
  13999. if (a.distance < b.distance) {
  14000. return 1;
  14001. }
  14002. if (a.distance > b.distance) {
  14003. return -1;
  14004. }
  14005. return 0;
  14006. });
  14007. };
  14008. /**
  14009. * Add a mesh as LOD level triggered at the given distance.
  14010. * @param {number} distance - the distance from the center of the object to show this level
  14011. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14012. * @return {BABYLON.Mesh} this mesh (for chaining)
  14013. */
  14014. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14015. if (mesh && mesh._masterMesh) {
  14016. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14017. return this;
  14018. }
  14019. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14020. this._LODLevels.push(level);
  14021. if (mesh) {
  14022. mesh._masterMesh = this;
  14023. }
  14024. this._sortLODLevels();
  14025. return this;
  14026. };
  14027. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14028. for (var index = 0; index < this._LODLevels.length; index++) {
  14029. var level = this._LODLevels[index];
  14030. if (level.distance === distance) {
  14031. return level.mesh;
  14032. }
  14033. }
  14034. return null;
  14035. };
  14036. /**
  14037. * Remove a mesh from the LOD array
  14038. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14039. * @return {BABYLON.Mesh} this mesh (for chaining)
  14040. */
  14041. Mesh.prototype.removeLODLevel = function (mesh) {
  14042. for (var index = 0; index < this._LODLevels.length; index++) {
  14043. if (this._LODLevels[index].mesh === mesh) {
  14044. this._LODLevels.splice(index, 1);
  14045. if (mesh) {
  14046. mesh._masterMesh = null;
  14047. }
  14048. }
  14049. }
  14050. this._sortLODLevels();
  14051. return this;
  14052. };
  14053. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14054. if (!this._LODLevels || this._LODLevels.length === 0) {
  14055. return this;
  14056. }
  14057. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14058. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14059. if (this.onLODLevelSelection) {
  14060. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14061. }
  14062. return this;
  14063. }
  14064. for (var index = 0; index < this._LODLevels.length; index++) {
  14065. var level = this._LODLevels[index];
  14066. if (level.distance < distanceToCamera) {
  14067. if (level.mesh) {
  14068. level.mesh._preActivate();
  14069. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14070. }
  14071. if (this.onLODLevelSelection) {
  14072. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14073. }
  14074. return level.mesh;
  14075. }
  14076. }
  14077. if (this.onLODLevelSelection) {
  14078. this.onLODLevelSelection(distanceToCamera, this, this);
  14079. }
  14080. return this;
  14081. };
  14082. Object.defineProperty(Mesh.prototype, "geometry", {
  14083. get: function () {
  14084. return this._geometry;
  14085. },
  14086. enumerable: true,
  14087. configurable: true
  14088. });
  14089. Mesh.prototype.getTotalVertices = function () {
  14090. if (!this._geometry) {
  14091. return 0;
  14092. }
  14093. return this._geometry.getTotalVertices();
  14094. };
  14095. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14096. if (!this._geometry) {
  14097. return null;
  14098. }
  14099. return this._geometry.getVerticesData(kind, copyWhenShared);
  14100. };
  14101. Mesh.prototype.getVertexBuffer = function (kind) {
  14102. if (!this._geometry) {
  14103. return undefined;
  14104. }
  14105. return this._geometry.getVertexBuffer(kind);
  14106. };
  14107. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14108. if (!this._geometry) {
  14109. if (this._delayInfo) {
  14110. return this._delayInfo.indexOf(kind) !== -1;
  14111. }
  14112. return false;
  14113. }
  14114. return this._geometry.isVerticesDataPresent(kind);
  14115. };
  14116. Mesh.prototype.getVerticesDataKinds = function () {
  14117. if (!this._geometry) {
  14118. var result = [];
  14119. if (this._delayInfo) {
  14120. for (var kind in this._delayInfo) {
  14121. result.push(kind);
  14122. }
  14123. }
  14124. return result;
  14125. }
  14126. return this._geometry.getVerticesDataKinds();
  14127. };
  14128. Mesh.prototype.getTotalIndices = function () {
  14129. if (!this._geometry) {
  14130. return 0;
  14131. }
  14132. return this._geometry.getTotalIndices();
  14133. };
  14134. Mesh.prototype.getIndices = function (copyWhenShared) {
  14135. if (!this._geometry) {
  14136. return [];
  14137. }
  14138. return this._geometry.getIndices(copyWhenShared);
  14139. };
  14140. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14141. get: function () {
  14142. return this._masterMesh !== null && this._masterMesh !== undefined;
  14143. },
  14144. enumerable: true,
  14145. configurable: true
  14146. });
  14147. Mesh.prototype.isReady = function () {
  14148. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14149. return false;
  14150. }
  14151. return _super.prototype.isReady.call(this);
  14152. };
  14153. Mesh.prototype.isDisposed = function () {
  14154. return this._isDisposed;
  14155. };
  14156. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14157. get: function () {
  14158. return this._sideOrientation;
  14159. },
  14160. set: function (sideO) {
  14161. this._sideOrientation = sideO;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14167. get: function () {
  14168. return this._areNormalsFrozen;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14174. Mesh.prototype.freezeNormals = function () {
  14175. this._areNormalsFrozen = true;
  14176. };
  14177. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14178. Mesh.prototype.unfreezeNormals = function () {
  14179. this._areNormalsFrozen = false;
  14180. };
  14181. // Methods
  14182. Mesh.prototype._preActivate = function () {
  14183. var sceneRenderId = this.getScene().getRenderId();
  14184. if (this._preActivateId === sceneRenderId) {
  14185. return;
  14186. }
  14187. this._preActivateId = sceneRenderId;
  14188. this._visibleInstances = null;
  14189. };
  14190. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14191. if (!this._visibleInstances) {
  14192. this._visibleInstances = {};
  14193. this._visibleInstances.defaultRenderId = renderId;
  14194. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14195. }
  14196. if (!this._visibleInstances[renderId]) {
  14197. this._visibleInstances[renderId] = new Array();
  14198. }
  14199. this._visibleInstances[renderId].push(instance);
  14200. };
  14201. Mesh.prototype.refreshBoundingInfo = function () {
  14202. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14203. if (data) {
  14204. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14205. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14206. }
  14207. if (this.subMeshes) {
  14208. for (var index = 0; index < this.subMeshes.length; index++) {
  14209. this.subMeshes[index].refreshBoundingInfo();
  14210. }
  14211. }
  14212. this._updateBoundingInfo();
  14213. };
  14214. Mesh.prototype._createGlobalSubMesh = function () {
  14215. var totalVertices = this.getTotalVertices();
  14216. if (!totalVertices || !this.getIndices()) {
  14217. return null;
  14218. }
  14219. this.releaseSubMeshes();
  14220. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14221. };
  14222. Mesh.prototype.subdivide = function (count) {
  14223. if (count < 1) {
  14224. return;
  14225. }
  14226. var totalIndices = this.getTotalIndices();
  14227. var subdivisionSize = (totalIndices / count) | 0;
  14228. var offset = 0;
  14229. // Ensure that subdivisionSize is a multiple of 3
  14230. while (subdivisionSize % 3 !== 0) {
  14231. subdivisionSize++;
  14232. }
  14233. this.releaseSubMeshes();
  14234. for (var index = 0; index < count; index++) {
  14235. if (offset >= totalIndices) {
  14236. break;
  14237. }
  14238. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14239. offset += subdivisionSize;
  14240. }
  14241. this.synchronizeInstances();
  14242. };
  14243. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14244. if (!this._geometry) {
  14245. var vertexData = new BABYLON.VertexData();
  14246. vertexData.set(data, kind);
  14247. var scene = this.getScene();
  14248. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14249. }
  14250. else {
  14251. this._geometry.setVerticesData(kind, data, updatable, stride);
  14252. }
  14253. };
  14254. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14255. if (!this._geometry) {
  14256. return;
  14257. }
  14258. if (!makeItUnique) {
  14259. this._geometry.updateVerticesData(kind, data, updateExtends);
  14260. }
  14261. else {
  14262. this.makeGeometryUnique();
  14263. this.updateVerticesData(kind, data, updateExtends, false);
  14264. }
  14265. };
  14266. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14267. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14268. if (!this._geometry) {
  14269. return;
  14270. }
  14271. if (!makeItUnique) {
  14272. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14273. }
  14274. else {
  14275. this.makeGeometryUnique();
  14276. this.updateVerticesDataDirectly(kind, data, offset, false);
  14277. }
  14278. };
  14279. // Mesh positions update function :
  14280. // updates the mesh positions according to the positionFunction returned values.
  14281. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14282. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14283. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14284. if (computeNormals === void 0) { computeNormals = true; }
  14285. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14286. positionFunction(positions);
  14287. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14288. if (computeNormals) {
  14289. var indices = this.getIndices();
  14290. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14291. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14292. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14293. }
  14294. };
  14295. Mesh.prototype.makeGeometryUnique = function () {
  14296. if (!this._geometry) {
  14297. return;
  14298. }
  14299. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14300. geometry.applyToMesh(this);
  14301. };
  14302. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14303. if (!this._geometry) {
  14304. var vertexData = new BABYLON.VertexData();
  14305. vertexData.indices = indices;
  14306. var scene = this.getScene();
  14307. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14308. }
  14309. else {
  14310. this._geometry.setIndices(indices, totalVertices);
  14311. }
  14312. };
  14313. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14314. var engine = this.getScene().getEngine();
  14315. // Wireframe
  14316. var indexToBind;
  14317. switch (fillMode) {
  14318. case BABYLON.Material.PointFillMode:
  14319. indexToBind = null;
  14320. break;
  14321. case BABYLON.Material.WireFrameFillMode:
  14322. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14323. break;
  14324. default:
  14325. case BABYLON.Material.TriangleFillMode:
  14326. indexToBind = this._geometry.getIndexBuffer();
  14327. break;
  14328. }
  14329. // VBOs
  14330. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14331. };
  14332. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14333. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14334. return;
  14335. }
  14336. var engine = this.getScene().getEngine();
  14337. // Draw order
  14338. switch (fillMode) {
  14339. case BABYLON.Material.PointFillMode:
  14340. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14341. break;
  14342. case BABYLON.Material.WireFrameFillMode:
  14343. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14344. break;
  14345. default:
  14346. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14347. }
  14348. };
  14349. Mesh.prototype.registerBeforeRender = function (func) {
  14350. this._onBeforeRenderCallbacks.push(func);
  14351. };
  14352. Mesh.prototype.unregisterBeforeRender = function (func) {
  14353. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14354. if (index > -1) {
  14355. this._onBeforeRenderCallbacks.splice(index, 1);
  14356. }
  14357. };
  14358. Mesh.prototype.registerAfterRender = function (func) {
  14359. this._onAfterRenderCallbacks.push(func);
  14360. };
  14361. Mesh.prototype.unregisterAfterRender = function (func) {
  14362. var index = this._onAfterRenderCallbacks.indexOf(func);
  14363. if (index > -1) {
  14364. this._onAfterRenderCallbacks.splice(index, 1);
  14365. }
  14366. };
  14367. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14368. var scene = this.getScene();
  14369. this._batchCache.mustReturn = false;
  14370. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14371. this._batchCache.visibleInstances[subMeshId] = null;
  14372. if (this._visibleInstances) {
  14373. var currentRenderId = scene.getRenderId();
  14374. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14375. var selfRenderId = this._renderId;
  14376. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14377. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14378. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14379. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14380. }
  14381. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14382. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14383. this._batchCache.mustReturn = true;
  14384. return this._batchCache;
  14385. }
  14386. if (currentRenderId !== selfRenderId) {
  14387. this._batchCache.renderSelf[subMeshId] = false;
  14388. }
  14389. }
  14390. this._renderIdForInstances[subMeshId] = currentRenderId;
  14391. }
  14392. return this._batchCache;
  14393. };
  14394. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14395. var visibleInstances = batch.visibleInstances[subMesh._id];
  14396. var matricesCount = visibleInstances.length + 1;
  14397. var bufferSize = matricesCount * 16 * 4;
  14398. while (this._instancesBufferSize < bufferSize) {
  14399. this._instancesBufferSize *= 2;
  14400. }
  14401. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14402. if (this._worldMatricesInstancesBuffer) {
  14403. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14404. }
  14405. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14406. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14407. }
  14408. var offset = 0;
  14409. var instancesCount = 0;
  14410. var world = this.getWorldMatrix();
  14411. if (batch.renderSelf[subMesh._id]) {
  14412. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14413. offset += 16;
  14414. instancesCount++;
  14415. }
  14416. if (visibleInstances) {
  14417. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14418. var instance = visibleInstances[instanceIndex];
  14419. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14420. offset += 16;
  14421. instancesCount++;
  14422. }
  14423. }
  14424. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14425. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14426. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14427. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14428. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14429. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14430. this._draw(subMesh, fillMode, instancesCount);
  14431. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14432. };
  14433. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14434. var scene = this.getScene();
  14435. var engine = scene.getEngine();
  14436. if (hardwareInstancedRendering) {
  14437. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14438. }
  14439. else {
  14440. if (batch.renderSelf[subMesh._id]) {
  14441. // Draw
  14442. if (onBeforeDraw) {
  14443. onBeforeDraw(false, this.getWorldMatrix());
  14444. }
  14445. this._draw(subMesh, fillMode);
  14446. }
  14447. if (batch.visibleInstances[subMesh._id]) {
  14448. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14449. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14450. // World
  14451. var world = instance.getWorldMatrix();
  14452. if (onBeforeDraw) {
  14453. onBeforeDraw(true, world);
  14454. }
  14455. // Draw
  14456. this._draw(subMesh, fillMode);
  14457. }
  14458. }
  14459. }
  14460. };
  14461. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14462. var scene = this.getScene();
  14463. // Managing instances
  14464. var batch = this._getInstancesRenderList(subMesh._id);
  14465. if (batch.mustReturn) {
  14466. return;
  14467. }
  14468. // Checking geometry state
  14469. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14470. return;
  14471. }
  14472. var callbackIndex;
  14473. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14474. this._onBeforeRenderCallbacks[callbackIndex](this);
  14475. }
  14476. var engine = scene.getEngine();
  14477. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14478. // Material
  14479. var effectiveMaterial = subMesh.getMaterial();
  14480. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14481. return;
  14482. }
  14483. // Outline - step 1
  14484. var savedDepthWrite = engine.getDepthWrite();
  14485. if (this.renderOutline) {
  14486. engine.setDepthWrite(false);
  14487. scene.getOutlineRenderer().render(subMesh, batch);
  14488. engine.setDepthWrite(savedDepthWrite);
  14489. }
  14490. effectiveMaterial._preBind();
  14491. var effect = effectiveMaterial.getEffect();
  14492. // Bind
  14493. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14494. this._bind(subMesh, effect, fillMode);
  14495. var world = this.getWorldMatrix();
  14496. effectiveMaterial.bind(world, this);
  14497. // Alpha mode
  14498. if (enableAlphaMode) {
  14499. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14500. }
  14501. // Draw
  14502. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14503. if (isInstance) {
  14504. effectiveMaterial.bindOnlyWorldMatrix(world);
  14505. }
  14506. });
  14507. // Unbind
  14508. effectiveMaterial.unbind();
  14509. // Outline - step 2
  14510. if (this.renderOutline && savedDepthWrite) {
  14511. engine.setDepthWrite(true);
  14512. engine.setColorWrite(false);
  14513. scene.getOutlineRenderer().render(subMesh, batch);
  14514. engine.setColorWrite(true);
  14515. }
  14516. // Overlay
  14517. if (this.renderOverlay) {
  14518. var currentMode = engine.getAlphaMode();
  14519. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14520. scene.getOutlineRenderer().render(subMesh, batch, true);
  14521. engine.setAlphaMode(currentMode);
  14522. }
  14523. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14524. this._onAfterRenderCallbacks[callbackIndex](this);
  14525. }
  14526. };
  14527. Mesh.prototype.getEmittedParticleSystems = function () {
  14528. var results = new Array();
  14529. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14530. var particleSystem = this.getScene().particleSystems[index];
  14531. if (particleSystem.emitter === this) {
  14532. results.push(particleSystem);
  14533. }
  14534. }
  14535. return results;
  14536. };
  14537. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14538. var results = new Array();
  14539. var descendants = this.getDescendants();
  14540. descendants.push(this);
  14541. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14542. var particleSystem = this.getScene().particleSystems[index];
  14543. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14544. results.push(particleSystem);
  14545. }
  14546. }
  14547. return results;
  14548. };
  14549. Mesh.prototype.getChildren = function () {
  14550. var results = [];
  14551. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14552. var mesh = this.getScene().meshes[index];
  14553. if (mesh.parent === this) {
  14554. results.push(mesh);
  14555. }
  14556. }
  14557. return results;
  14558. };
  14559. Mesh.prototype._checkDelayState = function () {
  14560. var _this = this;
  14561. var that = this;
  14562. var scene = this.getScene();
  14563. if (this._geometry) {
  14564. this._geometry.load(scene);
  14565. }
  14566. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14567. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14568. scene._addPendingData(that);
  14569. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14570. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14571. if (data instanceof ArrayBuffer) {
  14572. _this._delayLoadingFunction(data, _this);
  14573. }
  14574. else {
  14575. _this._delayLoadingFunction(JSON.parse(data), _this);
  14576. }
  14577. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14578. scene._removePendingData(_this);
  14579. }, function () { }, scene.database, getBinaryData);
  14580. }
  14581. };
  14582. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14583. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14584. return false;
  14585. }
  14586. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14587. return false;
  14588. }
  14589. this._checkDelayState();
  14590. return true;
  14591. };
  14592. Mesh.prototype.setMaterialByID = function (id) {
  14593. var materials = this.getScene().materials;
  14594. var index;
  14595. for (index = 0; index < materials.length; index++) {
  14596. if (materials[index].id === id) {
  14597. this.material = materials[index];
  14598. return;
  14599. }
  14600. }
  14601. // Multi
  14602. var multiMaterials = this.getScene().multiMaterials;
  14603. for (index = 0; index < multiMaterials.length; index++) {
  14604. if (multiMaterials[index].id === id) {
  14605. this.material = multiMaterials[index];
  14606. return;
  14607. }
  14608. }
  14609. };
  14610. Mesh.prototype.getAnimatables = function () {
  14611. var results = [];
  14612. if (this.material) {
  14613. results.push(this.material);
  14614. }
  14615. if (this.skeleton) {
  14616. results.push(this.skeleton);
  14617. }
  14618. return results;
  14619. };
  14620. // Geometry
  14621. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14622. // Position
  14623. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14624. return;
  14625. }
  14626. this._resetPointsArrayCache();
  14627. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14628. var temp = [];
  14629. var index;
  14630. for (index = 0; index < data.length; index += 3) {
  14631. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14632. }
  14633. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14634. // Normals
  14635. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14636. return;
  14637. }
  14638. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14639. temp = [];
  14640. for (index = 0; index < data.length; index += 3) {
  14641. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14642. }
  14643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14644. // flip faces?
  14645. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14646. this.flipFaces();
  14647. }
  14648. };
  14649. // Will apply current transform to mesh and reset world matrix
  14650. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14651. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14652. this.scaling.copyFromFloats(1, 1, 1);
  14653. this.position.copyFromFloats(0, 0, 0);
  14654. this.rotation.copyFromFloats(0, 0, 0);
  14655. //only if quaternion is already set
  14656. if (this.rotationQuaternion) {
  14657. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14658. }
  14659. this._worldMatrix = BABYLON.Matrix.Identity();
  14660. };
  14661. // Cache
  14662. Mesh.prototype._resetPointsArrayCache = function () {
  14663. this._positions = null;
  14664. };
  14665. Mesh.prototype._generatePointsArray = function () {
  14666. if (this._positions)
  14667. return true;
  14668. this._positions = [];
  14669. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14670. if (!data) {
  14671. return false;
  14672. }
  14673. for (var index = 0; index < data.length; index += 3) {
  14674. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14675. }
  14676. return true;
  14677. };
  14678. // Clone
  14679. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14680. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14681. };
  14682. // Dispose
  14683. Mesh.prototype.dispose = function (doNotRecurse) {
  14684. if (this._geometry) {
  14685. this._geometry.releaseForMesh(this, true);
  14686. }
  14687. // Instances
  14688. if (this._worldMatricesInstancesBuffer) {
  14689. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14690. this._worldMatricesInstancesBuffer = null;
  14691. }
  14692. while (this.instances.length) {
  14693. this.instances[0].dispose();
  14694. }
  14695. _super.prototype.dispose.call(this, doNotRecurse);
  14696. };
  14697. // Geometric tools
  14698. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14699. var _this = this;
  14700. var scene = this.getScene();
  14701. var onload = function (img) {
  14702. // Getting height map data
  14703. var canvas = document.createElement("canvas");
  14704. var context = canvas.getContext("2d");
  14705. var heightMapWidth = img.width;
  14706. var heightMapHeight = img.height;
  14707. canvas.width = heightMapWidth;
  14708. canvas.height = heightMapHeight;
  14709. context.drawImage(img, 0, 0);
  14710. // Create VertexData from map data
  14711. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14712. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14713. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14714. //execute success callback, if set
  14715. if (onSuccess) {
  14716. onSuccess(_this);
  14717. }
  14718. };
  14719. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14720. };
  14721. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14722. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14723. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14724. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14725. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14726. return;
  14727. }
  14728. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14729. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14730. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14731. var position = BABYLON.Vector3.Zero();
  14732. var normal = BABYLON.Vector3.Zero();
  14733. var uv = BABYLON.Vector2.Zero();
  14734. for (var index = 0; index < positions.length; index += 3) {
  14735. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14736. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14737. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14738. // Compute height
  14739. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14740. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14741. var pos = (u + v * heightMapWidth) * 4;
  14742. var r = buffer[pos] / 255.0;
  14743. var g = buffer[pos + 1] / 255.0;
  14744. var b = buffer[pos + 2] / 255.0;
  14745. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14746. normal.normalize();
  14747. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14748. position = position.add(normal);
  14749. position.toArray(positions, index);
  14750. }
  14751. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14752. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14753. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14754. };
  14755. Mesh.prototype.convertToFlatShadedMesh = function () {
  14756. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14757. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14758. var kinds = this.getVerticesDataKinds();
  14759. var vbs = [];
  14760. var data = [];
  14761. var newdata = [];
  14762. var updatableNormals = false;
  14763. var kindIndex;
  14764. var kind;
  14765. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14766. kind = kinds[kindIndex];
  14767. var vertexBuffer = this.getVertexBuffer(kind);
  14768. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14769. updatableNormals = vertexBuffer.isUpdatable();
  14770. kinds.splice(kindIndex, 1);
  14771. kindIndex--;
  14772. continue;
  14773. }
  14774. vbs[kind] = vertexBuffer;
  14775. data[kind] = vbs[kind].getData();
  14776. newdata[kind] = [];
  14777. }
  14778. // Save previous submeshes
  14779. var previousSubmeshes = this.subMeshes.slice(0);
  14780. var indices = this.getIndices();
  14781. var totalIndices = this.getTotalIndices();
  14782. // Generating unique vertices per face
  14783. var index;
  14784. for (index = 0; index < totalIndices; index++) {
  14785. var vertexIndex = indices[index];
  14786. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14787. kind = kinds[kindIndex];
  14788. var stride = vbs[kind].getStrideSize();
  14789. for (var offset = 0; offset < stride; offset++) {
  14790. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14791. }
  14792. }
  14793. }
  14794. // Updating faces & normal
  14795. var normals = [];
  14796. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14797. for (index = 0; index < totalIndices; index += 3) {
  14798. indices[index] = index;
  14799. indices[index + 1] = index + 1;
  14800. indices[index + 2] = index + 2;
  14801. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14802. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14803. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14804. var p1p2 = p1.subtract(p2);
  14805. var p3p2 = p3.subtract(p2);
  14806. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14807. // Store same normals for every vertex
  14808. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14809. normals.push(normal.x);
  14810. normals.push(normal.y);
  14811. normals.push(normal.z);
  14812. }
  14813. }
  14814. this.setIndices(indices);
  14815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14816. // Updating vertex buffers
  14817. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14818. kind = kinds[kindIndex];
  14819. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14820. }
  14821. // Updating submeshes
  14822. this.releaseSubMeshes();
  14823. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14824. var previousOne = previousSubmeshes[submeshIndex];
  14825. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14826. }
  14827. this.synchronizeInstances();
  14828. };
  14829. // will inverse faces orientations, and invert normals too if specified
  14830. Mesh.prototype.flipFaces = function (flipNormals) {
  14831. if (flipNormals === void 0) { flipNormals = false; }
  14832. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14833. var i;
  14834. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14835. for (i = 0; i < vertex_data.normals.length; i++) {
  14836. vertex_data.normals[i] *= -1;
  14837. }
  14838. }
  14839. var temp;
  14840. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14841. // reassign indices
  14842. temp = vertex_data.indices[i + 1];
  14843. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14844. vertex_data.indices[i + 2] = temp;
  14845. }
  14846. vertex_data.applyToMesh(this);
  14847. };
  14848. // Instances
  14849. Mesh.prototype.createInstance = function (name) {
  14850. return new BABYLON.InstancedMesh(name, this);
  14851. };
  14852. Mesh.prototype.synchronizeInstances = function () {
  14853. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14854. var instance = this.instances[instanceIndex];
  14855. instance._syncSubMeshes();
  14856. }
  14857. };
  14858. /**
  14859. * Simplify the mesh according to the given array of settings.
  14860. * Function will return immediately and will simplify async.
  14861. * @param settings a collection of simplification settings.
  14862. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14863. * @param type the type of simplification to run.
  14864. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14865. */
  14866. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14867. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14868. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14869. this.getScene().simplificationQueue.addTask({
  14870. settings: settings,
  14871. parallelProcessing: parallelProcessing,
  14872. mesh: this,
  14873. simplificationType: simplificationType,
  14874. successCallback: successCallback
  14875. });
  14876. };
  14877. /**
  14878. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14879. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14880. * This should be used together with the simplification to avoid disappearing triangles.
  14881. * @param successCallback an optional success callback to be called after the optimization finished.
  14882. */
  14883. Mesh.prototype.optimizeIndices = function (successCallback) {
  14884. var _this = this;
  14885. var indices = this.getIndices();
  14886. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14887. var vectorPositions = [];
  14888. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14889. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14890. }
  14891. var dupes = [];
  14892. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14893. var realPos = vectorPositions.length - 1 - iteration;
  14894. var testedPosition = vectorPositions[realPos];
  14895. for (var j = 0; j < realPos; ++j) {
  14896. var againstPosition = vectorPositions[j];
  14897. if (testedPosition.equals(againstPosition)) {
  14898. dupes[realPos] = j;
  14899. break;
  14900. }
  14901. }
  14902. }, function () {
  14903. for (var i = 0; i < indices.length; ++i) {
  14904. indices[i] = dupes[indices[i]] || indices[i];
  14905. }
  14906. //indices are now reordered
  14907. var originalSubMeshes = _this.subMeshes.slice(0);
  14908. _this.setIndices(indices);
  14909. _this.subMeshes = originalSubMeshes;
  14910. if (successCallback) {
  14911. successCallback(_this);
  14912. }
  14913. });
  14914. };
  14915. // Statics
  14916. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14917. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14918. pathArray: pathArray,
  14919. closeArray: closeArray,
  14920. closePath: closePath,
  14921. offset: offset,
  14922. updatable: updatable,
  14923. sideOrientation: sideOrientation,
  14924. instance: instance
  14925. }, scene);
  14926. };
  14927. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14928. var options = {
  14929. radius: radius,
  14930. tessellation: tessellation,
  14931. sideOrientation: sideOrientation,
  14932. updatable: updatable
  14933. };
  14934. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14935. };
  14936. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14937. var options = {
  14938. size: size,
  14939. sideOrientation: sideOrientation,
  14940. updatable: updatable
  14941. };
  14942. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14943. };
  14944. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14945. var options = {
  14946. segments: segments,
  14947. diameterX: diameter,
  14948. diameterY: diameter,
  14949. diameterZ: diameter,
  14950. sideOrientation: sideOrientation,
  14951. updatable: updatable
  14952. };
  14953. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14954. };
  14955. // Cylinder and cone
  14956. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14957. var options = {
  14958. height: height,
  14959. diameterTop: diameterTop,
  14960. diameterBottom: diameterBottom,
  14961. tessellation: tessellation,
  14962. subdivisions: subdivisions,
  14963. sideOrientation: sideOrientation,
  14964. updatable: updatable
  14965. };
  14966. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14967. };
  14968. // Torus (Code from SharpDX.org)
  14969. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14970. var options = {
  14971. diameter: diameter,
  14972. thickness: thickness,
  14973. tessellation: tessellation,
  14974. sideOrientation: sideOrientation,
  14975. updatable: updatable
  14976. };
  14977. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14978. };
  14979. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14980. var options = {
  14981. radius: radius,
  14982. tube: tube,
  14983. radialSegments: radialSegments,
  14984. tubularSegments: tubularSegments,
  14985. p: p,
  14986. q: q,
  14987. sideOrientation: sideOrientation,
  14988. updatable: updatable
  14989. };
  14990. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14991. };
  14992. // Lines
  14993. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14994. var options = {
  14995. points: points,
  14996. updatable: updatable,
  14997. instance: instance
  14998. };
  14999. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15000. };
  15001. // Dashed Lines
  15002. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15003. var options = {
  15004. points: points,
  15005. dashSize: dashSize,
  15006. gapSize: gapSize,
  15007. dashNb: dashNb,
  15008. updatable: updatable
  15009. };
  15010. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15011. };
  15012. // Extrusion
  15013. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15014. var options = {
  15015. shape: shape,
  15016. path: path,
  15017. scale: scale,
  15018. rotation: rotation,
  15019. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15020. sideOrientation: sideOrientation,
  15021. instance: instance,
  15022. updatable: updatable
  15023. };
  15024. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15025. };
  15026. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15027. var options = {
  15028. shape: shape,
  15029. path: path,
  15030. scaleFunction: scaleFunction,
  15031. rotationFunction: rotationFunction,
  15032. ribbonCloseArray: ribbonCloseArray,
  15033. ribbonClosePath: ribbonClosePath,
  15034. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15035. sideOrientation: sideOrientation,
  15036. instance: instance,
  15037. updatable: updatable
  15038. };
  15039. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15040. };
  15041. // Lathe
  15042. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15043. var options = {
  15044. shape: shape,
  15045. radius: radius,
  15046. tessellation: tessellation,
  15047. sideOrientation: sideOrientation,
  15048. updatable: updatable
  15049. };
  15050. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15051. };
  15052. // Plane & ground
  15053. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15054. var options = {
  15055. size: size,
  15056. width: size,
  15057. height: size,
  15058. sideOrientation: sideOrientation,
  15059. updatable: updatable
  15060. };
  15061. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15062. };
  15063. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15064. var options = {
  15065. width: width,
  15066. height: height,
  15067. subdivisions: subdivisions,
  15068. updatable: updatable
  15069. };
  15070. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15071. };
  15072. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15073. var options = {
  15074. xmin: xmin,
  15075. zmin: zmin,
  15076. xmax: xmax,
  15077. zmax: zmax,
  15078. subdivisions: subdivisions,
  15079. precision: precision,
  15080. updatable: updatable
  15081. };
  15082. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15083. };
  15084. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15085. var options = {
  15086. width: width,
  15087. height: height,
  15088. subdivisions: subdivisions,
  15089. minHeight: minHeight,
  15090. maxHeight: maxHeight,
  15091. updatable: updatable,
  15092. onReady: onReady
  15093. };
  15094. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15095. };
  15096. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15097. var options = {
  15098. path: path,
  15099. radius: radius,
  15100. tessellation: tessellation,
  15101. radiusFunction: radiusFunction,
  15102. arc: 1,
  15103. cap: cap,
  15104. updatable: updatable,
  15105. sideOrientation: sideOrientation,
  15106. instance: instance
  15107. };
  15108. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15109. };
  15110. Mesh.CreatePolyhedron = function (name, options, scene) {
  15111. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15112. };
  15113. Mesh.CreateIcoSphere = function (name, options, scene) {
  15114. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15115. };
  15116. // Decals
  15117. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15118. var options = {
  15119. position: position,
  15120. normal: normal,
  15121. size: size,
  15122. angle: angle
  15123. };
  15124. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15125. };
  15126. // Skeletons
  15127. /**
  15128. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15129. */
  15130. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15131. var source;
  15132. if (!this._sourcePositions) {
  15133. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15134. this._sourcePositions = new Float32Array(source);
  15135. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15136. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15137. }
  15138. }
  15139. return this._sourcePositions;
  15140. };
  15141. /**
  15142. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15143. */
  15144. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15145. var source;
  15146. if (!this._sourceNormals) {
  15147. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15148. this._sourceNormals = new Float32Array(source);
  15149. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15150. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15151. }
  15152. }
  15153. return this._sourceNormals;
  15154. };
  15155. /**
  15156. * Update the vertex buffers by applying transformation from the bones
  15157. * @param {skeleton} skeleton to apply
  15158. */
  15159. Mesh.prototype.applySkeleton = function (skeleton) {
  15160. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15161. return this;
  15162. }
  15163. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15164. return this;
  15165. }
  15166. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15167. return this;
  15168. }
  15169. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15170. return this;
  15171. }
  15172. if (!this._sourcePositions) {
  15173. this.setPositionsForCPUSkinning();
  15174. }
  15175. if (!this._sourceNormals) {
  15176. this.setNormalsForCPUSkinning();
  15177. }
  15178. // positionsData checks for not being Float32Array will only pass at most once
  15179. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15180. if (!(positionsData instanceof Float32Array)) {
  15181. positionsData = new Float32Array(positionsData);
  15182. }
  15183. // normalsData checks for not being Float32Array will only pass at most once
  15184. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15185. if (!(normalsData instanceof Float32Array)) {
  15186. normalsData = new Float32Array(normalsData);
  15187. }
  15188. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15189. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15190. var needExtras = this.numBoneInfluencers > 4;
  15191. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15192. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15193. var skeletonMatrices = skeleton.getTransformMatrices();
  15194. var tempVector3 = BABYLON.Vector3.Zero();
  15195. var finalMatrix = new BABYLON.Matrix();
  15196. var tempMatrix = new BABYLON.Matrix();
  15197. var matWeightIdx = 0;
  15198. var inf;
  15199. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15200. var weight;
  15201. for (inf = 0; inf < 4; inf++) {
  15202. weight = matricesWeightsData[matWeightIdx + inf];
  15203. if (weight > 0) {
  15204. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15205. finalMatrix.addToSelf(tempMatrix);
  15206. }
  15207. else
  15208. break;
  15209. }
  15210. if (needExtras) {
  15211. for (inf = 0; inf < 4; inf++) {
  15212. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15213. if (weight > 0) {
  15214. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15215. finalMatrix.addToSelf(tempMatrix);
  15216. }
  15217. else
  15218. break;
  15219. }
  15220. }
  15221. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15222. tempVector3.toArray(positionsData, index);
  15223. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15224. tempVector3.toArray(normalsData, index);
  15225. finalMatrix.reset();
  15226. }
  15227. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15228. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15229. return this;
  15230. };
  15231. // Tools
  15232. Mesh.MinMax = function (meshes) {
  15233. var minVector = null;
  15234. var maxVector = null;
  15235. for (var i in meshes) {
  15236. var mesh = meshes[i];
  15237. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15238. if (!minVector) {
  15239. minVector = boundingBox.minimumWorld;
  15240. maxVector = boundingBox.maximumWorld;
  15241. continue;
  15242. }
  15243. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15244. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15245. }
  15246. return {
  15247. min: minVector,
  15248. max: maxVector
  15249. };
  15250. };
  15251. Mesh.Center = function (meshesOrMinMaxVector) {
  15252. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15253. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15254. };
  15255. /**
  15256. * Merge the array of meshes into a single mesh for performance reasons.
  15257. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15258. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15259. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15260. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15261. */
  15262. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15263. if (disposeSource === void 0) { disposeSource = true; }
  15264. var index;
  15265. if (!allow32BitsIndices) {
  15266. var totalVertices = 0;
  15267. // Counting vertices
  15268. for (index = 0; index < meshes.length; index++) {
  15269. if (meshes[index]) {
  15270. totalVertices += meshes[index].getTotalVertices();
  15271. if (totalVertices > 65536) {
  15272. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15273. return null;
  15274. }
  15275. }
  15276. }
  15277. }
  15278. // Merge
  15279. var vertexData;
  15280. var otherVertexData;
  15281. var source;
  15282. for (index = 0; index < meshes.length; index++) {
  15283. if (meshes[index]) {
  15284. meshes[index].computeWorldMatrix(true);
  15285. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15286. otherVertexData.transform(meshes[index].getWorldMatrix());
  15287. if (vertexData) {
  15288. vertexData.merge(otherVertexData);
  15289. }
  15290. else {
  15291. vertexData = otherVertexData;
  15292. source = meshes[index];
  15293. }
  15294. }
  15295. }
  15296. if (!meshSubclass) {
  15297. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15298. }
  15299. vertexData.applyToMesh(meshSubclass);
  15300. // Setting properties
  15301. meshSubclass.material = source.material;
  15302. meshSubclass.checkCollisions = source.checkCollisions;
  15303. // Cleaning
  15304. if (disposeSource) {
  15305. for (index = 0; index < meshes.length; index++) {
  15306. if (meshes[index]) {
  15307. meshes[index].dispose();
  15308. }
  15309. }
  15310. }
  15311. return meshSubclass;
  15312. };
  15313. // Consts
  15314. Mesh._FRONTSIDE = 0;
  15315. Mesh._BACKSIDE = 1;
  15316. Mesh._DOUBLESIDE = 2;
  15317. Mesh._DEFAULTSIDE = 0;
  15318. Mesh._NO_CAP = 0;
  15319. Mesh._CAP_START = 1;
  15320. Mesh._CAP_END = 2;
  15321. Mesh._CAP_ALL = 3;
  15322. return Mesh;
  15323. })(BABYLON.AbstractMesh);
  15324. BABYLON.Mesh = Mesh;
  15325. })(BABYLON || (BABYLON = {}));
  15326. var BABYLON;
  15327. (function (BABYLON) {
  15328. var SubMesh = (function () {
  15329. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15330. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15331. this.materialIndex = materialIndex;
  15332. this.verticesStart = verticesStart;
  15333. this.verticesCount = verticesCount;
  15334. this.indexStart = indexStart;
  15335. this.indexCount = indexCount;
  15336. this._renderId = 0;
  15337. this._mesh = mesh;
  15338. this._renderingMesh = renderingMesh || mesh;
  15339. mesh.subMeshes.push(this);
  15340. this._trianglePlanes = [];
  15341. this._id = mesh.subMeshes.length - 1;
  15342. if (createBoundingBox) {
  15343. this.refreshBoundingInfo();
  15344. mesh.computeWorldMatrix(true);
  15345. }
  15346. }
  15347. SubMesh.prototype.getBoundingInfo = function () {
  15348. return this._boundingInfo;
  15349. };
  15350. SubMesh.prototype.getMesh = function () {
  15351. return this._mesh;
  15352. };
  15353. SubMesh.prototype.getRenderingMesh = function () {
  15354. return this._renderingMesh;
  15355. };
  15356. SubMesh.prototype.getMaterial = function () {
  15357. var rootMaterial = this._renderingMesh.material;
  15358. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15359. var multiMaterial = rootMaterial;
  15360. return multiMaterial.getSubMaterial(this.materialIndex);
  15361. }
  15362. if (!rootMaterial) {
  15363. return this._mesh.getScene().defaultMaterial;
  15364. }
  15365. return rootMaterial;
  15366. };
  15367. // Methods
  15368. SubMesh.prototype.refreshBoundingInfo = function () {
  15369. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15370. if (!data) {
  15371. this._boundingInfo = this._mesh._boundingInfo;
  15372. return;
  15373. }
  15374. var indices = this._renderingMesh.getIndices();
  15375. var extend;
  15376. //is this the only submesh?
  15377. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15378. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15379. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15380. }
  15381. else {
  15382. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15383. }
  15384. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15385. };
  15386. SubMesh.prototype._checkCollision = function (collider) {
  15387. return this._boundingInfo._checkCollision(collider);
  15388. };
  15389. SubMesh.prototype.updateBoundingInfo = function (world) {
  15390. if (!this._boundingInfo) {
  15391. this.refreshBoundingInfo();
  15392. }
  15393. this._boundingInfo._update(world);
  15394. };
  15395. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15396. return this._boundingInfo.isInFrustum(frustumPlanes);
  15397. };
  15398. SubMesh.prototype.render = function (enableAlphaMode) {
  15399. this._renderingMesh.render(this, enableAlphaMode);
  15400. };
  15401. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15402. if (!this._linesIndexBuffer) {
  15403. var linesIndices = [];
  15404. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15405. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15406. }
  15407. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15408. this.linesIndexCount = linesIndices.length;
  15409. }
  15410. return this._linesIndexBuffer;
  15411. };
  15412. SubMesh.prototype.canIntersects = function (ray) {
  15413. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15414. };
  15415. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15416. var intersectInfo = null;
  15417. // Triangles test
  15418. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15419. var p0 = positions[indices[index]];
  15420. var p1 = positions[indices[index + 1]];
  15421. var p2 = positions[indices[index + 2]];
  15422. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15423. if (currentIntersectInfo) {
  15424. if (currentIntersectInfo.distance < 0) {
  15425. continue;
  15426. }
  15427. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15428. intersectInfo = currentIntersectInfo;
  15429. intersectInfo.faceId = index / 3;
  15430. if (fastCheck) {
  15431. break;
  15432. }
  15433. }
  15434. }
  15435. }
  15436. return intersectInfo;
  15437. };
  15438. // Clone
  15439. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15440. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15441. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15442. return result;
  15443. };
  15444. // Dispose
  15445. SubMesh.prototype.dispose = function () {
  15446. if (this._linesIndexBuffer) {
  15447. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15448. this._linesIndexBuffer = null;
  15449. }
  15450. // Remove from mesh
  15451. var index = this._mesh.subMeshes.indexOf(this);
  15452. this._mesh.subMeshes.splice(index, 1);
  15453. };
  15454. // Statics
  15455. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15456. var minVertexIndex = Number.MAX_VALUE;
  15457. var maxVertexIndex = -Number.MAX_VALUE;
  15458. renderingMesh = renderingMesh || mesh;
  15459. var indices = renderingMesh.getIndices();
  15460. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15461. var vertexIndex = indices[index];
  15462. if (vertexIndex < minVertexIndex)
  15463. minVertexIndex = vertexIndex;
  15464. if (vertexIndex > maxVertexIndex)
  15465. maxVertexIndex = vertexIndex;
  15466. }
  15467. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15468. };
  15469. return SubMesh;
  15470. })();
  15471. BABYLON.SubMesh = SubMesh;
  15472. })(BABYLON || (BABYLON = {}));
  15473. var BABYLON;
  15474. (function (BABYLON) {
  15475. var MeshBuilder = (function () {
  15476. function MeshBuilder() {
  15477. }
  15478. MeshBuilder.CreateBox = function (name, options, scene) {
  15479. var box = new BABYLON.Mesh(name, scene);
  15480. var vertexData = BABYLON.VertexData.CreateBox(options);
  15481. vertexData.applyToMesh(box, options.updatable);
  15482. return box;
  15483. };
  15484. MeshBuilder.CreateSphere = function (name, options, scene) {
  15485. var sphere = new BABYLON.Mesh(name, scene);
  15486. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15487. vertexData.applyToMesh(sphere, options.updatable);
  15488. return sphere;
  15489. };
  15490. MeshBuilder.CreateDisc = function (name, options, scene) {
  15491. var disc = new BABYLON.Mesh(name, scene);
  15492. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15493. vertexData.applyToMesh(disc, options.updatable);
  15494. return disc;
  15495. };
  15496. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15497. var sphere = new BABYLON.Mesh(name, scene);
  15498. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15499. vertexData.applyToMesh(sphere, options.updatable);
  15500. return sphere;
  15501. };
  15502. ;
  15503. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15504. var pathArray = options.pathArray;
  15505. var closeArray = options.closeArray;
  15506. var closePath = options.closePath;
  15507. var offset = options.offset;
  15508. var sideOrientation = options.sideOrientation;
  15509. var instance = options.instance;
  15510. var updatable = options.updatable;
  15511. if (instance) {
  15512. // positionFunction : ribbon case
  15513. // only pathArray and sideOrientation parameters are taken into account for positions update
  15514. var positionFunction = function (positions) {
  15515. var minlg = pathArray[0].length;
  15516. var i = 0;
  15517. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15518. for (var si = 1; si <= ns; si++) {
  15519. for (var p = 0; p < pathArray.length; p++) {
  15520. var path = pathArray[p];
  15521. var l = path.length;
  15522. minlg = (minlg < l) ? minlg : l;
  15523. var j = 0;
  15524. while (j < minlg) {
  15525. positions[i] = path[j].x;
  15526. positions[i + 1] = path[j].y;
  15527. positions[i + 2] = path[j].z;
  15528. j++;
  15529. i += 3;
  15530. }
  15531. if (instance._closePath) {
  15532. positions[i] = path[0].x;
  15533. positions[i + 1] = path[0].y;
  15534. positions[i + 2] = path[0].z;
  15535. i += 3;
  15536. }
  15537. }
  15538. }
  15539. };
  15540. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15541. positionFunction(positions);
  15542. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15543. if (!(instance.areNormalsFrozen)) {
  15544. var indices = instance.getIndices();
  15545. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15546. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15547. if (instance._closePath) {
  15548. var indexFirst = 0;
  15549. var indexLast = 0;
  15550. for (var p = 0; p < pathArray.length; p++) {
  15551. indexFirst = instance._idx[p] * 3;
  15552. if (p + 1 < pathArray.length) {
  15553. indexLast = (instance._idx[p + 1] - 1) * 3;
  15554. }
  15555. else {
  15556. indexLast = normals.length - 3;
  15557. }
  15558. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15559. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15560. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15561. normals[indexLast] = normals[indexFirst];
  15562. normals[indexLast + 1] = normals[indexFirst + 1];
  15563. normals[indexLast + 2] = normals[indexFirst + 2];
  15564. }
  15565. }
  15566. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15567. }
  15568. return instance;
  15569. }
  15570. else {
  15571. var ribbon = new BABYLON.Mesh(name, scene);
  15572. ribbon.sideOrientation = sideOrientation;
  15573. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15574. if (closePath) {
  15575. ribbon._idx = vertexData._idx;
  15576. }
  15577. ribbon._closePath = closePath;
  15578. ribbon._closeArray = closeArray;
  15579. vertexData.applyToMesh(ribbon, updatable);
  15580. return ribbon;
  15581. }
  15582. };
  15583. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15584. var cylinder = new BABYLON.Mesh(name, scene);
  15585. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15586. vertexData.applyToMesh(cylinder, options.updatable);
  15587. return cylinder;
  15588. };
  15589. MeshBuilder.CreateTorus = function (name, options, scene) {
  15590. var torus = new BABYLON.Mesh(name, scene);
  15591. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15592. vertexData.applyToMesh(torus, options.updatable);
  15593. return torus;
  15594. };
  15595. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15596. var torusKnot = new BABYLON.Mesh(name, scene);
  15597. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15598. vertexData.applyToMesh(torusKnot, options.updatable);
  15599. return torusKnot;
  15600. };
  15601. MeshBuilder.CreateLines = function (name, options, scene) {
  15602. var instance = options.instance;
  15603. var points = options.points;
  15604. if (instance) {
  15605. var positionFunction = function (positions) {
  15606. var i = 0;
  15607. for (var p = 0; p < points.length; p++) {
  15608. positions[i] = points[p].x;
  15609. positions[i + 1] = points[p].y;
  15610. positions[i + 2] = points[p].z;
  15611. i += 3;
  15612. }
  15613. };
  15614. instance.updateMeshPositions(positionFunction, false);
  15615. return instance;
  15616. }
  15617. // lines creation
  15618. var lines = new BABYLON.LinesMesh(name, scene);
  15619. var vertexData = BABYLON.VertexData.CreateLines(options);
  15620. vertexData.applyToMesh(lines, options.updatable);
  15621. return lines;
  15622. };
  15623. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15624. var points = options.points;
  15625. var instance = options.instance;
  15626. var gapSize = options.gapSize;
  15627. var dashNb = options.dashNb;
  15628. var dashSize = options.dashSize;
  15629. if (instance) {
  15630. var positionFunction = function (positions) {
  15631. var curvect = BABYLON.Vector3.Zero();
  15632. var nbSeg = positions.length / 6;
  15633. var lg = 0;
  15634. var nb = 0;
  15635. var shft = 0;
  15636. var dashshft = 0;
  15637. var curshft = 0;
  15638. var p = 0;
  15639. var i = 0;
  15640. var j = 0;
  15641. for (i = 0; i < points.length - 1; i++) {
  15642. points[i + 1].subtractToRef(points[i], curvect);
  15643. lg += curvect.length();
  15644. }
  15645. shft = lg / nbSeg;
  15646. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15647. for (i = 0; i < points.length - 1; i++) {
  15648. points[i + 1].subtractToRef(points[i], curvect);
  15649. nb = Math.floor(curvect.length() / shft);
  15650. curvect.normalize();
  15651. j = 0;
  15652. while (j < nb && p < positions.length) {
  15653. curshft = shft * j;
  15654. positions[p] = points[i].x + curshft * curvect.x;
  15655. positions[p + 1] = points[i].y + curshft * curvect.y;
  15656. positions[p + 2] = points[i].z + curshft * curvect.z;
  15657. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15658. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15659. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15660. p += 6;
  15661. j++;
  15662. }
  15663. }
  15664. while (p < positions.length) {
  15665. positions[p] = points[i].x;
  15666. positions[p + 1] = points[i].y;
  15667. positions[p + 2] = points[i].z;
  15668. p += 3;
  15669. }
  15670. };
  15671. instance.updateMeshPositions(positionFunction, false);
  15672. return instance;
  15673. }
  15674. // dashed lines creation
  15675. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15676. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15677. vertexData.applyToMesh(dashedLines, options.updatable);
  15678. dashedLines.dashSize = dashSize;
  15679. dashedLines.gapSize = gapSize;
  15680. return dashedLines;
  15681. };
  15682. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15683. var path = options.path;
  15684. var shape = options.shape;
  15685. var scale = options.scale || 1;
  15686. var rotation = options.rotation || 0;
  15687. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15688. var updatable = options.updatable;
  15689. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15690. var instance = options.instance;
  15691. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15692. };
  15693. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15694. var path = options.path;
  15695. var shape = options.shape;
  15696. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15697. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15698. var ribbonCloseArray = options.ribbonCloseArray || false;
  15699. var ribbonClosePath = options.ribbonClosePath || false;
  15700. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15701. var updatable = options.updatable;
  15702. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15703. var instance = options.instance;
  15704. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15705. };
  15706. MeshBuilder.CreateLathe = function (name, options, scene) {
  15707. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15708. var closed = (options.closed === undefined) ? true : options.closed;
  15709. var shape = options.shape;
  15710. var radius = options.radius || 1;
  15711. var tessellation = options.tessellation || 64;
  15712. var updatable = options.updatable;
  15713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15714. var pi2 = Math.PI * 2;
  15715. var shapeLathe = new Array();
  15716. // first rotatable point
  15717. var i = 0;
  15718. while (shape[i].x === 0) {
  15719. i++;
  15720. }
  15721. var pt = shape[i];
  15722. for (i = 0; i < shape.length; i++) {
  15723. shapeLathe.push(shape[i].subtract(pt));
  15724. }
  15725. // circle path
  15726. var step = pi2 / tessellation * arc;
  15727. var rotated;
  15728. var path = new Array();
  15729. ;
  15730. for (i = 0; i <= tessellation; i++) {
  15731. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15732. path.push(rotated);
  15733. }
  15734. if (closed) {
  15735. path.push(path[0]);
  15736. }
  15737. // extrusion
  15738. var scaleFunction = function () { return 1; };
  15739. var rotateFunction = function () { return 0; };
  15740. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15741. return lathe;
  15742. };
  15743. MeshBuilder.CreatePlane = function (name, options, scene) {
  15744. var plane = new BABYLON.Mesh(name, scene);
  15745. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15746. vertexData.applyToMesh(plane, options.updatable);
  15747. if (options.sourcePlane) {
  15748. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15749. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15750. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15751. plane.rotate(vectorProduct, product);
  15752. }
  15753. return plane;
  15754. };
  15755. MeshBuilder.CreateGround = function (name, options, scene) {
  15756. var ground = new BABYLON.GroundMesh(name, scene);
  15757. ground._setReady(false);
  15758. ground._subdivisions = options.subdivisions || 1;
  15759. var vertexData = BABYLON.VertexData.CreateGround(options);
  15760. vertexData.applyToMesh(ground, options.updatable);
  15761. ground._setReady(true);
  15762. return ground;
  15763. };
  15764. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15765. var tiledGround = new BABYLON.Mesh(name, scene);
  15766. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15767. vertexData.applyToMesh(tiledGround, options.updatable);
  15768. return tiledGround;
  15769. };
  15770. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15771. var width = options.width || 10;
  15772. var height = options.height || 10;
  15773. var subdivisions = options.subdivisions || 1;
  15774. var minHeight = options.minHeight;
  15775. var maxHeight = options.maxHeight || 10;
  15776. var updatable = options.updatable;
  15777. var onReady = options.onReady;
  15778. var ground = new BABYLON.GroundMesh(name, scene);
  15779. ground._subdivisions = subdivisions;
  15780. ground._setReady(false);
  15781. var onload = function (img) {
  15782. // Getting height map data
  15783. var canvas = document.createElement("canvas");
  15784. var context = canvas.getContext("2d");
  15785. var bufferWidth = img.width;
  15786. var bufferHeight = img.height;
  15787. canvas.width = bufferWidth;
  15788. canvas.height = bufferHeight;
  15789. context.drawImage(img, 0, 0);
  15790. // Create VertexData from map data
  15791. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15792. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15793. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15794. width: width, height: height,
  15795. subdivisions: subdivisions,
  15796. minHeight: minHeight, maxHeight: maxHeight,
  15797. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15798. });
  15799. vertexData.applyToMesh(ground, updatable);
  15800. ground._setReady(true);
  15801. //execute ready callback, if set
  15802. if (onReady) {
  15803. onReady(ground);
  15804. }
  15805. };
  15806. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15807. return ground;
  15808. };
  15809. MeshBuilder.CreateTube = function (name, options, scene) {
  15810. var path = options.path;
  15811. var radius = options.radius || 1;
  15812. var tessellation = options.tessellation || 64;
  15813. var radiusFunction = options.radiusFunction;
  15814. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15815. var updatable = options.updatable;
  15816. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15817. var instance = options.instance;
  15818. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15819. // tube geometry
  15820. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15821. var tangents = path3D.getTangents();
  15822. var normals = path3D.getNormals();
  15823. var distances = path3D.getDistances();
  15824. var pi2 = Math.PI * 2;
  15825. var step = pi2 / tessellation * arc;
  15826. var returnRadius = function () { return radius; };
  15827. var radiusFunctionFinal = radiusFunction || returnRadius;
  15828. var circlePath;
  15829. var rad;
  15830. var normal;
  15831. var rotated;
  15832. var rotationMatrix = BABYLON.Matrix.Zero();
  15833. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15834. for (var i = 0; i < path.length; i++) {
  15835. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15836. circlePath = Array(); // current circle array
  15837. normal = normals[i]; // current normal
  15838. for (var t = 0; t < tessellation; t++) {
  15839. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15840. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15841. circlePath.push(rotated);
  15842. }
  15843. circlePaths[index] = circlePath;
  15844. index++;
  15845. }
  15846. // cap
  15847. var capPath = function (nbPoints, pathIndex) {
  15848. var pointCap = Array();
  15849. for (var i = 0; i < nbPoints; i++) {
  15850. pointCap.push(path[pathIndex]);
  15851. }
  15852. return pointCap;
  15853. };
  15854. switch (cap) {
  15855. case BABYLON.Mesh.NO_CAP:
  15856. break;
  15857. case BABYLON.Mesh.CAP_START:
  15858. circlePaths[0] = capPath(tessellation, 0);
  15859. circlePaths[1] = circlePaths[2].slice(0);
  15860. break;
  15861. case BABYLON.Mesh.CAP_END:
  15862. circlePaths[index] = circlePaths[index - 1].slice(0);
  15863. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15864. break;
  15865. case BABYLON.Mesh.CAP_ALL:
  15866. circlePaths[0] = capPath(tessellation, 0);
  15867. circlePaths[1] = circlePaths[2].slice(0);
  15868. circlePaths[index] = circlePaths[index - 1].slice(0);
  15869. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15870. break;
  15871. default:
  15872. break;
  15873. }
  15874. return circlePaths;
  15875. };
  15876. var path3D;
  15877. var pathArray;
  15878. if (instance) {
  15879. var arc = options.arc || instance.arc;
  15880. path3D = (instance.path3D).update(path);
  15881. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15882. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15883. instance.path3D = path3D;
  15884. instance.pathArray = pathArray;
  15885. instance.arc = arc;
  15886. return instance;
  15887. }
  15888. // tube creation
  15889. path3D = new BABYLON.Path3D(path);
  15890. var newPathArray = new Array();
  15891. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15892. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15893. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15894. tube.pathArray = pathArray;
  15895. tube.path3D = path3D;
  15896. tube.tessellation = tessellation;
  15897. tube.cap = cap;
  15898. tube.arc = options.arc;
  15899. return tube;
  15900. };
  15901. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15902. var polyhedron = new BABYLON.Mesh(name, scene);
  15903. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15904. vertexData.applyToMesh(polyhedron, options.updatable);
  15905. return polyhedron;
  15906. };
  15907. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15908. var indices = sourceMesh.getIndices();
  15909. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15910. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15911. var position = options.position || BABYLON.Vector3.Zero();
  15912. var normal = options.normal || BABYLON.Vector3.Up();
  15913. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15914. var angle = options.angle || 0;
  15915. // Getting correct rotation
  15916. if (!normal) {
  15917. var target = new BABYLON.Vector3(0, 0, 1);
  15918. var camera = sourceMesh.getScene().activeCamera;
  15919. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15920. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15921. }
  15922. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15923. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15924. var pitch = Math.atan2(normal.y, len);
  15925. // Matrix
  15926. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15927. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15928. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15929. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15930. var vertexData = new BABYLON.VertexData();
  15931. vertexData.indices = [];
  15932. vertexData.positions = [];
  15933. vertexData.normals = [];
  15934. vertexData.uvs = [];
  15935. var currentVertexDataIndex = 0;
  15936. var extractDecalVector3 = function (indexId) {
  15937. var vertexId = indices[indexId];
  15938. var result = new BABYLON.PositionNormalVertex();
  15939. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15940. // Send vector to decal local world
  15941. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15942. // Get normal
  15943. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15944. return result;
  15945. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15946. var clip = function (vertices, axis) {
  15947. if (vertices.length === 0) {
  15948. return vertices;
  15949. }
  15950. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15951. var clipVertices = function (v0, v1) {
  15952. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15953. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15954. };
  15955. var result = new Array();
  15956. for (var index = 0; index < vertices.length; index += 3) {
  15957. var v1Out;
  15958. var v2Out;
  15959. var v3Out;
  15960. var total = 0;
  15961. var nV1, nV2, nV3, nV4;
  15962. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15963. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15964. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15965. v1Out = d1 > 0;
  15966. v2Out = d2 > 0;
  15967. v3Out = d3 > 0;
  15968. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15969. switch (total) {
  15970. case 0:
  15971. result.push(vertices[index]);
  15972. result.push(vertices[index + 1]);
  15973. result.push(vertices[index + 2]);
  15974. break;
  15975. case 1:
  15976. if (v1Out) {
  15977. nV1 = vertices[index + 1];
  15978. nV2 = vertices[index + 2];
  15979. nV3 = clipVertices(vertices[index], nV1);
  15980. nV4 = clipVertices(vertices[index], nV2);
  15981. }
  15982. if (v2Out) {
  15983. nV1 = vertices[index];
  15984. nV2 = vertices[index + 2];
  15985. nV3 = clipVertices(vertices[index + 1], nV1);
  15986. nV4 = clipVertices(vertices[index + 1], nV2);
  15987. result.push(nV3);
  15988. result.push(nV2.clone());
  15989. result.push(nV1.clone());
  15990. result.push(nV2.clone());
  15991. result.push(nV3.clone());
  15992. result.push(nV4);
  15993. break;
  15994. }
  15995. if (v3Out) {
  15996. nV1 = vertices[index];
  15997. nV2 = vertices[index + 1];
  15998. nV3 = clipVertices(vertices[index + 2], nV1);
  15999. nV4 = clipVertices(vertices[index + 2], nV2);
  16000. }
  16001. result.push(nV1.clone());
  16002. result.push(nV2.clone());
  16003. result.push(nV3);
  16004. result.push(nV4);
  16005. result.push(nV3.clone());
  16006. result.push(nV2.clone());
  16007. break;
  16008. case 2:
  16009. if (!v1Out) {
  16010. nV1 = vertices[index].clone();
  16011. nV2 = clipVertices(nV1, vertices[index + 1]);
  16012. nV3 = clipVertices(nV1, vertices[index + 2]);
  16013. result.push(nV1);
  16014. result.push(nV2);
  16015. result.push(nV3);
  16016. }
  16017. if (!v2Out) {
  16018. nV1 = vertices[index + 1].clone();
  16019. nV2 = clipVertices(nV1, vertices[index + 2]);
  16020. nV3 = clipVertices(nV1, vertices[index]);
  16021. result.push(nV1);
  16022. result.push(nV2);
  16023. result.push(nV3);
  16024. }
  16025. if (!v3Out) {
  16026. nV1 = vertices[index + 2].clone();
  16027. nV2 = clipVertices(nV1, vertices[index]);
  16028. nV3 = clipVertices(nV1, vertices[index + 1]);
  16029. result.push(nV1);
  16030. result.push(nV2);
  16031. result.push(nV3);
  16032. }
  16033. break;
  16034. case 3:
  16035. break;
  16036. }
  16037. }
  16038. return result;
  16039. };
  16040. for (var index = 0; index < indices.length; index += 3) {
  16041. var faceVertices = new Array();
  16042. faceVertices.push(extractDecalVector3(index));
  16043. faceVertices.push(extractDecalVector3(index + 1));
  16044. faceVertices.push(extractDecalVector3(index + 2));
  16045. // Clip
  16046. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16047. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16048. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16049. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16052. if (faceVertices.length === 0) {
  16053. continue;
  16054. }
  16055. // Add UVs and get back to world
  16056. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16057. var vertex = faceVertices[vIndex];
  16058. vertexData.indices.push(currentVertexDataIndex);
  16059. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16060. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16061. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16062. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16063. currentVertexDataIndex++;
  16064. }
  16065. }
  16066. // Return mesh
  16067. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16068. vertexData.applyToMesh(decal);
  16069. decal.position = position.clone();
  16070. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16071. return decal;
  16072. };
  16073. // Privates
  16074. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16075. // extrusion geometry
  16076. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16077. var tangents = path3D.getTangents();
  16078. var normals = path3D.getNormals();
  16079. var binormals = path3D.getBinormals();
  16080. var distances = path3D.getDistances();
  16081. var angle = 0;
  16082. var returnScale = function () { return scale; };
  16083. var returnRotation = function () { return rotation; };
  16084. var rotate = custom ? rotateFunction : returnRotation;
  16085. var scl = custom ? scaleFunction : returnScale;
  16086. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16087. var rotationMatrix = BABYLON.Matrix.Zero();
  16088. for (var i = 0; i < curve.length; i++) {
  16089. var shapePath = new Array();
  16090. var angleStep = rotate(i, distances[i]);
  16091. var scaleRatio = scl(i, distances[i]);
  16092. for (var p = 0; p < shape.length; p++) {
  16093. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16094. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16095. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16096. shapePath.push(rotated);
  16097. }
  16098. shapePaths[index] = shapePath;
  16099. angle += angleStep;
  16100. index++;
  16101. }
  16102. // cap
  16103. var capPath = function (shapePath) {
  16104. var pointCap = Array();
  16105. var barycenter = BABYLON.Vector3.Zero();
  16106. var i;
  16107. for (i = 0; i < shapePath.length; i++) {
  16108. barycenter.addInPlace(shapePath[i]);
  16109. }
  16110. barycenter.scaleInPlace(1 / shapePath.length);
  16111. for (i = 0; i < shapePath.length; i++) {
  16112. pointCap.push(barycenter);
  16113. }
  16114. return pointCap;
  16115. };
  16116. switch (cap) {
  16117. case BABYLON.Mesh.NO_CAP:
  16118. break;
  16119. case BABYLON.Mesh.CAP_START:
  16120. shapePaths[0] = capPath(shapePaths[2]);
  16121. shapePaths[1] = shapePaths[2].slice(0);
  16122. break;
  16123. case BABYLON.Mesh.CAP_END:
  16124. shapePaths[index] = shapePaths[index - 1];
  16125. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16126. break;
  16127. case BABYLON.Mesh.CAP_ALL:
  16128. shapePaths[0] = capPath(shapePaths[2]);
  16129. shapePaths[1] = shapePaths[2].slice(0);
  16130. shapePaths[index] = shapePaths[index - 1];
  16131. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16132. break;
  16133. default:
  16134. break;
  16135. }
  16136. return shapePaths;
  16137. };
  16138. var path3D;
  16139. var pathArray;
  16140. if (instance) {
  16141. path3D = (instance.path3D).update(curve);
  16142. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16143. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16144. return instance;
  16145. }
  16146. // extruded shape creation
  16147. path3D = new BABYLON.Path3D(curve);
  16148. var newShapePaths = new Array();
  16149. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16150. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16151. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16152. extrudedGeneric.pathArray = pathArray;
  16153. extrudedGeneric.path3D = path3D;
  16154. extrudedGeneric.cap = cap;
  16155. return extrudedGeneric;
  16156. };
  16157. return MeshBuilder;
  16158. })();
  16159. BABYLON.MeshBuilder = MeshBuilder;
  16160. })(BABYLON || (BABYLON = {}));
  16161. var BABYLON;
  16162. (function (BABYLON) {
  16163. var BaseTexture = (function () {
  16164. function BaseTexture(scene) {
  16165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16166. this.hasAlpha = false;
  16167. this.getAlphaFromRGB = false;
  16168. this.level = 1;
  16169. this.isCube = false;
  16170. this.isRenderTarget = false;
  16171. this.animations = new Array();
  16172. this.coordinatesIndex = 0;
  16173. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16174. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16175. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16176. this.anisotropicFilteringLevel = 4;
  16177. this._scene = scene;
  16178. this._scene.textures.push(this);
  16179. }
  16180. BaseTexture.prototype.getScene = function () {
  16181. return this._scene;
  16182. };
  16183. BaseTexture.prototype.getTextureMatrix = function () {
  16184. return null;
  16185. };
  16186. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16187. return null;
  16188. };
  16189. BaseTexture.prototype.getInternalTexture = function () {
  16190. return this._texture;
  16191. };
  16192. BaseTexture.prototype.isReady = function () {
  16193. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16194. return true;
  16195. }
  16196. if (this._texture) {
  16197. return this._texture.isReady;
  16198. }
  16199. return false;
  16200. };
  16201. BaseTexture.prototype.getSize = function () {
  16202. if (this._texture._width) {
  16203. return { width: this._texture._width, height: this._texture._height };
  16204. }
  16205. if (this._texture._size) {
  16206. return { width: this._texture._size, height: this._texture._size };
  16207. }
  16208. return { width: 0, height: 0 };
  16209. };
  16210. BaseTexture.prototype.getBaseSize = function () {
  16211. if (!this.isReady())
  16212. return { width: 0, height: 0 };
  16213. if (this._texture._size) {
  16214. return { width: this._texture._size, height: this._texture._size };
  16215. }
  16216. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16217. };
  16218. BaseTexture.prototype.scale = function (ratio) {
  16219. };
  16220. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16221. get: function () {
  16222. return false;
  16223. },
  16224. enumerable: true,
  16225. configurable: true
  16226. });
  16227. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16228. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16229. for (var index = 0; index < texturesCache.length; index++) {
  16230. var texturesCacheEntry = texturesCache[index];
  16231. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16232. texturesCache.splice(index, 1);
  16233. return;
  16234. }
  16235. }
  16236. };
  16237. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16238. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16239. for (var index = 0; index < texturesCache.length; index++) {
  16240. var texturesCacheEntry = texturesCache[index];
  16241. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16242. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16243. texturesCacheEntry.references++;
  16244. return texturesCacheEntry;
  16245. }
  16246. }
  16247. }
  16248. return null;
  16249. };
  16250. BaseTexture.prototype.delayLoad = function () {
  16251. };
  16252. BaseTexture.prototype.clone = function () {
  16253. return null;
  16254. };
  16255. BaseTexture.prototype.releaseInternalTexture = function () {
  16256. if (this._texture) {
  16257. this._scene.getEngine().releaseInternalTexture(this._texture);
  16258. delete this._texture;
  16259. }
  16260. };
  16261. BaseTexture.prototype.dispose = function () {
  16262. // Animations
  16263. this.getScene().stopAnimation(this);
  16264. // Remove from scene
  16265. var index = this._scene.textures.indexOf(this);
  16266. if (index >= 0) {
  16267. this._scene.textures.splice(index, 1);
  16268. }
  16269. if (this._texture === undefined) {
  16270. return;
  16271. }
  16272. // Callback
  16273. if (this.onDispose) {
  16274. this.onDispose();
  16275. }
  16276. };
  16277. return BaseTexture;
  16278. })();
  16279. BABYLON.BaseTexture = BaseTexture;
  16280. })(BABYLON || (BABYLON = {}));
  16281. var BABYLON;
  16282. (function (BABYLON) {
  16283. var Texture = (function (_super) {
  16284. __extends(Texture, _super);
  16285. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16286. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16287. if (onLoad === void 0) { onLoad = null; }
  16288. if (onError === void 0) { onError = null; }
  16289. if (buffer === void 0) { buffer = null; }
  16290. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16291. _super.call(this, scene);
  16292. this.uOffset = 0;
  16293. this.vOffset = 0;
  16294. this.uScale = 1.0;
  16295. this.vScale = 1.0;
  16296. this.uAng = 0;
  16297. this.vAng = 0;
  16298. this.wAng = 0;
  16299. this.name = url;
  16300. this.url = url;
  16301. this._noMipmap = noMipmap;
  16302. this._invertY = invertY;
  16303. this._samplingMode = samplingMode;
  16304. this._buffer = buffer;
  16305. this._deleteBuffer = deleteBuffer;
  16306. if (!url) {
  16307. return;
  16308. }
  16309. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16310. if (!this._texture) {
  16311. if (!scene.useDelayedTextureLoading) {
  16312. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16313. if (deleteBuffer) {
  16314. delete this._buffer;
  16315. }
  16316. }
  16317. else {
  16318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16319. }
  16320. }
  16321. else {
  16322. BABYLON.Tools.SetImmediate(function () {
  16323. if (onLoad) {
  16324. onLoad();
  16325. }
  16326. });
  16327. }
  16328. }
  16329. Texture.prototype.delayLoad = function () {
  16330. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16331. return;
  16332. }
  16333. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16334. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16335. if (!this._texture) {
  16336. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16337. if (this._deleteBuffer) {
  16338. delete this._buffer;
  16339. }
  16340. }
  16341. };
  16342. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16343. if (!this._texture) {
  16344. return;
  16345. }
  16346. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16347. };
  16348. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16349. x *= this.uScale;
  16350. y *= this.vScale;
  16351. x -= 0.5 * this.uScale;
  16352. y -= 0.5 * this.vScale;
  16353. z -= 0.5;
  16354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16355. t.x += 0.5 * this.uScale + this.uOffset;
  16356. t.y += 0.5 * this.vScale + this.vOffset;
  16357. t.z += 0.5;
  16358. };
  16359. Texture.prototype.getTextureMatrix = function () {
  16360. if (this.uOffset === this._cachedUOffset &&
  16361. this.vOffset === this._cachedVOffset &&
  16362. this.uScale === this._cachedUScale &&
  16363. this.vScale === this._cachedVScale &&
  16364. this.uAng === this._cachedUAng &&
  16365. this.vAng === this._cachedVAng &&
  16366. this.wAng === this._cachedWAng) {
  16367. return this._cachedTextureMatrix;
  16368. }
  16369. this._cachedUOffset = this.uOffset;
  16370. this._cachedVOffset = this.vOffset;
  16371. this._cachedUScale = this.uScale;
  16372. this._cachedVScale = this.vScale;
  16373. this._cachedUAng = this.uAng;
  16374. this._cachedVAng = this.vAng;
  16375. this._cachedWAng = this.wAng;
  16376. if (!this._cachedTextureMatrix) {
  16377. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16378. this._rowGenerationMatrix = new BABYLON.Matrix();
  16379. this._t0 = BABYLON.Vector3.Zero();
  16380. this._t1 = BABYLON.Vector3.Zero();
  16381. this._t2 = BABYLON.Vector3.Zero();
  16382. }
  16383. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16384. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16385. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16386. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16387. this._t1.subtractInPlace(this._t0);
  16388. this._t2.subtractInPlace(this._t0);
  16389. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16390. this._cachedTextureMatrix.m[0] = this._t1.x;
  16391. this._cachedTextureMatrix.m[1] = this._t1.y;
  16392. this._cachedTextureMatrix.m[2] = this._t1.z;
  16393. this._cachedTextureMatrix.m[4] = this._t2.x;
  16394. this._cachedTextureMatrix.m[5] = this._t2.y;
  16395. this._cachedTextureMatrix.m[6] = this._t2.z;
  16396. this._cachedTextureMatrix.m[8] = this._t0.x;
  16397. this._cachedTextureMatrix.m[9] = this._t0.y;
  16398. this._cachedTextureMatrix.m[10] = this._t0.z;
  16399. return this._cachedTextureMatrix;
  16400. };
  16401. Texture.prototype.getReflectionTextureMatrix = function () {
  16402. if (this.uOffset === this._cachedUOffset &&
  16403. this.vOffset === this._cachedVOffset &&
  16404. this.uScale === this._cachedUScale &&
  16405. this.vScale === this._cachedVScale &&
  16406. this.coordinatesMode === this._cachedCoordinatesMode) {
  16407. return this._cachedTextureMatrix;
  16408. }
  16409. if (!this._cachedTextureMatrix) {
  16410. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16411. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16412. }
  16413. this._cachedCoordinatesMode = this.coordinatesMode;
  16414. switch (this.coordinatesMode) {
  16415. case Texture.PLANAR_MODE:
  16416. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16417. this._cachedTextureMatrix[0] = this.uScale;
  16418. this._cachedTextureMatrix[5] = this.vScale;
  16419. this._cachedTextureMatrix[12] = this.uOffset;
  16420. this._cachedTextureMatrix[13] = this.vOffset;
  16421. break;
  16422. case Texture.PROJECTION_MODE:
  16423. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16424. this._projectionModeMatrix.m[0] = 0.5;
  16425. this._projectionModeMatrix.m[5] = -0.5;
  16426. this._projectionModeMatrix.m[10] = 0.0;
  16427. this._projectionModeMatrix.m[12] = 0.5;
  16428. this._projectionModeMatrix.m[13] = 0.5;
  16429. this._projectionModeMatrix.m[14] = 1.0;
  16430. this._projectionModeMatrix.m[15] = 1.0;
  16431. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16432. break;
  16433. default:
  16434. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16435. break;
  16436. }
  16437. return this._cachedTextureMatrix;
  16438. };
  16439. Texture.prototype.clone = function () {
  16440. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16441. // Base texture
  16442. newTexture.hasAlpha = this.hasAlpha;
  16443. newTexture.level = this.level;
  16444. newTexture.wrapU = this.wrapU;
  16445. newTexture.wrapV = this.wrapV;
  16446. newTexture.coordinatesIndex = this.coordinatesIndex;
  16447. newTexture.coordinatesMode = this.coordinatesMode;
  16448. // Texture
  16449. newTexture.uOffset = this.uOffset;
  16450. newTexture.vOffset = this.vOffset;
  16451. newTexture.uScale = this.uScale;
  16452. newTexture.vScale = this.vScale;
  16453. newTexture.uAng = this.uAng;
  16454. newTexture.vAng = this.vAng;
  16455. newTexture.wAng = this.wAng;
  16456. return newTexture;
  16457. };
  16458. // Statics
  16459. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16460. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16461. if (onLoad === void 0) { onLoad = null; }
  16462. if (onError === void 0) { onError = null; }
  16463. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16464. };
  16465. // Constants
  16466. Texture.NEAREST_SAMPLINGMODE = 1;
  16467. Texture.BILINEAR_SAMPLINGMODE = 2;
  16468. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16469. Texture.EXPLICIT_MODE = 0;
  16470. Texture.SPHERICAL_MODE = 1;
  16471. Texture.PLANAR_MODE = 2;
  16472. Texture.CUBIC_MODE = 3;
  16473. Texture.PROJECTION_MODE = 4;
  16474. Texture.SKYBOX_MODE = 5;
  16475. Texture.INVCUBIC_MODE = 6;
  16476. Texture.EQUIRECTANGULAR_MODE = 7;
  16477. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  16478. Texture.CLAMP_ADDRESSMODE = 0;
  16479. Texture.WRAP_ADDRESSMODE = 1;
  16480. Texture.MIRROR_ADDRESSMODE = 2;
  16481. return Texture;
  16482. })(BABYLON.BaseTexture);
  16483. BABYLON.Texture = Texture;
  16484. })(BABYLON || (BABYLON = {}));
  16485. var BABYLON;
  16486. (function (BABYLON) {
  16487. var CubeTexture = (function (_super) {
  16488. __extends(CubeTexture, _super);
  16489. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16490. _super.call(this, scene);
  16491. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16492. this.name = rootUrl;
  16493. this.url = rootUrl;
  16494. this._noMipmap = noMipmap;
  16495. this.hasAlpha = false;
  16496. if (!rootUrl) {
  16497. return;
  16498. }
  16499. this._texture = this._getFromCache(rootUrl, noMipmap);
  16500. if (!extensions) {
  16501. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16502. }
  16503. this._extensions = extensions;
  16504. if (!this._texture) {
  16505. if (!scene.useDelayedTextureLoading) {
  16506. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16507. }
  16508. else {
  16509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16510. }
  16511. }
  16512. this.isCube = true;
  16513. this._textureMatrix = BABYLON.Matrix.Identity();
  16514. }
  16515. CubeTexture.prototype.clone = function () {
  16516. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16517. // Base texture
  16518. newTexture.level = this.level;
  16519. newTexture.wrapU = this.wrapU;
  16520. newTexture.wrapV = this.wrapV;
  16521. newTexture.coordinatesIndex = this.coordinatesIndex;
  16522. newTexture.coordinatesMode = this.coordinatesMode;
  16523. return newTexture;
  16524. };
  16525. // Methods
  16526. CubeTexture.prototype.delayLoad = function () {
  16527. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16528. return;
  16529. }
  16530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16531. this._texture = this._getFromCache(this.url, this._noMipmap);
  16532. if (!this._texture) {
  16533. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16534. }
  16535. };
  16536. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16537. return this._textureMatrix;
  16538. };
  16539. return CubeTexture;
  16540. })(BABYLON.BaseTexture);
  16541. BABYLON.CubeTexture = CubeTexture;
  16542. })(BABYLON || (BABYLON = {}));
  16543. var BABYLON;
  16544. (function (BABYLON) {
  16545. var RenderTargetTexture = (function (_super) {
  16546. __extends(RenderTargetTexture, _super);
  16547. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16548. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16549. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16550. if (isCube === void 0) { isCube = false; }
  16551. _super.call(this, null, scene, !generateMipMaps);
  16552. this.isCube = isCube;
  16553. this.renderList = new Array();
  16554. this.renderParticles = true;
  16555. this.renderSprites = false;
  16556. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16557. this._currentRefreshId = -1;
  16558. this._refreshRate = 1;
  16559. this.name = name;
  16560. this.isRenderTarget = true;
  16561. this._size = size;
  16562. this._generateMipMaps = generateMipMaps;
  16563. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16564. if (isCube) {
  16565. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16566. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16567. this._textureMatrix = BABYLON.Matrix.Identity();
  16568. }
  16569. else {
  16570. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16571. }
  16572. // Rendering groups
  16573. this._renderingManager = new BABYLON.RenderingManager(scene);
  16574. }
  16575. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16576. get: function () {
  16577. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16583. get: function () {
  16584. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16585. },
  16586. enumerable: true,
  16587. configurable: true
  16588. });
  16589. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16590. get: function () {
  16591. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16592. },
  16593. enumerable: true,
  16594. configurable: true
  16595. });
  16596. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16597. this._currentRefreshId = -1;
  16598. };
  16599. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16600. get: function () {
  16601. return this._refreshRate;
  16602. },
  16603. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16604. set: function (value) {
  16605. this._refreshRate = value;
  16606. this.resetRefreshCounter();
  16607. },
  16608. enumerable: true,
  16609. configurable: true
  16610. });
  16611. RenderTargetTexture.prototype._shouldRender = function () {
  16612. if (this._currentRefreshId === -1) {
  16613. this._currentRefreshId = 1;
  16614. return true;
  16615. }
  16616. if (this.refreshRate === this._currentRefreshId) {
  16617. this._currentRefreshId = 1;
  16618. return true;
  16619. }
  16620. this._currentRefreshId++;
  16621. return false;
  16622. };
  16623. RenderTargetTexture.prototype.isReady = function () {
  16624. if (!this.getScene().renderTargetsEnabled) {
  16625. return false;
  16626. }
  16627. return _super.prototype.isReady.call(this);
  16628. };
  16629. RenderTargetTexture.prototype.getRenderSize = function () {
  16630. return this._size;
  16631. };
  16632. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16633. get: function () {
  16634. return true;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. RenderTargetTexture.prototype.scale = function (ratio) {
  16640. var newSize = this._size * ratio;
  16641. this.resize(newSize, this._generateMipMaps);
  16642. };
  16643. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16644. if (this.isCube) {
  16645. return this._textureMatrix;
  16646. }
  16647. return _super.prototype.getReflectionTextureMatrix.call(this);
  16648. };
  16649. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16650. this.releaseInternalTexture();
  16651. if (this.isCube) {
  16652. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16653. }
  16654. else {
  16655. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16656. }
  16657. };
  16658. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16659. var scene = this.getScene();
  16660. if (this._waitingRenderList) {
  16661. this.renderList = [];
  16662. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16663. var id = this._waitingRenderList[index];
  16664. this.renderList.push(scene.getMeshByID(id));
  16665. }
  16666. delete this._waitingRenderList;
  16667. }
  16668. if (this.renderList && this.renderList.length === 0) {
  16669. return;
  16670. }
  16671. // Prepare renderingManager
  16672. this._renderingManager.reset();
  16673. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16674. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16675. var mesh = currentRenderList[meshIndex];
  16676. if (mesh) {
  16677. if (!mesh.isReady()) {
  16678. // Reset _currentRefreshId
  16679. this.resetRefreshCounter();
  16680. continue;
  16681. }
  16682. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16683. mesh._activate(scene.getRenderId());
  16684. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16685. var subMesh = mesh.subMeshes[subIndex];
  16686. scene._activeIndices += subMesh.indexCount;
  16687. this._renderingManager.dispatch(subMesh);
  16688. }
  16689. }
  16690. }
  16691. }
  16692. if (this.isCube) {
  16693. for (var face = 0; face < 6; face++) {
  16694. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16695. }
  16696. }
  16697. else {
  16698. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16699. }
  16700. if (this.onAfterUnbind) {
  16701. this.onAfterUnbind();
  16702. }
  16703. scene.resetCachedMaterial();
  16704. };
  16705. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16706. var scene = this.getScene();
  16707. var engine = scene.getEngine();
  16708. // Bind
  16709. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16710. if (this.isCube) {
  16711. engine.bindFramebuffer(this._texture, faceIndex);
  16712. }
  16713. else {
  16714. engine.bindFramebuffer(this._texture);
  16715. }
  16716. }
  16717. if (this.onBeforeRender) {
  16718. this.onBeforeRender(faceIndex);
  16719. }
  16720. // Clear
  16721. if (this.onClear) {
  16722. this.onClear(engine);
  16723. }
  16724. else {
  16725. engine.clear(scene.clearColor, true, true);
  16726. }
  16727. if (!this._doNotChangeAspectRatio) {
  16728. scene.updateTransformMatrix(true);
  16729. }
  16730. // Render
  16731. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16732. if (useCameraPostProcess) {
  16733. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16734. }
  16735. if (!this._doNotChangeAspectRatio) {
  16736. scene.updateTransformMatrix(true);
  16737. }
  16738. if (this.onAfterRender) {
  16739. this.onAfterRender(faceIndex);
  16740. }
  16741. // Dump ?
  16742. if (dumpForDebug) {
  16743. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16744. }
  16745. // Unbind
  16746. if (!this.isCube || faceIndex === 5) {
  16747. if (this.isCube) {
  16748. if (faceIndex === 5) {
  16749. engine.generateMipMapsForCubemap(this._texture);
  16750. }
  16751. }
  16752. engine.unBindFramebuffer(this._texture, this.isCube);
  16753. }
  16754. };
  16755. RenderTargetTexture.prototype.clone = function () {
  16756. var textureSize = this.getSize();
  16757. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16758. // Base texture
  16759. newTexture.hasAlpha = this.hasAlpha;
  16760. newTexture.level = this.level;
  16761. // RenderTarget Texture
  16762. newTexture.coordinatesMode = this.coordinatesMode;
  16763. newTexture.renderList = this.renderList.slice(0);
  16764. return newTexture;
  16765. };
  16766. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16767. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16768. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16769. return RenderTargetTexture;
  16770. })(BABYLON.Texture);
  16771. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16772. })(BABYLON || (BABYLON = {}));
  16773. var BABYLON;
  16774. (function (BABYLON) {
  16775. var ProceduralTexture = (function (_super) {
  16776. __extends(ProceduralTexture, _super);
  16777. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16778. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16779. _super.call(this, null, scene, !generateMipMaps);
  16780. this.isEnabled = true;
  16781. this._currentRefreshId = -1;
  16782. this._refreshRate = 1;
  16783. this._vertexDeclaration = [2];
  16784. this._vertexStrideSize = 2 * 4;
  16785. this._uniforms = new Array();
  16786. this._samplers = new Array();
  16787. this._textures = new Array();
  16788. this._floats = new Array();
  16789. this._floatsArrays = {};
  16790. this._colors3 = new Array();
  16791. this._colors4 = new Array();
  16792. this._vectors2 = new Array();
  16793. this._vectors3 = new Array();
  16794. this._matrices = new Array();
  16795. this._fallbackTextureUsed = false;
  16796. scene._proceduralTextures.push(this);
  16797. this.name = name;
  16798. this.isRenderTarget = true;
  16799. this._size = size;
  16800. this._generateMipMaps = generateMipMaps;
  16801. this.setFragment(fragment);
  16802. this._fallbackTexture = fallbackTexture;
  16803. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16804. // VBO
  16805. var vertices = [];
  16806. vertices.push(1, 1);
  16807. vertices.push(-1, 1);
  16808. vertices.push(-1, -1);
  16809. vertices.push(1, -1);
  16810. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16811. // Indices
  16812. var indices = [];
  16813. indices.push(0);
  16814. indices.push(1);
  16815. indices.push(2);
  16816. indices.push(0);
  16817. indices.push(2);
  16818. indices.push(3);
  16819. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16820. }
  16821. ProceduralTexture.prototype.reset = function () {
  16822. if (this._effect === undefined) {
  16823. return;
  16824. }
  16825. var engine = this.getScene().getEngine();
  16826. engine._releaseEffect(this._effect);
  16827. };
  16828. ProceduralTexture.prototype.isReady = function () {
  16829. var _this = this;
  16830. var engine = this.getScene().getEngine();
  16831. var shaders;
  16832. if (!this._fragment) {
  16833. return false;
  16834. }
  16835. if (this._fallbackTextureUsed) {
  16836. return true;
  16837. }
  16838. if (this._fragment.fragmentElement !== undefined) {
  16839. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16840. }
  16841. else {
  16842. shaders = { vertex: "procedural", fragment: this._fragment };
  16843. }
  16844. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16845. _this.releaseInternalTexture();
  16846. if (_this._fallbackTexture) {
  16847. _this._texture = _this._fallbackTexture._texture;
  16848. _this._texture.references++;
  16849. }
  16850. _this._fallbackTextureUsed = true;
  16851. });
  16852. return this._effect.isReady();
  16853. };
  16854. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16855. this._currentRefreshId = -1;
  16856. };
  16857. ProceduralTexture.prototype.setFragment = function (fragment) {
  16858. this._fragment = fragment;
  16859. };
  16860. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16861. get: function () {
  16862. return this._refreshRate;
  16863. },
  16864. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16865. set: function (value) {
  16866. this._refreshRate = value;
  16867. this.resetRefreshCounter();
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. ProceduralTexture.prototype._shouldRender = function () {
  16873. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16874. return false;
  16875. }
  16876. if (this._fallbackTextureUsed) {
  16877. return false;
  16878. }
  16879. if (this._currentRefreshId === -1) {
  16880. this._currentRefreshId = 1;
  16881. return true;
  16882. }
  16883. if (this.refreshRate === this._currentRefreshId) {
  16884. this._currentRefreshId = 1;
  16885. return true;
  16886. }
  16887. this._currentRefreshId++;
  16888. return false;
  16889. };
  16890. ProceduralTexture.prototype.getRenderSize = function () {
  16891. return this._size;
  16892. };
  16893. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16894. if (this._fallbackTextureUsed) {
  16895. return;
  16896. }
  16897. this.releaseInternalTexture();
  16898. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16899. };
  16900. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16901. if (this._uniforms.indexOf(uniformName) === -1) {
  16902. this._uniforms.push(uniformName);
  16903. }
  16904. };
  16905. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16906. if (this._samplers.indexOf(name) === -1) {
  16907. this._samplers.push(name);
  16908. }
  16909. this._textures[name] = texture;
  16910. return this;
  16911. };
  16912. ProceduralTexture.prototype.setFloat = function (name, value) {
  16913. this._checkUniform(name);
  16914. this._floats[name] = value;
  16915. return this;
  16916. };
  16917. ProceduralTexture.prototype.setFloats = function (name, value) {
  16918. this._checkUniform(name);
  16919. this._floatsArrays[name] = value;
  16920. return this;
  16921. };
  16922. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16923. this._checkUniform(name);
  16924. this._colors3[name] = value;
  16925. return this;
  16926. };
  16927. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16928. this._checkUniform(name);
  16929. this._colors4[name] = value;
  16930. return this;
  16931. };
  16932. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16933. this._checkUniform(name);
  16934. this._vectors2[name] = value;
  16935. return this;
  16936. };
  16937. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16938. this._checkUniform(name);
  16939. this._vectors3[name] = value;
  16940. return this;
  16941. };
  16942. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16943. this._checkUniform(name);
  16944. this._matrices[name] = value;
  16945. return this;
  16946. };
  16947. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16948. var scene = this.getScene();
  16949. var engine = scene.getEngine();
  16950. engine.bindFramebuffer(this._texture);
  16951. // Clear
  16952. engine.clear(scene.clearColor, true, true);
  16953. // Render
  16954. engine.enableEffect(this._effect);
  16955. engine.setState(false);
  16956. // Texture
  16957. for (var name in this._textures) {
  16958. this._effect.setTexture(name, this._textures[name]);
  16959. }
  16960. // Float
  16961. for (name in this._floats) {
  16962. this._effect.setFloat(name, this._floats[name]);
  16963. }
  16964. // Floats
  16965. for (name in this._floatsArrays) {
  16966. this._effect.setArray(name, this._floatsArrays[name]);
  16967. }
  16968. // Color3
  16969. for (name in this._colors3) {
  16970. this._effect.setColor3(name, this._colors3[name]);
  16971. }
  16972. // Color4
  16973. for (name in this._colors4) {
  16974. var color = this._colors4[name];
  16975. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16976. }
  16977. // Vector2
  16978. for (name in this._vectors2) {
  16979. this._effect.setVector2(name, this._vectors2[name]);
  16980. }
  16981. // Vector3
  16982. for (name in this._vectors3) {
  16983. this._effect.setVector3(name, this._vectors3[name]);
  16984. }
  16985. // Matrix
  16986. for (name in this._matrices) {
  16987. this._effect.setMatrix(name, this._matrices[name]);
  16988. }
  16989. // VBOs
  16990. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16991. // Draw order
  16992. engine.draw(true, 0, 6);
  16993. // Unbind
  16994. engine.unBindFramebuffer(this._texture);
  16995. };
  16996. ProceduralTexture.prototype.clone = function () {
  16997. var textureSize = this.getSize();
  16998. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16999. // Base texture
  17000. newTexture.hasAlpha = this.hasAlpha;
  17001. newTexture.level = this.level;
  17002. // RenderTarget Texture
  17003. newTexture.coordinatesMode = this.coordinatesMode;
  17004. return newTexture;
  17005. };
  17006. ProceduralTexture.prototype.dispose = function () {
  17007. var index = this.getScene()._proceduralTextures.indexOf(this);
  17008. if (index >= 0) {
  17009. this.getScene()._proceduralTextures.splice(index, 1);
  17010. }
  17011. _super.prototype.dispose.call(this);
  17012. };
  17013. return ProceduralTexture;
  17014. })(BABYLON.Texture);
  17015. BABYLON.ProceduralTexture = ProceduralTexture;
  17016. })(BABYLON || (BABYLON = {}));
  17017. var BABYLON;
  17018. (function (BABYLON) {
  17019. var MirrorTexture = (function (_super) {
  17020. __extends(MirrorTexture, _super);
  17021. function MirrorTexture(name, size, scene, generateMipMaps) {
  17022. var _this = this;
  17023. _super.call(this, name, size, scene, generateMipMaps, true);
  17024. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17025. this._transformMatrix = BABYLON.Matrix.Zero();
  17026. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17027. this.onBeforeRender = function () {
  17028. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17029. _this._savedViewMatrix = scene.getViewMatrix();
  17030. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17031. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17032. scene.clipPlane = _this.mirrorPlane;
  17033. scene.getEngine().cullBackFaces = false;
  17034. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17035. };
  17036. this.onAfterRender = function () {
  17037. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17038. scene.getEngine().cullBackFaces = true;
  17039. scene._mirroredCameraPosition = null;
  17040. delete scene.clipPlane;
  17041. };
  17042. }
  17043. MirrorTexture.prototype.clone = function () {
  17044. var textureSize = this.getSize();
  17045. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17046. // Base texture
  17047. newTexture.hasAlpha = this.hasAlpha;
  17048. newTexture.level = this.level;
  17049. // Mirror Texture
  17050. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17051. newTexture.renderList = this.renderList.slice(0);
  17052. return newTexture;
  17053. };
  17054. return MirrorTexture;
  17055. })(BABYLON.RenderTargetTexture);
  17056. BABYLON.MirrorTexture = MirrorTexture;
  17057. })(BABYLON || (BABYLON = {}));
  17058. var BABYLON;
  17059. (function (BABYLON) {
  17060. var DynamicTexture = (function (_super) {
  17061. __extends(DynamicTexture, _super);
  17062. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17064. _super.call(this, null, scene, !generateMipMaps);
  17065. this.name = name;
  17066. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17067. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17068. this._generateMipMaps = generateMipMaps;
  17069. if (options.getContext) {
  17070. this._canvas = options;
  17071. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17072. }
  17073. else {
  17074. this._canvas = document.createElement("canvas");
  17075. if (options.width) {
  17076. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17077. }
  17078. else {
  17079. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17080. }
  17081. }
  17082. var textureSize = this.getSize();
  17083. this._canvas.width = textureSize.width;
  17084. this._canvas.height = textureSize.height;
  17085. this._context = this._canvas.getContext("2d");
  17086. }
  17087. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17088. get: function () {
  17089. return true;
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. DynamicTexture.prototype.scale = function (ratio) {
  17095. var textureSize = this.getSize();
  17096. textureSize.width *= ratio;
  17097. textureSize.height *= ratio;
  17098. this._canvas.width = textureSize.width;
  17099. this._canvas.height = textureSize.height;
  17100. this.releaseInternalTexture();
  17101. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17102. };
  17103. DynamicTexture.prototype.getContext = function () {
  17104. return this._context;
  17105. };
  17106. DynamicTexture.prototype.clear = function () {
  17107. var size = this.getSize();
  17108. this._context.fillRect(0, 0, size.width, size.height);
  17109. };
  17110. DynamicTexture.prototype.update = function (invertY) {
  17111. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17112. };
  17113. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17114. if (update === void 0) { update = true; }
  17115. var size = this.getSize();
  17116. if (clearColor) {
  17117. this._context.fillStyle = clearColor;
  17118. this._context.fillRect(0, 0, size.width, size.height);
  17119. }
  17120. this._context.font = font;
  17121. if (x === null) {
  17122. var textSize = this._context.measureText(text);
  17123. x = (size.width - textSize.width) / 2;
  17124. }
  17125. this._context.fillStyle = color;
  17126. this._context.fillText(text, x, y);
  17127. if (update) {
  17128. this.update(invertY);
  17129. }
  17130. };
  17131. DynamicTexture.prototype.clone = function () {
  17132. var textureSize = this.getSize();
  17133. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17134. // Base texture
  17135. newTexture.hasAlpha = this.hasAlpha;
  17136. newTexture.level = this.level;
  17137. // Dynamic Texture
  17138. newTexture.wrapU = this.wrapU;
  17139. newTexture.wrapV = this.wrapV;
  17140. return newTexture;
  17141. };
  17142. return DynamicTexture;
  17143. })(BABYLON.Texture);
  17144. BABYLON.DynamicTexture = DynamicTexture;
  17145. })(BABYLON || (BABYLON = {}));
  17146. var BABYLON;
  17147. (function (BABYLON) {
  17148. var VideoTexture = (function (_super) {
  17149. __extends(VideoTexture, _super);
  17150. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17151. var _this = this;
  17152. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17153. if (invertY === void 0) { invertY = false; }
  17154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17155. _super.call(this, null, scene, !generateMipMaps, invertY);
  17156. this._autoLaunch = true;
  17157. this.name = name;
  17158. this.video = document.createElement("video");
  17159. this.video.autoplay = false;
  17160. this.video.loop = true;
  17161. this.video.addEventListener("canplaythrough", function () {
  17162. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17163. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17164. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17165. }
  17166. else {
  17167. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17168. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17169. generateMipMaps = false;
  17170. }
  17171. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17172. _this._texture.isReady = true;
  17173. });
  17174. urls.forEach(function (url) {
  17175. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17176. var source = document.createElement("source");
  17177. source.src = url;
  17178. _this.video.appendChild(source);
  17179. });
  17180. this._lastUpdate = BABYLON.Tools.Now;
  17181. }
  17182. VideoTexture.prototype.update = function () {
  17183. if (this._autoLaunch) {
  17184. this._autoLaunch = false;
  17185. this.video.play();
  17186. }
  17187. var now = BABYLON.Tools.Now;
  17188. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17189. return false;
  17190. }
  17191. this._lastUpdate = now;
  17192. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17193. return true;
  17194. };
  17195. return VideoTexture;
  17196. })(BABYLON.Texture);
  17197. BABYLON.VideoTexture = VideoTexture;
  17198. })(BABYLON || (BABYLON = {}));
  17199. var BABYLON;
  17200. (function (BABYLON) {
  17201. var CustomProceduralTexture = (function (_super) {
  17202. __extends(CustomProceduralTexture, _super);
  17203. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17204. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17205. this._animate = true;
  17206. this._time = 0;
  17207. this._texturePath = texturePath;
  17208. //Try to load json
  17209. this.loadJson(texturePath);
  17210. this.refreshRate = 1;
  17211. }
  17212. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17213. var _this = this;
  17214. var that = this;
  17215. function noConfigFile() {
  17216. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17217. try {
  17218. that.setFragment(that._texturePath);
  17219. }
  17220. catch (ex) {
  17221. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17222. }
  17223. }
  17224. var configFileUrl = jsonUrl + "/config.json";
  17225. var xhr = new XMLHttpRequest();
  17226. xhr.open("GET", configFileUrl, true);
  17227. xhr.addEventListener("load", function () {
  17228. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17229. try {
  17230. _this._config = JSON.parse(xhr.response);
  17231. _this.updateShaderUniforms();
  17232. _this.updateTextures();
  17233. _this.setFragment(_this._texturePath + "/custom");
  17234. _this._animate = _this._config.animate;
  17235. _this.refreshRate = _this._config.refreshrate;
  17236. }
  17237. catch (ex) {
  17238. noConfigFile();
  17239. }
  17240. }
  17241. else {
  17242. noConfigFile();
  17243. }
  17244. }, false);
  17245. xhr.addEventListener("error", function () {
  17246. noConfigFile();
  17247. }, false);
  17248. try {
  17249. xhr.send();
  17250. }
  17251. catch (ex) {
  17252. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17253. }
  17254. };
  17255. CustomProceduralTexture.prototype.isReady = function () {
  17256. if (!_super.prototype.isReady.call(this)) {
  17257. return false;
  17258. }
  17259. for (var name in this._textures) {
  17260. var texture = this._textures[name];
  17261. if (!texture.isReady()) {
  17262. return false;
  17263. }
  17264. }
  17265. return true;
  17266. };
  17267. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17268. if (this._animate) {
  17269. this._time += this.getScene().getAnimationRatio() * 0.03;
  17270. this.updateShaderUniforms();
  17271. }
  17272. _super.prototype.render.call(this, useCameraPostProcess);
  17273. };
  17274. CustomProceduralTexture.prototype.updateTextures = function () {
  17275. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17276. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17277. }
  17278. };
  17279. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17280. if (this._config) {
  17281. for (var j = 0; j < this._config.uniforms.length; j++) {
  17282. var uniform = this._config.uniforms[j];
  17283. switch (uniform.type) {
  17284. case "float":
  17285. this.setFloat(uniform.name, uniform.value);
  17286. break;
  17287. case "color3":
  17288. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17289. break;
  17290. case "color4":
  17291. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17292. break;
  17293. case "vector2":
  17294. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17295. break;
  17296. case "vector3":
  17297. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17298. break;
  17299. }
  17300. }
  17301. }
  17302. this.setFloat("time", this._time);
  17303. };
  17304. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17305. get: function () {
  17306. return this._animate;
  17307. },
  17308. set: function (value) {
  17309. this._animate = value;
  17310. },
  17311. enumerable: true,
  17312. configurable: true
  17313. });
  17314. return CustomProceduralTexture;
  17315. })(BABYLON.ProceduralTexture);
  17316. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17317. })(BABYLON || (BABYLON = {}));
  17318. var BABYLON;
  17319. (function (BABYLON) {
  17320. var EffectFallbacks = (function () {
  17321. function EffectFallbacks() {
  17322. this._defines = {};
  17323. this._currentRank = 32;
  17324. this._maxRank = -1;
  17325. }
  17326. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17327. if (!this._defines[rank]) {
  17328. if (rank < this._currentRank) {
  17329. this._currentRank = rank;
  17330. }
  17331. if (rank > this._maxRank) {
  17332. this._maxRank = rank;
  17333. }
  17334. this._defines[rank] = new Array();
  17335. }
  17336. this._defines[rank].push(define);
  17337. };
  17338. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17339. this._meshRank = rank;
  17340. this._mesh = mesh;
  17341. if (rank > this._maxRank) {
  17342. this._maxRank = rank;
  17343. }
  17344. };
  17345. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17346. get: function () {
  17347. return this._currentRank <= this._maxRank;
  17348. },
  17349. enumerable: true,
  17350. configurable: true
  17351. });
  17352. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17353. var currentFallbacks = this._defines[this._currentRank];
  17354. for (var index = 0; index < currentFallbacks.length; index++) {
  17355. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17356. }
  17357. if (this._mesh && this._currentRank === this._meshRank) {
  17358. this._mesh.computeBonesUsingShaders = false;
  17359. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17360. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17361. }
  17362. this._currentRank++;
  17363. return currentDefines;
  17364. };
  17365. return EffectFallbacks;
  17366. })();
  17367. BABYLON.EffectFallbacks = EffectFallbacks;
  17368. var Effect = (function () {
  17369. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17370. var _this = this;
  17371. this._isReady = false;
  17372. this._compilationError = "";
  17373. this._valueCache = [];
  17374. this._engine = engine;
  17375. this.name = baseName;
  17376. this.defines = defines;
  17377. this._uniformsNames = uniformsNames.concat(samplers);
  17378. this._samplers = samplers;
  17379. this._attributesNames = attributesNames;
  17380. this.onError = onError;
  17381. this.onCompiled = onCompiled;
  17382. var vertexSource;
  17383. var fragmentSource;
  17384. if (baseName.vertexElement) {
  17385. vertexSource = document.getElementById(baseName.vertexElement);
  17386. if (!vertexSource) {
  17387. vertexSource = baseName.vertexElement;
  17388. }
  17389. }
  17390. else {
  17391. vertexSource = baseName.vertex || baseName;
  17392. }
  17393. if (baseName.fragmentElement) {
  17394. fragmentSource = document.getElementById(baseName.fragmentElement);
  17395. if (!fragmentSource) {
  17396. fragmentSource = baseName.fragmentElement;
  17397. }
  17398. }
  17399. else {
  17400. fragmentSource = baseName.fragment || baseName;
  17401. }
  17402. this._loadVertexShader(vertexSource, function (vertexCode) {
  17403. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17404. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17405. });
  17406. });
  17407. }
  17408. // Properties
  17409. Effect.prototype.isReady = function () {
  17410. return this._isReady;
  17411. };
  17412. Effect.prototype.getProgram = function () {
  17413. return this._program;
  17414. };
  17415. Effect.prototype.getAttributesNames = function () {
  17416. return this._attributesNames;
  17417. };
  17418. Effect.prototype.getAttributeLocation = function (index) {
  17419. return this._attributes[index];
  17420. };
  17421. Effect.prototype.getAttributeLocationByName = function (name) {
  17422. var index = this._attributesNames.indexOf(name);
  17423. return this._attributes[index];
  17424. };
  17425. Effect.prototype.getAttributesCount = function () {
  17426. return this._attributes.length;
  17427. };
  17428. Effect.prototype.getUniformIndex = function (uniformName) {
  17429. return this._uniformsNames.indexOf(uniformName);
  17430. };
  17431. Effect.prototype.getUniform = function (uniformName) {
  17432. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17433. };
  17434. Effect.prototype.getSamplers = function () {
  17435. return this._samplers;
  17436. };
  17437. Effect.prototype.getCompilationError = function () {
  17438. return this._compilationError;
  17439. };
  17440. // Methods
  17441. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17442. // DOM element ?
  17443. if (vertex instanceof HTMLElement) {
  17444. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17445. callback(vertexCode);
  17446. return;
  17447. }
  17448. // Is in local store ?
  17449. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17450. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17451. return;
  17452. }
  17453. var vertexShaderUrl;
  17454. if (vertex[0] === "." || vertex[0] === "/") {
  17455. vertexShaderUrl = vertex;
  17456. }
  17457. else {
  17458. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17459. }
  17460. // Vertex shader
  17461. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17462. };
  17463. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17464. // DOM element ?
  17465. if (fragment instanceof HTMLElement) {
  17466. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17467. callback(fragmentCode);
  17468. return;
  17469. }
  17470. // Is in local store ?
  17471. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17472. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17473. return;
  17474. }
  17475. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17476. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17477. return;
  17478. }
  17479. var fragmentShaderUrl;
  17480. if (fragment[0] === "." || fragment[0] === "/") {
  17481. fragmentShaderUrl = fragment;
  17482. }
  17483. else {
  17484. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17485. }
  17486. // Fragment shader
  17487. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17488. };
  17489. Effect.prototype._dumpShadersName = function () {
  17490. if (this.name.vertexElement) {
  17491. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17492. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17493. }
  17494. else if (this.name.vertex) {
  17495. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17496. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17497. }
  17498. else {
  17499. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17500. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17501. }
  17502. };
  17503. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17504. try {
  17505. var engine = this._engine;
  17506. if (!engine.getCaps().highPrecisionShaderSupported) {
  17507. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17508. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17509. }
  17510. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17511. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17512. this._attributes = engine.getAttributes(this._program, attributesNames);
  17513. for (var index = 0; index < this._samplers.length; index++) {
  17514. var sampler = this.getUniform(this._samplers[index]);
  17515. if (sampler == null) {
  17516. this._samplers.splice(index, 1);
  17517. index--;
  17518. }
  17519. }
  17520. engine.bindSamplers(this);
  17521. this._isReady = true;
  17522. if (this.onCompiled) {
  17523. this.onCompiled(this);
  17524. }
  17525. }
  17526. catch (e) {
  17527. // Is it a problem with precision?
  17528. if (e.message.indexOf("highp") !== -1) {
  17529. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17530. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17531. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17532. return;
  17533. }
  17534. // Let's go through fallbacks then
  17535. if (fallbacks && fallbacks.isMoreFallbacks) {
  17536. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17537. this._dumpShadersName();
  17538. defines = fallbacks.reduce(defines);
  17539. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17540. }
  17541. else {
  17542. BABYLON.Tools.Error("Unable to compile effect: ");
  17543. this._dumpShadersName();
  17544. BABYLON.Tools.Error("Defines: " + defines);
  17545. BABYLON.Tools.Error("Error: " + e.message);
  17546. this._compilationError = e.message;
  17547. if (this.onError) {
  17548. this.onError(this, this._compilationError);
  17549. }
  17550. }
  17551. }
  17552. };
  17553. Object.defineProperty(Effect.prototype, "isSupported", {
  17554. get: function () {
  17555. return this._compilationError === "";
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. Effect.prototype._bindTexture = function (channel, texture) {
  17561. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17562. };
  17563. Effect.prototype.setTexture = function (channel, texture) {
  17564. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17565. };
  17566. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17567. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17568. };
  17569. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17570. if (!this._valueCache[uniformName]) {
  17571. this._valueCache[uniformName] = new BABYLON.Matrix();
  17572. }
  17573. for (var index = 0; index < 16; index++) {
  17574. this._valueCache[uniformName].m[index] = matrix.m[index];
  17575. }
  17576. };
  17577. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17578. if (!this._valueCache[uniformName]) {
  17579. this._valueCache[uniformName] = [x, y];
  17580. return;
  17581. }
  17582. this._valueCache[uniformName][0] = x;
  17583. this._valueCache[uniformName][1] = y;
  17584. };
  17585. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17586. if (!this._valueCache[uniformName]) {
  17587. this._valueCache[uniformName] = [x, y, z];
  17588. return;
  17589. }
  17590. this._valueCache[uniformName][0] = x;
  17591. this._valueCache[uniformName][1] = y;
  17592. this._valueCache[uniformName][2] = z;
  17593. };
  17594. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17595. if (!this._valueCache[uniformName]) {
  17596. this._valueCache[uniformName] = [x, y, z, w];
  17597. return;
  17598. }
  17599. this._valueCache[uniformName][0] = x;
  17600. this._valueCache[uniformName][1] = y;
  17601. this._valueCache[uniformName][2] = z;
  17602. this._valueCache[uniformName][3] = w;
  17603. };
  17604. Effect.prototype.setArray = function (uniformName, array) {
  17605. this._engine.setArray(this.getUniform(uniformName), array);
  17606. return this;
  17607. };
  17608. Effect.prototype.setArray2 = function (uniformName, array) {
  17609. this._engine.setArray2(this.getUniform(uniformName), array);
  17610. return this;
  17611. };
  17612. Effect.prototype.setArray3 = function (uniformName, array) {
  17613. this._engine.setArray3(this.getUniform(uniformName), array);
  17614. return this;
  17615. };
  17616. Effect.prototype.setArray4 = function (uniformName, array) {
  17617. this._engine.setArray4(this.getUniform(uniformName), array);
  17618. return this;
  17619. };
  17620. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17621. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17622. return this;
  17623. };
  17624. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17625. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17626. return this;
  17627. this._cacheMatrix(uniformName, matrix);
  17628. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17629. return this;
  17630. };
  17631. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17632. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17633. return this;
  17634. };
  17635. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  17636. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  17637. return this;
  17638. };
  17639. Effect.prototype.setFloat = function (uniformName, value) {
  17640. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17641. return this;
  17642. this._valueCache[uniformName] = value;
  17643. this._engine.setFloat(this.getUniform(uniformName), value);
  17644. return this;
  17645. };
  17646. Effect.prototype.setBool = function (uniformName, bool) {
  17647. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17648. return this;
  17649. this._valueCache[uniformName] = bool;
  17650. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17651. return this;
  17652. };
  17653. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17654. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17655. return this;
  17656. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17657. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17658. return this;
  17659. };
  17660. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17661. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17662. return this;
  17663. this._cacheFloat2(uniformName, x, y);
  17664. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17665. return this;
  17666. };
  17667. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17668. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17669. return this;
  17670. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17671. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17672. return this;
  17673. };
  17674. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17675. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17676. return this;
  17677. this._cacheFloat3(uniformName, x, y, z);
  17678. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17679. return this;
  17680. };
  17681. Effect.prototype.setVector4 = function (uniformName, vector4) {
  17682. 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)
  17683. return this;
  17684. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  17685. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  17686. return this;
  17687. };
  17688. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17689. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17690. return this;
  17691. this._cacheFloat4(uniformName, x, y, z, w);
  17692. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17693. return this;
  17694. };
  17695. Effect.prototype.setColor3 = function (uniformName, color3) {
  17696. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17697. return this;
  17698. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17699. this._engine.setColor3(this.getUniform(uniformName), color3);
  17700. return this;
  17701. };
  17702. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17703. 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)
  17704. return this;
  17705. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17706. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17707. return this;
  17708. };
  17709. // Statics
  17710. Effect.ShadersStore = {};
  17711. return Effect;
  17712. })();
  17713. BABYLON.Effect = Effect;
  17714. })(BABYLON || (BABYLON = {}));
  17715. var BABYLON;
  17716. (function (BABYLON) {
  17717. var MaterialDefines = (function () {
  17718. function MaterialDefines() {
  17719. }
  17720. MaterialDefines.prototype.isEqual = function (other) {
  17721. for (var index = 0; index < this._keys.length; index++) {
  17722. var prop = this._keys[index];
  17723. if (this[prop] !== other[prop]) {
  17724. return false;
  17725. }
  17726. }
  17727. return true;
  17728. };
  17729. MaterialDefines.prototype.cloneTo = function (other) {
  17730. for (var index = 0; index < this._keys.length; index++) {
  17731. var prop = this._keys[index];
  17732. other[prop] = this[prop];
  17733. }
  17734. };
  17735. MaterialDefines.prototype.reset = function () {
  17736. for (var index = 0; index < this._keys.length; index++) {
  17737. var prop = this._keys[index];
  17738. if (typeof (this[prop]) === "number") {
  17739. this[prop] = 0;
  17740. }
  17741. else {
  17742. this[prop] = false;
  17743. }
  17744. }
  17745. };
  17746. MaterialDefines.prototype.toString = function () {
  17747. var result = "";
  17748. for (var index = 0; index < this._keys.length; index++) {
  17749. var prop = this._keys[index];
  17750. if (typeof (this[prop]) === "number") {
  17751. result += "#define " + prop + " " + this[prop] + "\n";
  17752. }
  17753. else if (this[prop]) {
  17754. result += "#define " + prop + "\n";
  17755. }
  17756. }
  17757. return result;
  17758. };
  17759. return MaterialDefines;
  17760. })();
  17761. BABYLON.MaterialDefines = MaterialDefines;
  17762. var Material = (function () {
  17763. function Material(name, scene, doNotAdd) {
  17764. this.name = name;
  17765. this.checkReadyOnEveryCall = false;
  17766. this.checkReadyOnlyOnce = false;
  17767. this.state = "";
  17768. this.alpha = 1.0;
  17769. this.backFaceCulling = true;
  17770. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  17771. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  17772. this.disableDepthWrite = false;
  17773. this.fogEnabled = true;
  17774. this._wasPreviouslyReady = false;
  17775. this._fillMode = Material.TriangleFillMode;
  17776. this.pointSize = 1.0;
  17777. this.zOffset = 0;
  17778. this.id = name;
  17779. this._scene = scene;
  17780. if (!doNotAdd) {
  17781. scene.materials.push(this);
  17782. }
  17783. }
  17784. Object.defineProperty(Material, "TriangleFillMode", {
  17785. get: function () {
  17786. return Material._TriangleFillMode;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. Object.defineProperty(Material, "WireFrameFillMode", {
  17792. get: function () {
  17793. return Material._WireFrameFillMode;
  17794. },
  17795. enumerable: true,
  17796. configurable: true
  17797. });
  17798. Object.defineProperty(Material, "PointFillMode", {
  17799. get: function () {
  17800. return Material._PointFillMode;
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  17806. get: function () {
  17807. return Material._ClockWiseSideOrientation;
  17808. },
  17809. enumerable: true,
  17810. configurable: true
  17811. });
  17812. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  17813. get: function () {
  17814. return Material._CounterClockWiseSideOrientation;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(Material.prototype, "wireframe", {
  17820. get: function () {
  17821. return this._fillMode === Material.WireFrameFillMode;
  17822. },
  17823. set: function (value) {
  17824. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(Material.prototype, "pointsCloud", {
  17830. get: function () {
  17831. return this._fillMode === Material.PointFillMode;
  17832. },
  17833. set: function (value) {
  17834. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(Material.prototype, "fillMode", {
  17840. get: function () {
  17841. return this._fillMode;
  17842. },
  17843. set: function (value) {
  17844. this._fillMode = value;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Material.prototype.isReady = function (mesh, useInstances) {
  17850. return true;
  17851. };
  17852. Material.prototype.getEffect = function () {
  17853. return this._effect;
  17854. };
  17855. Material.prototype.getScene = function () {
  17856. return this._scene;
  17857. };
  17858. Material.prototype.needAlphaBlending = function () {
  17859. return (this.alpha < 1.0);
  17860. };
  17861. Material.prototype.needAlphaTesting = function () {
  17862. return false;
  17863. };
  17864. Material.prototype.getAlphaTestTexture = function () {
  17865. return null;
  17866. };
  17867. Material.prototype.trackCreation = function (onCompiled, onError) {
  17868. };
  17869. Material.prototype.markDirty = function () {
  17870. this._wasPreviouslyReady = false;
  17871. };
  17872. Material.prototype._preBind = function () {
  17873. var engine = this._scene.getEngine();
  17874. engine.enableEffect(this._effect);
  17875. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  17876. };
  17877. Material.prototype.bind = function (world, mesh) {
  17878. this._scene._cachedMaterial = this;
  17879. if (this.onBind) {
  17880. this.onBind(this, mesh);
  17881. }
  17882. if (this.disableDepthWrite) {
  17883. var engine = this._scene.getEngine();
  17884. this._cachedDepthWriteState = engine.getDepthWrite();
  17885. engine.setDepthWrite(false);
  17886. }
  17887. };
  17888. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17889. };
  17890. Material.prototype.unbind = function () {
  17891. if (this.disableDepthWrite) {
  17892. var engine = this._scene.getEngine();
  17893. engine.setDepthWrite(this._cachedDepthWriteState);
  17894. }
  17895. };
  17896. Material.prototype.clone = function (name) {
  17897. return null;
  17898. };
  17899. Material.prototype.getBindedMeshes = function () {
  17900. var result = new Array();
  17901. for (var index = 0; index < this._scene.meshes.length; index++) {
  17902. var mesh = this._scene.meshes[index];
  17903. if (mesh.material === this) {
  17904. result.push(mesh);
  17905. }
  17906. }
  17907. return result;
  17908. };
  17909. Material.prototype.dispose = function (forceDisposeEffect) {
  17910. // Animations
  17911. this.getScene().stopAnimation(this);
  17912. // Remove from scene
  17913. var index = this._scene.materials.indexOf(this);
  17914. if (index >= 0) {
  17915. this._scene.materials.splice(index, 1);
  17916. }
  17917. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17918. if (forceDisposeEffect && this._effect) {
  17919. this._scene.getEngine()._releaseEffect(this._effect);
  17920. this._effect = null;
  17921. }
  17922. // Remove from meshes
  17923. for (index = 0; index < this._scene.meshes.length; index++) {
  17924. var mesh = this._scene.meshes[index];
  17925. if (mesh.material === this) {
  17926. mesh.material = null;
  17927. }
  17928. }
  17929. // Callback
  17930. if (this.onDispose) {
  17931. this.onDispose();
  17932. }
  17933. };
  17934. Material.prototype.copyTo = function (other) {
  17935. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  17936. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17937. other.alpha = this.alpha;
  17938. other.fillMode = this.fillMode;
  17939. other.backFaceCulling = this.backFaceCulling;
  17940. other.fogEnabled = this.fogEnabled;
  17941. other.wireframe = this.wireframe;
  17942. other.zOffset = this.zOffset;
  17943. other.alphaMode = this.alphaMode;
  17944. other.sideOrientation = this.sideOrientation;
  17945. other.disableDepthWrite = this.disableDepthWrite;
  17946. other.pointSize = this.pointSize;
  17947. other.pointsCloud = this.pointsCloud;
  17948. };
  17949. Material._TriangleFillMode = 0;
  17950. Material._WireFrameFillMode = 1;
  17951. Material._PointFillMode = 2;
  17952. Material._ClockWiseSideOrientation = 0;
  17953. Material._CounterClockWiseSideOrientation = 1;
  17954. return Material;
  17955. })();
  17956. BABYLON.Material = Material;
  17957. })(BABYLON || (BABYLON = {}));
  17958. var BABYLON;
  17959. (function (BABYLON) {
  17960. var maxSimultaneousLights = 4;
  17961. var FresnelParameters = (function () {
  17962. function FresnelParameters() {
  17963. this.isEnabled = true;
  17964. this.leftColor = BABYLON.Color3.White();
  17965. this.rightColor = BABYLON.Color3.Black();
  17966. this.bias = 0;
  17967. this.power = 1;
  17968. }
  17969. FresnelParameters.prototype.clone = function () {
  17970. var newFresnelParameters = new FresnelParameters();
  17971. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  17972. return new FresnelParameters;
  17973. };
  17974. return FresnelParameters;
  17975. })();
  17976. BABYLON.FresnelParameters = FresnelParameters;
  17977. var StandardMaterialDefines = (function (_super) {
  17978. __extends(StandardMaterialDefines, _super);
  17979. function StandardMaterialDefines() {
  17980. _super.call(this);
  17981. this.DIFFUSE = false;
  17982. this.AMBIENT = false;
  17983. this.OPACITY = false;
  17984. this.OPACITYRGB = false;
  17985. this.REFLECTION = false;
  17986. this.EMISSIVE = false;
  17987. this.SPECULAR = false;
  17988. this.BUMP = false;
  17989. this.SPECULAROVERALPHA = false;
  17990. this.CLIPPLANE = false;
  17991. this.ALPHATEST = false;
  17992. this.ALPHAFROMDIFFUSE = false;
  17993. this.POINTSIZE = false;
  17994. this.FOG = false;
  17995. this.LIGHT0 = false;
  17996. this.LIGHT1 = false;
  17997. this.LIGHT2 = false;
  17998. this.LIGHT3 = false;
  17999. this.SPOTLIGHT0 = false;
  18000. this.SPOTLIGHT1 = false;
  18001. this.SPOTLIGHT2 = false;
  18002. this.SPOTLIGHT3 = false;
  18003. this.HEMILIGHT0 = false;
  18004. this.HEMILIGHT1 = false;
  18005. this.HEMILIGHT2 = false;
  18006. this.HEMILIGHT3 = false;
  18007. this.POINTLIGHT0 = false;
  18008. this.POINTLIGHT1 = false;
  18009. this.POINTLIGHT2 = false;
  18010. this.POINTLIGHT3 = false;
  18011. this.DIRLIGHT0 = false;
  18012. this.DIRLIGHT1 = false;
  18013. this.DIRLIGHT2 = false;
  18014. this.DIRLIGHT3 = false;
  18015. this.SPECULARTERM = false;
  18016. this.SHADOW0 = false;
  18017. this.SHADOW1 = false;
  18018. this.SHADOW2 = false;
  18019. this.SHADOW3 = false;
  18020. this.SHADOWS = false;
  18021. this.SHADOWVSM0 = false;
  18022. this.SHADOWVSM1 = false;
  18023. this.SHADOWVSM2 = false;
  18024. this.SHADOWVSM3 = false;
  18025. this.SHADOWPCF0 = false;
  18026. this.SHADOWPCF1 = false;
  18027. this.SHADOWPCF2 = false;
  18028. this.SHADOWPCF3 = false;
  18029. this.DIFFUSEFRESNEL = false;
  18030. this.OPACITYFRESNEL = false;
  18031. this.REFLECTIONFRESNEL = false;
  18032. this.EMISSIVEFRESNEL = false;
  18033. this.FRESNEL = false;
  18034. this.NORMAL = false;
  18035. this.UV1 = false;
  18036. this.UV2 = false;
  18037. this.VERTEXCOLOR = false;
  18038. this.VERTEXALPHA = false;
  18039. this.NUM_BONE_INFLUENCERS = 0;
  18040. this.BonesPerMesh = 0;
  18041. this.INSTANCES = false;
  18042. this.GLOSSINESS = false;
  18043. this.ROUGHNESS = false;
  18044. this.EMISSIVEASILLUMINATION = false;
  18045. this.LINKEMISSIVEWITHDIFFUSE = false;
  18046. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18047. this.LIGHTMAP = false;
  18048. this.USELIGHTMAPASSHADOWMAP = false;
  18049. this.REFLECTIONMAP_3D = false;
  18050. this.REFLECTIONMAP_SPHERICAL = false;
  18051. this.REFLECTIONMAP_PLANAR = false;
  18052. this.REFLECTIONMAP_CUBIC = false;
  18053. this.REFLECTIONMAP_PROJECTION = false;
  18054. this.REFLECTIONMAP_SKYBOX = false;
  18055. this.REFLECTIONMAP_EXPLICIT = false;
  18056. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18057. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  18058. this.INVERTCUBICMAP = false;
  18059. this.LOGARITHMICDEPTH = false;
  18060. this._keys = Object.keys(this);
  18061. }
  18062. return StandardMaterialDefines;
  18063. })(BABYLON.MaterialDefines);
  18064. var StandardMaterial = (function (_super) {
  18065. __extends(StandardMaterial, _super);
  18066. function StandardMaterial(name, scene) {
  18067. var _this = this;
  18068. _super.call(this, name, scene);
  18069. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18070. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18071. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18072. this.specularPower = 64;
  18073. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18074. this.useAlphaFromDiffuseTexture = false;
  18075. this.useEmissiveAsIllumination = false;
  18076. this.linkEmissiveWithDiffuse = false;
  18077. this.useReflectionFresnelFromSpecular = false;
  18078. this.useSpecularOverAlpha = true;
  18079. this.disableLighting = false;
  18080. this.roughness = 0;
  18081. this.useLightmapAsShadowmap = false;
  18082. this.useGlossinessFromSpecularMapAlpha = false;
  18083. this._renderTargets = new BABYLON.SmartArray(16);
  18084. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18085. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18086. this._defines = new StandardMaterialDefines();
  18087. this._cachedDefines = new StandardMaterialDefines();
  18088. this._cachedDefines.BonesPerMesh = -1;
  18089. this.getRenderTargetTextures = function () {
  18090. _this._renderTargets.reset();
  18091. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18092. _this._renderTargets.push(_this.reflectionTexture);
  18093. }
  18094. return _this._renderTargets;
  18095. };
  18096. }
  18097. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  18098. get: function () {
  18099. return this._useLogarithmicDepth;
  18100. },
  18101. set: function (value) {
  18102. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  18103. },
  18104. enumerable: true,
  18105. configurable: true
  18106. });
  18107. StandardMaterial.prototype.needAlphaBlending = function () {
  18108. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18109. };
  18110. StandardMaterial.prototype.needAlphaTesting = function () {
  18111. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18112. };
  18113. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18114. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18115. };
  18116. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18117. return this.diffuseTexture;
  18118. };
  18119. // Methods
  18120. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18121. if (!mesh) {
  18122. return true;
  18123. }
  18124. if (this._defines.INSTANCES !== useInstances) {
  18125. return false;
  18126. }
  18127. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18128. return true;
  18129. }
  18130. return false;
  18131. };
  18132. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18133. var lightIndex = 0;
  18134. var needNormals = false;
  18135. for (var index = 0; index < scene.lights.length; index++) {
  18136. var light = scene.lights[index];
  18137. if (!light.isEnabled()) {
  18138. continue;
  18139. }
  18140. // Excluded check
  18141. if (light._excludedMeshesIds.length > 0) {
  18142. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18143. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18144. if (excludedMesh) {
  18145. light.excludedMeshes.push(excludedMesh);
  18146. }
  18147. }
  18148. light._excludedMeshesIds = [];
  18149. }
  18150. // Included check
  18151. if (light._includedOnlyMeshesIds.length > 0) {
  18152. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18153. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18154. if (includedOnlyMesh) {
  18155. light.includedOnlyMeshes.push(includedOnlyMesh);
  18156. }
  18157. }
  18158. light._includedOnlyMeshesIds = [];
  18159. }
  18160. if (!light.canAffectMesh(mesh)) {
  18161. continue;
  18162. }
  18163. needNormals = true;
  18164. defines["LIGHT" + lightIndex] = true;
  18165. var type;
  18166. if (light instanceof BABYLON.SpotLight) {
  18167. type = "SPOTLIGHT" + lightIndex;
  18168. }
  18169. else if (light instanceof BABYLON.HemisphericLight) {
  18170. type = "HEMILIGHT" + lightIndex;
  18171. }
  18172. else if (light instanceof BABYLON.PointLight) {
  18173. type = "POINTLIGHT" + lightIndex;
  18174. }
  18175. else {
  18176. type = "DIRLIGHT" + lightIndex;
  18177. }
  18178. defines[type] = true;
  18179. // Specular
  18180. if (!light.specular.equalsFloats(0, 0, 0)) {
  18181. defines["SPECULARTERM"] = true;
  18182. }
  18183. // Shadows
  18184. if (scene.shadowsEnabled) {
  18185. var shadowGenerator = light.getShadowGenerator();
  18186. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18187. defines["SHADOW" + lightIndex] = true;
  18188. defines["SHADOWS"] = true;
  18189. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18190. defines["SHADOWVSM" + lightIndex] = true;
  18191. }
  18192. if (shadowGenerator.usePoissonSampling) {
  18193. defines["SHADOWPCF" + lightIndex] = true;
  18194. }
  18195. }
  18196. }
  18197. lightIndex++;
  18198. if (lightIndex === maxSimultaneousLights)
  18199. break;
  18200. }
  18201. return needNormals;
  18202. };
  18203. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18204. var lightIndex = 0;
  18205. for (var index = 0; index < scene.lights.length; index++) {
  18206. var light = scene.lights[index];
  18207. if (!light.isEnabled()) {
  18208. continue;
  18209. }
  18210. if (!light.canAffectMesh(mesh)) {
  18211. continue;
  18212. }
  18213. if (light instanceof BABYLON.PointLight) {
  18214. // Point Light
  18215. light.transferToEffect(effect, "vLightData" + lightIndex);
  18216. }
  18217. else if (light instanceof BABYLON.DirectionalLight) {
  18218. // Directional Light
  18219. light.transferToEffect(effect, "vLightData" + lightIndex);
  18220. }
  18221. else if (light instanceof BABYLON.SpotLight) {
  18222. // Spot Light
  18223. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18224. }
  18225. else if (light instanceof BABYLON.HemisphericLight) {
  18226. // Hemispheric Light
  18227. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18228. }
  18229. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18230. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18231. if (defines["SPECULARTERM"]) {
  18232. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18233. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18234. }
  18235. // Shadows
  18236. if (scene.shadowsEnabled) {
  18237. var shadowGenerator = light.getShadowGenerator();
  18238. if (mesh.receiveShadows && shadowGenerator) {
  18239. if (!light.needCube()) {
  18240. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18241. }
  18242. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18243. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18244. }
  18245. }
  18246. lightIndex++;
  18247. if (lightIndex === maxSimultaneousLights)
  18248. break;
  18249. }
  18250. };
  18251. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18252. if (this.checkReadyOnlyOnce) {
  18253. if (this._wasPreviouslyReady) {
  18254. return true;
  18255. }
  18256. }
  18257. var scene = this.getScene();
  18258. if (!this.checkReadyOnEveryCall) {
  18259. if (this._renderId === scene.getRenderId()) {
  18260. if (this._checkCache(scene, mesh, useInstances)) {
  18261. return true;
  18262. }
  18263. }
  18264. }
  18265. var engine = scene.getEngine();
  18266. var needNormals = false;
  18267. var needUVs = false;
  18268. this._defines.reset();
  18269. // Textures
  18270. if (scene.texturesEnabled) {
  18271. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18272. if (!this.diffuseTexture.isReady()) {
  18273. return false;
  18274. }
  18275. else {
  18276. needUVs = true;
  18277. this._defines.DIFFUSE = true;
  18278. }
  18279. }
  18280. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18281. if (!this.ambientTexture.isReady()) {
  18282. return false;
  18283. }
  18284. else {
  18285. needUVs = true;
  18286. this._defines.AMBIENT = true;
  18287. }
  18288. }
  18289. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18290. if (!this.opacityTexture.isReady()) {
  18291. return false;
  18292. }
  18293. else {
  18294. needUVs = true;
  18295. this._defines.OPACITY = true;
  18296. if (this.opacityTexture.getAlphaFromRGB) {
  18297. this._defines.OPACITYRGB = true;
  18298. }
  18299. }
  18300. }
  18301. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18302. if (!this.reflectionTexture.isReady()) {
  18303. return false;
  18304. }
  18305. else {
  18306. needNormals = true;
  18307. this._defines.REFLECTION = true;
  18308. if (this.roughness > 0) {
  18309. this._defines.ROUGHNESS = true;
  18310. }
  18311. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18312. this._defines.INVERTCUBICMAP = true;
  18313. }
  18314. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18315. switch (this.reflectionTexture.coordinatesMode) {
  18316. case BABYLON.Texture.CUBIC_MODE:
  18317. case BABYLON.Texture.INVCUBIC_MODE:
  18318. this._defines.REFLECTIONMAP_CUBIC = true;
  18319. break;
  18320. case BABYLON.Texture.EXPLICIT_MODE:
  18321. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18322. break;
  18323. case BABYLON.Texture.PLANAR_MODE:
  18324. this._defines.REFLECTIONMAP_PLANAR = true;
  18325. break;
  18326. case BABYLON.Texture.PROJECTION_MODE:
  18327. this._defines.REFLECTIONMAP_PROJECTION = true;
  18328. break;
  18329. case BABYLON.Texture.SKYBOX_MODE:
  18330. this._defines.REFLECTIONMAP_SKYBOX = true;
  18331. break;
  18332. case BABYLON.Texture.SPHERICAL_MODE:
  18333. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18334. break;
  18335. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18336. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18337. break;
  18338. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  18339. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  18340. break;
  18341. }
  18342. }
  18343. }
  18344. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18345. if (!this.emissiveTexture.isReady()) {
  18346. return false;
  18347. }
  18348. else {
  18349. needUVs = true;
  18350. this._defines.EMISSIVE = true;
  18351. }
  18352. }
  18353. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18354. if (!this.lightmapTexture.isReady()) {
  18355. return false;
  18356. }
  18357. else {
  18358. needUVs = true;
  18359. this._defines.LIGHTMAP = true;
  18360. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18361. }
  18362. }
  18363. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18364. if (!this.specularTexture.isReady()) {
  18365. return false;
  18366. }
  18367. else {
  18368. needUVs = true;
  18369. this._defines.SPECULAR = true;
  18370. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18371. }
  18372. }
  18373. }
  18374. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18375. if (!this.bumpTexture.isReady()) {
  18376. return false;
  18377. }
  18378. else {
  18379. needUVs = true;
  18380. this._defines.BUMP = true;
  18381. }
  18382. }
  18383. // Effect
  18384. if (scene.clipPlane) {
  18385. this._defines.CLIPPLANE = true;
  18386. }
  18387. if (engine.getAlphaTesting()) {
  18388. this._defines.ALPHATEST = true;
  18389. }
  18390. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18391. this._defines.ALPHAFROMDIFFUSE = true;
  18392. }
  18393. if (this.useEmissiveAsIllumination) {
  18394. this._defines.EMISSIVEASILLUMINATION = true;
  18395. }
  18396. if (this.linkEmissiveWithDiffuse) {
  18397. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18398. }
  18399. if (this.useReflectionFresnelFromSpecular) {
  18400. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18401. }
  18402. if (this.useLogarithmicDepth) {
  18403. this._defines.LOGARITHMICDEPTH = true;
  18404. }
  18405. // Point size
  18406. if (this.pointsCloud || scene.forcePointsCloud) {
  18407. this._defines.POINTSIZE = true;
  18408. }
  18409. // Fog
  18410. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18411. this._defines.FOG = true;
  18412. }
  18413. if (scene.lightsEnabled && !this.disableLighting) {
  18414. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18415. }
  18416. if (StandardMaterial.FresnelEnabled) {
  18417. // Fresnel
  18418. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18419. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18420. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18421. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18422. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18423. this._defines.DIFFUSEFRESNEL = true;
  18424. }
  18425. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18426. this._defines.OPACITYFRESNEL = true;
  18427. }
  18428. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18429. this._defines.REFLECTIONFRESNEL = true;
  18430. }
  18431. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18432. this._defines.EMISSIVEFRESNEL = true;
  18433. }
  18434. needNormals = true;
  18435. this._defines.FRESNEL = true;
  18436. }
  18437. }
  18438. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18439. this._defines.SPECULAROVERALPHA = true;
  18440. }
  18441. // Attribs
  18442. if (mesh) {
  18443. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18444. this._defines.NORMAL = true;
  18445. }
  18446. if (needUVs) {
  18447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18448. this._defines.UV1 = true;
  18449. }
  18450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18451. this._defines.UV2 = true;
  18452. }
  18453. }
  18454. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18455. this._defines.VERTEXCOLOR = true;
  18456. if (mesh.hasVertexAlpha) {
  18457. this._defines.VERTEXALPHA = true;
  18458. }
  18459. }
  18460. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18461. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  18462. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18463. }
  18464. // Instances
  18465. if (useInstances) {
  18466. this._defines.INSTANCES = true;
  18467. }
  18468. }
  18469. // Get correct effect
  18470. if (!this._defines.isEqual(this._cachedDefines)) {
  18471. this._defines.cloneTo(this._cachedDefines);
  18472. scene.resetCachedMaterial();
  18473. // Fallbacks
  18474. var fallbacks = new BABYLON.EffectFallbacks();
  18475. if (this._defines.REFLECTION) {
  18476. fallbacks.addFallback(0, "REFLECTION");
  18477. }
  18478. if (this._defines.SPECULAR) {
  18479. fallbacks.addFallback(0, "SPECULAR");
  18480. }
  18481. if (this._defines.BUMP) {
  18482. fallbacks.addFallback(0, "BUMP");
  18483. }
  18484. if (this._defines.SPECULAROVERALPHA) {
  18485. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18486. }
  18487. if (this._defines.FOG) {
  18488. fallbacks.addFallback(1, "FOG");
  18489. }
  18490. if (this._defines.POINTSIZE) {
  18491. fallbacks.addFallback(0, "POINTSIZE");
  18492. }
  18493. if (this._defines.LOGARITHMICDEPTH) {
  18494. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  18495. }
  18496. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18497. if (!this._defines["LIGHT" + lightIndex]) {
  18498. continue;
  18499. }
  18500. if (lightIndex > 0) {
  18501. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18502. }
  18503. if (this._defines["SHADOW" + lightIndex]) {
  18504. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18505. }
  18506. if (this._defines["SHADOWPCF" + lightIndex]) {
  18507. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18508. }
  18509. if (this._defines["SHADOWVSM" + lightIndex]) {
  18510. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18511. }
  18512. }
  18513. if (this._defines.SPECULARTERM) {
  18514. fallbacks.addFallback(0, "SPECULARTERM");
  18515. }
  18516. if (this._defines.DIFFUSEFRESNEL) {
  18517. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18518. }
  18519. if (this._defines.OPACITYFRESNEL) {
  18520. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18521. }
  18522. if (this._defines.REFLECTIONFRESNEL) {
  18523. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18524. }
  18525. if (this._defines.EMISSIVEFRESNEL) {
  18526. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18527. }
  18528. if (this._defines.FRESNEL) {
  18529. fallbacks.addFallback(4, "FRESNEL");
  18530. }
  18531. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18532. fallbacks.addCPUSkinningFallback(0, mesh);
  18533. }
  18534. //Attributes
  18535. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18536. if (this._defines.NORMAL) {
  18537. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18538. }
  18539. if (this._defines.UV1) {
  18540. attribs.push(BABYLON.VertexBuffer.UVKind);
  18541. }
  18542. if (this._defines.UV2) {
  18543. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18544. }
  18545. if (this._defines.VERTEXCOLOR) {
  18546. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18547. }
  18548. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18549. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18550. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18551. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  18552. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  18553. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  18554. }
  18555. }
  18556. if (this._defines.INSTANCES) {
  18557. attribs.push("world0");
  18558. attribs.push("world1");
  18559. attribs.push("world2");
  18560. attribs.push("world3");
  18561. }
  18562. // Legacy browser patch
  18563. var shaderName = "default";
  18564. if (!scene.getEngine().getCaps().standardDerivatives) {
  18565. shaderName = "legacydefault";
  18566. }
  18567. var join = this._defines.toString();
  18568. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18569. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18570. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18571. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18572. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18573. "vFogInfos", "vFogColor", "pointSize",
  18574. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18575. "mBones",
  18576. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18577. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18578. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  18579. "logarithmicDepthConstant"
  18580. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18581. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18582. ], join, fallbacks, this.onCompiled, this.onError);
  18583. }
  18584. if (!this._effect.isReady()) {
  18585. return false;
  18586. }
  18587. this._renderId = scene.getRenderId();
  18588. this._wasPreviouslyReady = true;
  18589. if (mesh) {
  18590. if (!mesh._materialDefines) {
  18591. mesh._materialDefines = new StandardMaterialDefines();
  18592. }
  18593. this._defines.cloneTo(mesh._materialDefines);
  18594. }
  18595. return true;
  18596. };
  18597. StandardMaterial.prototype.unbind = function () {
  18598. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18599. this._effect.setTexture("reflection2DSampler", null);
  18600. }
  18601. _super.prototype.unbind.call(this);
  18602. };
  18603. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18604. this._effect.setMatrix("world", world);
  18605. };
  18606. StandardMaterial.prototype.bind = function (world, mesh) {
  18607. var scene = this.getScene();
  18608. // Matrices
  18609. this.bindOnlyWorldMatrix(world);
  18610. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18611. // Bones
  18612. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18613. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18614. }
  18615. if (scene.getCachedMaterial() !== this) {
  18616. if (StandardMaterial.FresnelEnabled) {
  18617. // Fresnel
  18618. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18619. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18620. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18621. }
  18622. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18623. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18624. }
  18625. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18626. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18627. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18628. }
  18629. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18630. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18631. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18632. }
  18633. }
  18634. // Textures
  18635. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18636. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18637. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18638. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18639. }
  18640. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18641. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18642. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18643. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18644. }
  18645. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18646. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18647. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18648. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18649. }
  18650. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18651. if (this.reflectionTexture.isCube) {
  18652. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18653. }
  18654. else {
  18655. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18656. }
  18657. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18658. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18659. }
  18660. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18661. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18662. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18663. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18664. }
  18665. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18666. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18667. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  18668. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18669. }
  18670. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18671. this._effect.setTexture("specularSampler", this.specularTexture);
  18672. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18673. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18674. }
  18675. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18676. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18677. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18678. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18679. }
  18680. // Clip plane
  18681. if (scene.clipPlane) {
  18682. var clipPlane = scene.clipPlane;
  18683. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18684. }
  18685. // Point size
  18686. if (this.pointsCloud) {
  18687. this._effect.setFloat("pointSize", this.pointSize);
  18688. }
  18689. // Colors
  18690. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18691. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18692. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18693. if (this._defines.SPECULARTERM) {
  18694. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  18695. }
  18696. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18697. }
  18698. // Diffuse
  18699. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  18700. // Lights
  18701. if (scene.lightsEnabled && !this.disableLighting) {
  18702. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  18703. }
  18704. // View
  18705. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18706. this._effect.setMatrix("view", scene.getViewMatrix());
  18707. }
  18708. // Fog
  18709. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18710. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18711. this._effect.setColor3("vFogColor", scene.fogColor);
  18712. }
  18713. // Log. depth
  18714. if (this._defines.LOGARITHMICDEPTH) {
  18715. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  18716. }
  18717. _super.prototype.bind.call(this, world, mesh);
  18718. };
  18719. StandardMaterial.prototype.getAnimatables = function () {
  18720. var results = [];
  18721. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18722. results.push(this.diffuseTexture);
  18723. }
  18724. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18725. results.push(this.ambientTexture);
  18726. }
  18727. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18728. results.push(this.opacityTexture);
  18729. }
  18730. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18731. results.push(this.reflectionTexture);
  18732. }
  18733. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18734. results.push(this.emissiveTexture);
  18735. }
  18736. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18737. results.push(this.specularTexture);
  18738. }
  18739. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18740. results.push(this.bumpTexture);
  18741. }
  18742. return results;
  18743. };
  18744. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18745. if (this.diffuseTexture) {
  18746. this.diffuseTexture.dispose();
  18747. }
  18748. if (this.ambientTexture) {
  18749. this.ambientTexture.dispose();
  18750. }
  18751. if (this.opacityTexture) {
  18752. this.opacityTexture.dispose();
  18753. }
  18754. if (this.reflectionTexture) {
  18755. this.reflectionTexture.dispose();
  18756. }
  18757. if (this.emissiveTexture) {
  18758. this.emissiveTexture.dispose();
  18759. }
  18760. if (this.specularTexture) {
  18761. this.specularTexture.dispose();
  18762. }
  18763. if (this.bumpTexture) {
  18764. this.bumpTexture.dispose();
  18765. }
  18766. _super.prototype.dispose.call(this, forceDisposeEffect);
  18767. };
  18768. StandardMaterial.prototype.clone = function (name) {
  18769. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18770. // Base material
  18771. this.copyTo(newStandardMaterial);
  18772. // Standard material
  18773. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18774. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18775. }
  18776. if (this.ambientTexture && this.ambientTexture.clone) {
  18777. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18778. }
  18779. if (this.opacityTexture && this.opacityTexture.clone) {
  18780. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18781. }
  18782. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18783. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18784. }
  18785. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18786. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18787. }
  18788. if (this.specularTexture && this.specularTexture.clone) {
  18789. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18790. }
  18791. if (this.bumpTexture && this.bumpTexture.clone) {
  18792. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18793. }
  18794. if (this.lightmapTexture && this.lightmapTexture.clone) {
  18795. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  18796. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  18797. }
  18798. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18799. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18800. newStandardMaterial.specularColor = this.specularColor.clone();
  18801. newStandardMaterial.specularPower = this.specularPower;
  18802. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18803. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  18804. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  18805. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  18806. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  18807. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  18808. newStandardMaterial.roughness = this.roughness;
  18809. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  18810. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  18811. }
  18812. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  18813. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  18814. }
  18815. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  18816. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  18817. }
  18818. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  18819. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  18820. }
  18821. return newStandardMaterial;
  18822. };
  18823. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  18824. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  18825. // Statics
  18826. // Flags used to enable or disable a type of texture for all Standard Materials
  18827. StandardMaterial.DiffuseTextureEnabled = true;
  18828. StandardMaterial.AmbientTextureEnabled = true;
  18829. StandardMaterial.OpacityTextureEnabled = true;
  18830. StandardMaterial.ReflectionTextureEnabled = true;
  18831. StandardMaterial.EmissiveTextureEnabled = true;
  18832. StandardMaterial.SpecularTextureEnabled = true;
  18833. StandardMaterial.BumpTextureEnabled = true;
  18834. StandardMaterial.FresnelEnabled = true;
  18835. StandardMaterial.LightmapEnabled = true;
  18836. return StandardMaterial;
  18837. })(BABYLON.Material);
  18838. BABYLON.StandardMaterial = StandardMaterial;
  18839. })(BABYLON || (BABYLON = {}));
  18840. var BABYLON;
  18841. (function (BABYLON) {
  18842. var MultiMaterial = (function (_super) {
  18843. __extends(MultiMaterial, _super);
  18844. function MultiMaterial(name, scene) {
  18845. _super.call(this, name, scene, true);
  18846. this.subMaterials = new Array();
  18847. scene.multiMaterials.push(this);
  18848. }
  18849. // Properties
  18850. MultiMaterial.prototype.getSubMaterial = function (index) {
  18851. if (index < 0 || index >= this.subMaterials.length) {
  18852. return this.getScene().defaultMaterial;
  18853. }
  18854. return this.subMaterials[index];
  18855. };
  18856. // Methods
  18857. MultiMaterial.prototype.isReady = function (mesh) {
  18858. for (var index = 0; index < this.subMaterials.length; index++) {
  18859. var subMaterial = this.subMaterials[index];
  18860. if (subMaterial) {
  18861. if (!this.subMaterials[index].isReady(mesh)) {
  18862. return false;
  18863. }
  18864. }
  18865. }
  18866. return true;
  18867. };
  18868. MultiMaterial.prototype.clone = function (name) {
  18869. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18870. for (var index = 0; index < this.subMaterials.length; index++) {
  18871. var subMaterial = this.subMaterials[index];
  18872. newMultiMaterial.subMaterials.push(subMaterial);
  18873. }
  18874. return newMultiMaterial;
  18875. };
  18876. return MultiMaterial;
  18877. })(BABYLON.Material);
  18878. BABYLON.MultiMaterial = MultiMaterial;
  18879. })(BABYLON || (BABYLON = {}));
  18880. var BABYLON;
  18881. (function (BABYLON) {
  18882. var SceneLoader = (function () {
  18883. function SceneLoader() {
  18884. }
  18885. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18886. get: function () {
  18887. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18888. },
  18889. set: function (value) {
  18890. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18896. get: function () {
  18897. return SceneLoader._ShowLoadingScreen;
  18898. },
  18899. set: function (value) {
  18900. SceneLoader._ShowLoadingScreen = value;
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18906. var dotPosition = sceneFilename.lastIndexOf(".");
  18907. var queryStringPosition = sceneFilename.indexOf("?");
  18908. if (queryStringPosition === -1) {
  18909. queryStringPosition = sceneFilename.length;
  18910. }
  18911. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18912. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18913. var plugin = this._registeredPlugins[index];
  18914. if (plugin.extensions.indexOf(extension) !== -1) {
  18915. return plugin;
  18916. }
  18917. }
  18918. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18919. };
  18920. // Public functions
  18921. SceneLoader.RegisterPlugin = function (plugin) {
  18922. plugin.extensions = plugin.extensions.toLowerCase();
  18923. SceneLoader._registeredPlugins.push(plugin);
  18924. };
  18925. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18926. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18927. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18928. return;
  18929. }
  18930. var loadingToken = {};
  18931. scene._addPendingData(loadingToken);
  18932. var manifestChecked = function (success) {
  18933. scene.database = database;
  18934. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18935. var importMeshFromData = function (data) {
  18936. var meshes = [];
  18937. var particleSystems = [];
  18938. var skeletons = [];
  18939. try {
  18940. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18941. if (onerror) {
  18942. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  18943. }
  18944. scene._removePendingData(loadingToken);
  18945. return;
  18946. }
  18947. }
  18948. catch (e) {
  18949. if (onerror) {
  18950. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  18951. }
  18952. scene._removePendingData(loadingToken);
  18953. return;
  18954. }
  18955. if (onsuccess) {
  18956. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18957. onsuccess(meshes, particleSystems, skeletons);
  18958. scene._removePendingData(loadingToken);
  18959. }
  18960. };
  18961. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18962. // Direct load
  18963. importMeshFromData(sceneFilename.substr(5));
  18964. return;
  18965. }
  18966. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18967. importMeshFromData(data);
  18968. }, progressCallBack, database);
  18969. };
  18970. if (scene.getEngine().enableOfflineSupport) {
  18971. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18972. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18973. }
  18974. else {
  18975. manifestChecked(true);
  18976. }
  18977. };
  18978. /**
  18979. * Load a scene
  18980. * @param rootUrl a string that defines the root url for scene and resources
  18981. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18982. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18983. */
  18984. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18985. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18986. };
  18987. /**
  18988. * Append a scene
  18989. * @param rootUrl a string that defines the root url for scene and resources
  18990. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18991. * @param scene is the instance of BABYLON.Scene to append to
  18992. */
  18993. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18994. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18995. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18996. return;
  18997. }
  18998. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18999. var database;
  19000. var loadingToken = {};
  19001. scene._addPendingData(loadingToken);
  19002. if (SceneLoader.ShowLoadingScreen) {
  19003. scene.getEngine().displayLoadingUI();
  19004. }
  19005. var loadSceneFromData = function (data) {
  19006. scene.database = database;
  19007. if (!plugin.load(scene, data, rootUrl)) {
  19008. if (onerror) {
  19009. onerror(scene);
  19010. }
  19011. scene._removePendingData(loadingToken);
  19012. scene.getEngine().hideLoadingUI();
  19013. return;
  19014. }
  19015. if (onsuccess) {
  19016. onsuccess(scene);
  19017. }
  19018. scene._removePendingData(loadingToken);
  19019. if (SceneLoader.ShowLoadingScreen) {
  19020. scene.executeWhenReady(function () {
  19021. scene.getEngine().hideLoadingUI();
  19022. });
  19023. }
  19024. };
  19025. var manifestChecked = function (success) {
  19026. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19027. };
  19028. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19029. // Direct load
  19030. loadSceneFromData(sceneFilename.substr(5));
  19031. return;
  19032. }
  19033. if (rootUrl.indexOf("file:") === -1) {
  19034. if (scene.getEngine().enableOfflineSupport) {
  19035. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19036. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19037. }
  19038. else {
  19039. manifestChecked(true);
  19040. }
  19041. }
  19042. else {
  19043. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19044. }
  19045. };
  19046. // Flags
  19047. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19048. SceneLoader._ShowLoadingScreen = true;
  19049. // Members
  19050. SceneLoader._registeredPlugins = new Array();
  19051. return SceneLoader;
  19052. })();
  19053. BABYLON.SceneLoader = SceneLoader;
  19054. ;
  19055. })(BABYLON || (BABYLON = {}));
  19056. var BABYLON;
  19057. (function (BABYLON) {
  19058. var Internals;
  19059. (function (Internals) {
  19060. var checkColors4 = function (colors, count) {
  19061. // Check if color3 was used
  19062. if (colors.length === count * 3) {
  19063. var colors4 = [];
  19064. for (var index = 0; index < colors.length; index += 3) {
  19065. var newIndex = (index / 3) * 4;
  19066. colors4[newIndex] = colors[index];
  19067. colors4[newIndex + 1] = colors[index + 1];
  19068. colors4[newIndex + 2] = colors[index + 2];
  19069. colors4[newIndex + 3] = 1.0;
  19070. }
  19071. return colors4;
  19072. }
  19073. return colors;
  19074. };
  19075. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19076. var texture = null;
  19077. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19078. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19079. texture.name = parsedTexture.name;
  19080. texture.hasAlpha = parsedTexture.hasAlpha;
  19081. texture.level = parsedTexture.level;
  19082. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19083. }
  19084. return texture;
  19085. };
  19086. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19087. if (parsedTexture.isCube) {
  19088. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19089. }
  19090. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19091. return null;
  19092. }
  19093. var texture;
  19094. if (parsedTexture.mirrorPlane) {
  19095. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19096. texture._waitingRenderList = parsedTexture.renderList;
  19097. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19098. }
  19099. else if (parsedTexture.isRenderTarget) {
  19100. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19101. texture._waitingRenderList = parsedTexture.renderList;
  19102. }
  19103. else {
  19104. if (parsedTexture.base64String) {
  19105. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19106. }
  19107. else {
  19108. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19109. }
  19110. }
  19111. texture.name = parsedTexture.name;
  19112. texture.hasAlpha = parsedTexture.hasAlpha;
  19113. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19114. texture.level = parsedTexture.level;
  19115. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19116. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19117. texture.uOffset = parsedTexture.uOffset;
  19118. texture.vOffset = parsedTexture.vOffset;
  19119. texture.uScale = parsedTexture.uScale;
  19120. texture.vScale = parsedTexture.vScale;
  19121. texture.uAng = parsedTexture.uAng;
  19122. texture.vAng = parsedTexture.vAng;
  19123. texture.wAng = parsedTexture.wAng;
  19124. texture.wrapU = parsedTexture.wrapU;
  19125. texture.wrapV = parsedTexture.wrapV;
  19126. // Animations
  19127. if (parsedTexture.animations) {
  19128. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19129. var parsedAnimation = parsedTexture.animations[animationIndex];
  19130. texture.animations.push(parseAnimation(parsedAnimation));
  19131. }
  19132. }
  19133. return texture;
  19134. };
  19135. var parseSkeleton = function (parsedSkeleton, scene) {
  19136. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19137. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19138. var parsedBone = parsedSkeleton.bones[index];
  19139. var parentBone = null;
  19140. if (parsedBone.parentBoneIndex > -1) {
  19141. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19142. }
  19143. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19144. if (parsedBone.animation) {
  19145. bone.animations.push(parseAnimation(parsedBone.animation));
  19146. }
  19147. }
  19148. return skeleton;
  19149. };
  19150. var parseFresnelParameters = function (parsedFresnelParameters) {
  19151. var fresnelParameters = new BABYLON.FresnelParameters();
  19152. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19153. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19154. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19155. fresnelParameters.bias = parsedFresnelParameters.bias;
  19156. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19157. return fresnelParameters;
  19158. };
  19159. var parseCustomMaterial = function (parsedMaterial, scene, rootUrl) {
  19160. return null;
  19161. };
  19162. var parseStandardMaterial = function (parsedMaterial, scene, rootUrl) {
  19163. var material;
  19164. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19165. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19166. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19167. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19168. material.specularPower = parsedMaterial.specularPower;
  19169. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19170. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19171. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19172. material.alpha = parsedMaterial.alpha;
  19173. material.id = parsedMaterial.id;
  19174. if (parsedMaterial.disableDepthWrite) {
  19175. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19176. }
  19177. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19178. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19179. material.wireframe = parsedMaterial.wireframe;
  19180. if (parsedMaterial.diffuseTexture) {
  19181. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19182. }
  19183. if (parsedMaterial.diffuseFresnelParameters) {
  19184. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19185. }
  19186. if (parsedMaterial.ambientTexture) {
  19187. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19188. }
  19189. if (parsedMaterial.opacityTexture) {
  19190. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19191. }
  19192. if (parsedMaterial.opacityFresnelParameters) {
  19193. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19194. }
  19195. if (parsedMaterial.reflectionTexture) {
  19196. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19197. }
  19198. if (parsedMaterial.reflectionFresnelParameters) {
  19199. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19200. }
  19201. if (parsedMaterial.emissiveTexture) {
  19202. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19203. }
  19204. if (parsedMaterial.lightmapTexture) {
  19205. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19206. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19207. }
  19208. if (parsedMaterial.emissiveFresnelParameters) {
  19209. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19210. }
  19211. if (parsedMaterial.specularTexture) {
  19212. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19213. }
  19214. if (parsedMaterial.bumpTexture) {
  19215. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19216. }
  19217. if (parsedMaterial.checkReadyOnlyOnce) {
  19218. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19219. }
  19220. return material;
  19221. };
  19222. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19223. if (!parsedMaterial.customType) {
  19224. return parseStandardMaterial(parsedMaterial, scene, rootUrl);
  19225. }
  19226. return parseCustomMaterial(parsedMaterial, scene, rootUrl);
  19227. };
  19228. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19229. for (var index = 0; index < parsedData.materials.length; index++) {
  19230. var parsedMaterial = parsedData.materials[index];
  19231. if (parsedMaterial.id === id) {
  19232. return parseMaterial(parsedMaterial, scene, rootUrl);
  19233. }
  19234. }
  19235. return null;
  19236. };
  19237. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19238. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19239. multiMaterial.id = parsedMultiMaterial.id;
  19240. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19241. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19242. var subMatId = parsedMultiMaterial.materials[matIndex];
  19243. if (subMatId) {
  19244. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19245. }
  19246. else {
  19247. multiMaterial.subMaterials.push(null);
  19248. }
  19249. }
  19250. return multiMaterial;
  19251. };
  19252. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19253. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19254. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19255. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19256. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19257. var parsedFlare = parsedLensFlareSystem.flares[index];
  19258. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19259. }
  19260. return lensFlareSystem;
  19261. };
  19262. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19263. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19264. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19265. if (parsedParticleSystem.textureName) {
  19266. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19267. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19268. }
  19269. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19270. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19271. particleSystem.minSize = parsedParticleSystem.minSize;
  19272. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19273. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19274. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19275. particleSystem.emitter = emitter;
  19276. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19277. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19278. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19279. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19280. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19281. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19282. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19283. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19284. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19285. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19286. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19287. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19288. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19289. particleSystem.start();
  19290. return particleSystem;
  19291. };
  19292. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19293. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19294. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19295. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19296. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19297. shadowGenerator.getShadowMap().renderList.push(mesh);
  19298. }
  19299. if (parsedShadowGenerator.usePoissonSampling) {
  19300. shadowGenerator.usePoissonSampling = true;
  19301. }
  19302. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19303. shadowGenerator.useVarianceShadowMap = true;
  19304. }
  19305. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19306. shadowGenerator.useBlurVarianceShadowMap = true;
  19307. if (parsedShadowGenerator.blurScale) {
  19308. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19309. }
  19310. if (parsedShadowGenerator.blurBoxOffset) {
  19311. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19312. }
  19313. }
  19314. if (parsedShadowGenerator.bias !== undefined) {
  19315. shadowGenerator.bias = parsedShadowGenerator.bias;
  19316. }
  19317. return shadowGenerator;
  19318. };
  19319. var parseAnimation = function (parsedAnimation) {
  19320. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19321. var dataType = parsedAnimation.dataType;
  19322. var keys = [];
  19323. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19324. var key = parsedAnimation.keys[index];
  19325. var data;
  19326. switch (dataType) {
  19327. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19328. data = key.values[0];
  19329. break;
  19330. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19331. data = BABYLON.Quaternion.FromArray(key.values);
  19332. break;
  19333. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19334. data = BABYLON.Matrix.FromArray(key.values);
  19335. break;
  19336. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19337. default:
  19338. data = BABYLON.Vector3.FromArray(key.values);
  19339. break;
  19340. }
  19341. keys.push({
  19342. frame: key.frame,
  19343. value: data
  19344. });
  19345. }
  19346. animation.setKeys(keys);
  19347. return animation;
  19348. };
  19349. var parseLight = function (parsedLight, scene) {
  19350. var light;
  19351. switch (parsedLight.type) {
  19352. case 0:
  19353. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19354. break;
  19355. case 1:
  19356. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19357. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19358. break;
  19359. case 2:
  19360. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19361. break;
  19362. case 3:
  19363. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19364. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19365. break;
  19366. }
  19367. light.id = parsedLight.id;
  19368. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19369. if (parsedLight.intensity !== undefined) {
  19370. light.intensity = parsedLight.intensity;
  19371. }
  19372. if (parsedLight.range) {
  19373. light.range = parsedLight.range;
  19374. }
  19375. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19376. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19377. if (parsedLight.excludedMeshesIds) {
  19378. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19379. }
  19380. // Parent
  19381. if (parsedLight.parentId) {
  19382. light._waitingParentId = parsedLight.parentId;
  19383. }
  19384. if (parsedLight.includedOnlyMeshesIds) {
  19385. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19386. }
  19387. // Animations
  19388. if (parsedLight.animations) {
  19389. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19390. var parsedAnimation = parsedLight.animations[animationIndex];
  19391. light.animations.push(parseAnimation(parsedAnimation));
  19392. }
  19393. }
  19394. if (parsedLight.autoAnimate) {
  19395. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19396. }
  19397. };
  19398. var parseCamera = function (parsedCamera, scene) {
  19399. var camera;
  19400. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19401. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19402. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19403. var alpha = parsedCamera.alpha;
  19404. var beta = parsedCamera.beta;
  19405. var radius = parsedCamera.radius;
  19406. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19407. var interaxial_distance = parsedCamera.interaxial_distance;
  19408. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19409. }
  19410. else {
  19411. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19412. }
  19413. }
  19414. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19415. interaxial_distance = parsedCamera.interaxial_distance;
  19416. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19417. }
  19418. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19419. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19420. }
  19421. else if (parsedCamera.type === "FollowCamera") {
  19422. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19423. camera.heightOffset = parsedCamera.heightOffset;
  19424. camera.radius = parsedCamera.radius;
  19425. camera.rotationOffset = parsedCamera.rotationOffset;
  19426. if (lockedTargetMesh)
  19427. camera.target = lockedTargetMesh;
  19428. }
  19429. else if (parsedCamera.type === "GamepadCamera") {
  19430. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19431. }
  19432. else if (parsedCamera.type === "TouchCamera") {
  19433. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19434. }
  19435. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19436. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19437. }
  19438. else if (parsedCamera.type === "WebVRFreeCamera") {
  19439. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19440. }
  19441. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19442. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19443. }
  19444. else {
  19445. // Free Camera is the default value
  19446. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19447. }
  19448. // apply 3d rig, when found
  19449. if (parsedCamera.cameraRigMode) {
  19450. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19451. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19452. }
  19453. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19454. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19455. camera.lockedTarget = lockedTargetMesh;
  19456. }
  19457. camera.id = parsedCamera.id;
  19458. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19459. // Parent
  19460. if (parsedCamera.parentId) {
  19461. camera._waitingParentId = parsedCamera.parentId;
  19462. }
  19463. // Target
  19464. if (parsedCamera.target) {
  19465. if (camera.setTarget) {
  19466. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19467. }
  19468. else {
  19469. //For ArcRotate
  19470. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19471. }
  19472. }
  19473. else {
  19474. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19475. }
  19476. camera.fov = parsedCamera.fov;
  19477. camera.minZ = parsedCamera.minZ;
  19478. camera.maxZ = parsedCamera.maxZ;
  19479. camera.speed = parsedCamera.speed;
  19480. camera.inertia = parsedCamera.inertia;
  19481. camera.checkCollisions = parsedCamera.checkCollisions;
  19482. camera.applyGravity = parsedCamera.applyGravity;
  19483. if (parsedCamera.ellipsoid) {
  19484. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19485. }
  19486. // Animations
  19487. if (parsedCamera.animations) {
  19488. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19489. var parsedAnimation = parsedCamera.animations[animationIndex];
  19490. camera.animations.push(parseAnimation(parsedAnimation));
  19491. }
  19492. }
  19493. if (parsedCamera.autoAnimate) {
  19494. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19495. }
  19496. // Layer Mask
  19497. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19498. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19499. }
  19500. else {
  19501. camera.layerMask = 0x0FFFFFFF;
  19502. }
  19503. return camera;
  19504. };
  19505. var parseGeometry = function (parsedGeometry, scene) {
  19506. var id = parsedGeometry.id;
  19507. return scene.getGeometryByID(id);
  19508. };
  19509. var parseBox = function (parsedBox, scene) {
  19510. if (parseGeometry(parsedBox, scene)) {
  19511. return null; // null since geometry could be something else than a box...
  19512. }
  19513. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19514. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19515. scene.pushGeometry(box, true);
  19516. return box;
  19517. };
  19518. var parseSphere = function (parsedSphere, scene) {
  19519. if (parseGeometry(parsedSphere, scene)) {
  19520. return null; // null since geometry could be something else than a sphere...
  19521. }
  19522. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19523. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19524. scene.pushGeometry(sphere, true);
  19525. return sphere;
  19526. };
  19527. var parseCylinder = function (parsedCylinder, scene) {
  19528. if (parseGeometry(parsedCylinder, scene)) {
  19529. return null; // null since geometry could be something else than a cylinder...
  19530. }
  19531. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19532. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19533. scene.pushGeometry(cylinder, true);
  19534. return cylinder;
  19535. };
  19536. var parseTorus = function (parsedTorus, scene) {
  19537. if (parseGeometry(parsedTorus, scene)) {
  19538. return null; // null since geometry could be something else than a torus...
  19539. }
  19540. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19541. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19542. scene.pushGeometry(torus, true);
  19543. return torus;
  19544. };
  19545. var parseGround = function (parsedGround, scene) {
  19546. if (parseGeometry(parsedGround, scene)) {
  19547. return null; // null since geometry could be something else than a ground...
  19548. }
  19549. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19550. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19551. scene.pushGeometry(ground, true);
  19552. return ground;
  19553. };
  19554. var parsePlane = function (parsedPlane, scene) {
  19555. if (parseGeometry(parsedPlane, scene)) {
  19556. return null; // null since geometry could be something else than a plane...
  19557. }
  19558. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19559. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19560. scene.pushGeometry(plane, true);
  19561. return plane;
  19562. };
  19563. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19564. if (parseGeometry(parsedTorusKnot, scene)) {
  19565. return null; // null since geometry could be something else than a torusKnot...
  19566. }
  19567. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  19568. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19569. scene.pushGeometry(torusKnot, true);
  19570. return torusKnot;
  19571. };
  19572. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19573. if (parseGeometry(parsedVertexData, scene)) {
  19574. return null; // null since geometry could be a primitive
  19575. }
  19576. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19577. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19578. if (parsedVertexData.delayLoadingFile) {
  19579. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19580. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19581. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19582. geometry._delayInfo = [];
  19583. if (parsedVertexData.hasUVs) {
  19584. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19585. }
  19586. if (parsedVertexData.hasUVs2) {
  19587. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19588. }
  19589. if (parsedVertexData.hasUVs3) {
  19590. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19591. }
  19592. if (parsedVertexData.hasUVs4) {
  19593. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19594. }
  19595. if (parsedVertexData.hasUVs5) {
  19596. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19597. }
  19598. if (parsedVertexData.hasUVs6) {
  19599. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19600. }
  19601. if (parsedVertexData.hasColors) {
  19602. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19603. }
  19604. if (parsedVertexData.hasMatricesIndices) {
  19605. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19606. }
  19607. if (parsedVertexData.hasMatricesWeights) {
  19608. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19609. }
  19610. geometry._delayLoadingFunction = importVertexData;
  19611. }
  19612. else {
  19613. importVertexData(parsedVertexData, geometry);
  19614. }
  19615. scene.pushGeometry(geometry, true);
  19616. return geometry;
  19617. };
  19618. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19619. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19620. mesh.id = parsedMesh.id;
  19621. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19622. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19623. if (parsedMesh.rotationQuaternion) {
  19624. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19625. }
  19626. else if (parsedMesh.rotation) {
  19627. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19628. }
  19629. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19630. if (parsedMesh.localMatrix) {
  19631. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19632. }
  19633. else if (parsedMesh.pivotMatrix) {
  19634. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19635. }
  19636. mesh.setEnabled(parsedMesh.isEnabled);
  19637. mesh.isVisible = parsedMesh.isVisible;
  19638. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19639. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19640. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19641. if (parsedMesh.applyFog !== undefined) {
  19642. mesh.applyFog = parsedMesh.applyFog;
  19643. }
  19644. if (parsedMesh.pickable !== undefined) {
  19645. mesh.isPickable = parsedMesh.pickable;
  19646. }
  19647. if (parsedMesh.alphaIndex !== undefined) {
  19648. mesh.alphaIndex = parsedMesh.alphaIndex;
  19649. }
  19650. mesh.receiveShadows = parsedMesh.receiveShadows;
  19651. mesh.billboardMode = parsedMesh.billboardMode;
  19652. if (parsedMesh.visibility !== undefined) {
  19653. mesh.visibility = parsedMesh.visibility;
  19654. }
  19655. mesh.checkCollisions = parsedMesh.checkCollisions;
  19656. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19657. // freezeWorldMatrix
  19658. if (parsedMesh.freezeWorldMatrix) {
  19659. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19660. }
  19661. // Parent
  19662. if (parsedMesh.parentId) {
  19663. mesh._waitingParentId = parsedMesh.parentId;
  19664. }
  19665. // Actions
  19666. if (parsedMesh.actions !== undefined) {
  19667. mesh._waitingActions = parsedMesh.actions;
  19668. }
  19669. // Geometry
  19670. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19671. if (parsedMesh.delayLoadingFile) {
  19672. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19673. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19674. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19675. if (parsedMesh._binaryInfo) {
  19676. mesh._binaryInfo = parsedMesh._binaryInfo;
  19677. }
  19678. mesh._delayInfo = [];
  19679. if (parsedMesh.hasUVs) {
  19680. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19681. }
  19682. if (parsedMesh.hasUVs2) {
  19683. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19684. }
  19685. if (parsedMesh.hasUVs3) {
  19686. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19687. }
  19688. if (parsedMesh.hasUVs4) {
  19689. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19690. }
  19691. if (parsedMesh.hasUVs5) {
  19692. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19693. }
  19694. if (parsedMesh.hasUVs6) {
  19695. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19696. }
  19697. if (parsedMesh.hasColors) {
  19698. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19699. }
  19700. if (parsedMesh.hasMatricesIndices) {
  19701. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19702. }
  19703. if (parsedMesh.hasMatricesWeights) {
  19704. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19705. }
  19706. mesh._delayLoadingFunction = importGeometry;
  19707. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19708. mesh._checkDelayState();
  19709. }
  19710. }
  19711. else {
  19712. importGeometry(parsedMesh, mesh);
  19713. }
  19714. // Material
  19715. if (parsedMesh.materialId) {
  19716. mesh.setMaterialByID(parsedMesh.materialId);
  19717. }
  19718. else {
  19719. mesh.material = null;
  19720. }
  19721. // Skeleton
  19722. if (parsedMesh.skeletonId > -1) {
  19723. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19724. if (parsedMesh.numBoneInfluencers) {
  19725. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19726. }
  19727. }
  19728. // Physics
  19729. if (parsedMesh.physicsImpostor) {
  19730. if (!scene.isPhysicsEnabled()) {
  19731. scene.enablePhysics();
  19732. }
  19733. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19734. }
  19735. // Animations
  19736. if (parsedMesh.animations) {
  19737. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19738. var parsedAnimation = parsedMesh.animations[animationIndex];
  19739. mesh.animations.push(parseAnimation(parsedAnimation));
  19740. }
  19741. }
  19742. if (parsedMesh.autoAnimate) {
  19743. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19744. }
  19745. // Layer Mask
  19746. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19747. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19748. }
  19749. else {
  19750. mesh.layerMask = 0x0FFFFFFF;
  19751. }
  19752. // Instances
  19753. if (parsedMesh.instances) {
  19754. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19755. var parsedInstance = parsedMesh.instances[index];
  19756. var instance = mesh.createInstance(parsedInstance.name);
  19757. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19758. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19759. if (parsedInstance.rotationQuaternion) {
  19760. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19761. }
  19762. else if (parsedInstance.rotation) {
  19763. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19764. }
  19765. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19766. instance.checkCollisions = mesh.checkCollisions;
  19767. if (parsedMesh.animations) {
  19768. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19769. parsedAnimation = parsedMesh.animations[animationIndex];
  19770. instance.animations.push(parseAnimation(parsedAnimation));
  19771. }
  19772. }
  19773. }
  19774. }
  19775. return mesh;
  19776. };
  19777. var parseActions = function (parsedActions, object, scene) {
  19778. var actionManager = new BABYLON.ActionManager(scene);
  19779. if (object === null)
  19780. scene.actionManager = actionManager;
  19781. else
  19782. object.actionManager = actionManager;
  19783. // instanciate a new object
  19784. var instanciate = function (name, params) {
  19785. var newInstance = Object.create(BABYLON[name].prototype);
  19786. newInstance.constructor.apply(newInstance, params);
  19787. return newInstance;
  19788. };
  19789. var parseParameter = function (name, value, target, propertyPath) {
  19790. if (propertyPath === null) {
  19791. // String, boolean or float
  19792. var floatValue = parseFloat(value);
  19793. if (value === "true" || value === "false")
  19794. return value === "true";
  19795. else
  19796. return isNaN(floatValue) ? value : floatValue;
  19797. }
  19798. var effectiveTarget = propertyPath.split(".");
  19799. var values = value.split(",");
  19800. // Get effective Target
  19801. for (var i = 0; i < effectiveTarget.length; i++) {
  19802. target = target[effectiveTarget[i]];
  19803. }
  19804. // Return appropriate value with its type
  19805. if (typeof (target) === "boolean")
  19806. return values[0] === "true";
  19807. if (typeof (target) === "string")
  19808. return values[0];
  19809. // Parameters with multiple values such as Vector3 etc.
  19810. var split = new Array();
  19811. for (var i = 0; i < values.length; i++)
  19812. split.push(parseFloat(values[i]));
  19813. if (target instanceof BABYLON.Vector3)
  19814. return BABYLON.Vector3.FromArray(split);
  19815. if (target instanceof BABYLON.Vector4)
  19816. return BABYLON.Vector4.FromArray(split);
  19817. if (target instanceof BABYLON.Color3)
  19818. return BABYLON.Color3.FromArray(split);
  19819. if (target instanceof BABYLON.Color4)
  19820. return BABYLON.Color4.FromArray(split);
  19821. return parseFloat(values[0]);
  19822. };
  19823. // traverse graph per trigger
  19824. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19825. if (combineArray === void 0) { combineArray = null; }
  19826. if (parsedAction.detached)
  19827. return;
  19828. var parameters = new Array();
  19829. var target = null;
  19830. var propertyPath = null;
  19831. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19832. // Parameters
  19833. if (parsedAction.type === 2)
  19834. parameters.push(actionManager);
  19835. else
  19836. parameters.push(trigger);
  19837. if (combine) {
  19838. var actions = new Array();
  19839. for (var j = 0; j < parsedAction.combine.length; j++) {
  19840. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19841. }
  19842. parameters.push(actions);
  19843. }
  19844. else {
  19845. for (var i = 0; i < parsedAction.properties.length; i++) {
  19846. var value = parsedAction.properties[i].value;
  19847. var name = parsedAction.properties[i].name;
  19848. var targetType = parsedAction.properties[i].targetType;
  19849. if (name === "target")
  19850. if (targetType !== null && targetType === "SceneProperties")
  19851. value = target = scene;
  19852. else
  19853. value = target = scene.getNodeByName(value);
  19854. else if (name === "parent")
  19855. value = scene.getNodeByName(value);
  19856. else if (name === "sound")
  19857. value = scene.getSoundByName(value);
  19858. else if (name !== "propertyPath") {
  19859. if (parsedAction.type === 2 && name === "operator")
  19860. value = BABYLON.ValueCondition[value];
  19861. else
  19862. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19863. }
  19864. else {
  19865. propertyPath = value;
  19866. }
  19867. parameters.push(value);
  19868. }
  19869. }
  19870. if (combineArray === null) {
  19871. parameters.push(condition);
  19872. }
  19873. else {
  19874. parameters.push(null);
  19875. }
  19876. // If interpolate value action
  19877. if (parsedAction.name === "InterpolateValueAction") {
  19878. var param = parameters[parameters.length - 2];
  19879. parameters[parameters.length - 1] = param;
  19880. parameters[parameters.length - 2] = condition;
  19881. }
  19882. // Action or condition(s) and not CombineAction
  19883. var newAction = instanciate(parsedAction.name, parameters);
  19884. if (newAction instanceof BABYLON.Condition && condition !== null) {
  19885. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  19886. if (action)
  19887. action.then(nothing);
  19888. else
  19889. actionManager.registerAction(nothing);
  19890. action = nothing;
  19891. }
  19892. if (combineArray === null) {
  19893. if (newAction instanceof BABYLON.Condition) {
  19894. condition = newAction;
  19895. newAction = action;
  19896. }
  19897. else {
  19898. condition = null;
  19899. if (action)
  19900. action.then(newAction);
  19901. else
  19902. actionManager.registerAction(newAction);
  19903. }
  19904. }
  19905. else {
  19906. combineArray.push(newAction);
  19907. }
  19908. for (var i = 0; i < parsedAction.children.length; i++)
  19909. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19910. };
  19911. // triggers
  19912. for (var i = 0; i < parsedActions.children.length; i++) {
  19913. var triggerParams;
  19914. var trigger = parsedActions.children[i];
  19915. if (trigger.properties.length > 0) {
  19916. var param = trigger.properties[0].value;
  19917. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19918. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19919. }
  19920. else
  19921. triggerParams = BABYLON.ActionManager[trigger.name];
  19922. for (var j = 0; j < trigger.children.length; j++) {
  19923. if (!trigger.detached)
  19924. traverse(trigger.children[j], triggerParams, null, null);
  19925. }
  19926. }
  19927. };
  19928. var parseSound = function (parsedSound, scene, rootUrl) {
  19929. var soundName = parsedSound.name;
  19930. var soundUrl = rootUrl + soundName;
  19931. var options = {
  19932. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19933. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19934. rolloffFactor: parsedSound.rolloffFactor,
  19935. refDistance: parsedSound.refDistance,
  19936. distanceModel: parsedSound.distanceModel,
  19937. playbackRate: parsedSound.playbackRate
  19938. };
  19939. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19940. scene._addPendingData(newSound);
  19941. if (parsedSound.position) {
  19942. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19943. newSound.setPosition(soundPosition);
  19944. }
  19945. if (parsedSound.isDirectional) {
  19946. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19947. if (parsedSound.localDirectionToMesh) {
  19948. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19949. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19950. }
  19951. }
  19952. if (parsedSound.connectedMeshId) {
  19953. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19954. if (connectedMesh) {
  19955. newSound.attachToMesh(connectedMesh);
  19956. }
  19957. }
  19958. };
  19959. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19960. names = (names instanceof Array) ? names : [names];
  19961. for (var i in names) {
  19962. if (mesh.name === names[i]) {
  19963. hierarchyIds.push(mesh.id);
  19964. return true;
  19965. }
  19966. }
  19967. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19968. hierarchyIds.push(mesh.id);
  19969. return true;
  19970. }
  19971. return false;
  19972. };
  19973. var importVertexData = function (parsedVertexData, geometry) {
  19974. var vertexData = new BABYLON.VertexData();
  19975. // positions
  19976. var positions = parsedVertexData.positions;
  19977. if (positions) {
  19978. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19979. }
  19980. // normals
  19981. var normals = parsedVertexData.normals;
  19982. if (normals) {
  19983. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19984. }
  19985. // uvs
  19986. var uvs = parsedVertexData.uvs;
  19987. if (uvs) {
  19988. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19989. }
  19990. // uv2s
  19991. var uv2s = parsedVertexData.uv2s;
  19992. if (uv2s) {
  19993. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19994. }
  19995. // uv3s
  19996. var uv3s = parsedVertexData.uv3s;
  19997. if (uv3s) {
  19998. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  19999. }
  20000. // uv4s
  20001. var uv4s = parsedVertexData.uv4s;
  20002. if (uv4s) {
  20003. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20004. }
  20005. // uv5s
  20006. var uv5s = parsedVertexData.uv5s;
  20007. if (uv5s) {
  20008. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20009. }
  20010. // uv6s
  20011. var uv6s = parsedVertexData.uv6s;
  20012. if (uv6s) {
  20013. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20014. }
  20015. // colors
  20016. var colors = parsedVertexData.colors;
  20017. if (colors) {
  20018. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20019. }
  20020. // matricesIndices
  20021. var matricesIndices = parsedVertexData.matricesIndices;
  20022. if (matricesIndices) {
  20023. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20024. }
  20025. // matricesWeights
  20026. var matricesWeights = parsedVertexData.matricesWeights;
  20027. if (matricesWeights) {
  20028. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20029. }
  20030. // indices
  20031. var indices = parsedVertexData.indices;
  20032. if (indices) {
  20033. vertexData.indices = indices;
  20034. }
  20035. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20036. };
  20037. var importGeometry = function (parsedGeometry, mesh) {
  20038. var scene = mesh.getScene();
  20039. // Geometry
  20040. var geometryId = parsedGeometry.geometryId;
  20041. if (geometryId) {
  20042. var geometry = scene.getGeometryByID(geometryId);
  20043. if (geometry) {
  20044. geometry.applyToMesh(mesh);
  20045. }
  20046. }
  20047. else if (parsedGeometry instanceof ArrayBuffer) {
  20048. var binaryInfo = mesh._binaryInfo;
  20049. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20050. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20051. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20052. }
  20053. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20054. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20055. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20056. }
  20057. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20058. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20059. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20060. }
  20061. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20062. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20064. }
  20065. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20066. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20067. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20068. }
  20069. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20070. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20071. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20072. }
  20073. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20074. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20075. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20076. }
  20077. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20078. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20079. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20080. }
  20081. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20082. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20083. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20084. }
  20085. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20086. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20088. }
  20089. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20090. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20092. }
  20093. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20094. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20095. mesh.setIndices(indicesData);
  20096. }
  20097. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20098. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20099. mesh.subMeshes = [];
  20100. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20101. var materialIndex = subMeshesData[(i * 5) + 0];
  20102. var verticesStart = subMeshesData[(i * 5) + 1];
  20103. var verticesCount = subMeshesData[(i * 5) + 2];
  20104. var indexStart = subMeshesData[(i * 5) + 3];
  20105. var indexCount = subMeshesData[(i * 5) + 4];
  20106. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20107. }
  20108. }
  20109. }
  20110. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20111. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20112. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20113. if (parsedGeometry.uvs) {
  20114. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20115. }
  20116. if (parsedGeometry.uvs2) {
  20117. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20118. }
  20119. if (parsedGeometry.uvs3) {
  20120. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20121. }
  20122. if (parsedGeometry.uvs4) {
  20123. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20124. }
  20125. if (parsedGeometry.uvs5) {
  20126. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20127. }
  20128. if (parsedGeometry.uvs6) {
  20129. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20130. }
  20131. if (parsedGeometry.colors) {
  20132. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20133. }
  20134. if (parsedGeometry.matricesIndices) {
  20135. if (!parsedGeometry.matricesIndices._isExpanded) {
  20136. var floatIndices = [];
  20137. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20138. var matricesIndex = parsedGeometry.matricesIndices[i];
  20139. floatIndices.push(matricesIndex & 0x000000FF);
  20140. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20141. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20142. floatIndices.push(matricesIndex >> 24);
  20143. }
  20144. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20145. }
  20146. else {
  20147. delete parsedGeometry.matricesIndices._isExpanded;
  20148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20149. }
  20150. }
  20151. if (parsedGeometry.matricesIndicesExtra) {
  20152. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  20153. var floatIndices = [];
  20154. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  20155. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  20156. floatIndices.push(matricesIndex & 0x000000FF);
  20157. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20158. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20159. floatIndices.push(matricesIndex >> 24);
  20160. }
  20161. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  20162. }
  20163. else {
  20164. delete parsedGeometry.matricesIndices._isExpanded;
  20165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  20166. }
  20167. }
  20168. if (parsedGeometry.matricesWeights) {
  20169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20170. }
  20171. if (parsedGeometry.matricesWeightsExtra) {
  20172. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  20173. }
  20174. mesh.setIndices(parsedGeometry.indices);
  20175. }
  20176. // SubMeshes
  20177. if (parsedGeometry.subMeshes) {
  20178. mesh.subMeshes = [];
  20179. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20180. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20181. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20182. }
  20183. }
  20184. // Flat shading
  20185. if (mesh._shouldGenerateFlatShading) {
  20186. mesh.convertToFlatShadedMesh();
  20187. delete mesh._shouldGenerateFlatShading;
  20188. }
  20189. // Update
  20190. mesh.computeWorldMatrix(true);
  20191. // Octree
  20192. if (scene._selectionOctree) {
  20193. scene._selectionOctree.addMesh(mesh);
  20194. }
  20195. };
  20196. BABYLON.SceneLoader.RegisterPlugin({
  20197. extensions: ".babylon",
  20198. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20199. var parsedData = JSON.parse(data);
  20200. var loadedSkeletonsIds = [];
  20201. var loadedMaterialsIds = [];
  20202. var hierarchyIds = [];
  20203. var index;
  20204. for (index = 0; index < parsedData.meshes.length; index++) {
  20205. var parsedMesh = parsedData.meshes[index];
  20206. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20207. if (meshesNames instanceof Array) {
  20208. // Remove found mesh name from list.
  20209. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20210. }
  20211. //Geometry?
  20212. if (parsedMesh.geometryId) {
  20213. //does the file contain geometries?
  20214. if (parsedData.geometries) {
  20215. //find the correct geometry and add it to the scene
  20216. var found = false;
  20217. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20218. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20219. return;
  20220. }
  20221. else {
  20222. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20223. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20224. switch (geometryType) {
  20225. case "boxes":
  20226. parseBox(parsedGeometryData, scene);
  20227. break;
  20228. case "spheres":
  20229. parseSphere(parsedGeometryData, scene);
  20230. break;
  20231. case "cylinders":
  20232. parseCylinder(parsedGeometryData, scene);
  20233. break;
  20234. case "toruses":
  20235. parseTorus(parsedGeometryData, scene);
  20236. break;
  20237. case "grounds":
  20238. parseGround(parsedGeometryData, scene);
  20239. break;
  20240. case "planes":
  20241. parsePlane(parsedGeometryData, scene);
  20242. break;
  20243. case "torusKnots":
  20244. parseTorusKnot(parsedGeometryData, scene);
  20245. break;
  20246. case "vertexData":
  20247. parseVertexData(parsedGeometryData, scene, rootUrl);
  20248. break;
  20249. }
  20250. found = true;
  20251. }
  20252. });
  20253. }
  20254. });
  20255. if (!found) {
  20256. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20257. }
  20258. }
  20259. }
  20260. // Material ?
  20261. if (parsedMesh.materialId) {
  20262. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20263. if (!materialFound && parsedData.multiMaterials) {
  20264. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20265. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20266. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20267. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20268. var subMatId = parsedMultiMaterial.materials[matIndex];
  20269. loadedMaterialsIds.push(subMatId);
  20270. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20271. }
  20272. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20273. parseMultiMaterial(parsedMultiMaterial, scene);
  20274. materialFound = true;
  20275. break;
  20276. }
  20277. }
  20278. }
  20279. if (!materialFound) {
  20280. loadedMaterialsIds.push(parsedMesh.materialId);
  20281. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20282. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20283. }
  20284. }
  20285. }
  20286. // Skeleton ?
  20287. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20288. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20289. if (!skeletonAlreadyLoaded) {
  20290. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20291. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20292. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20293. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20294. loadedSkeletonsIds.push(parsedSkeleton.id);
  20295. }
  20296. }
  20297. }
  20298. }
  20299. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20300. meshes.push(mesh);
  20301. }
  20302. }
  20303. // Connecting parents
  20304. var currentMesh;
  20305. for (index = 0; index < scene.meshes.length; index++) {
  20306. currentMesh = scene.meshes[index];
  20307. if (currentMesh._waitingParentId) {
  20308. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20309. currentMesh._waitingParentId = undefined;
  20310. }
  20311. }
  20312. // freeze world matrix application
  20313. for (index = 0; index < scene.meshes.length; index++) {
  20314. currentMesh = scene.meshes[index];
  20315. if (currentMesh._waitingFreezeWorldMatrix) {
  20316. currentMesh.freezeWorldMatrix();
  20317. currentMesh._waitingFreezeWorldMatrix = undefined;
  20318. }
  20319. }
  20320. // Particles
  20321. if (parsedData.particleSystems) {
  20322. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20323. var parsedParticleSystem = parsedData.particleSystems[index];
  20324. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20325. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20326. }
  20327. }
  20328. }
  20329. return true;
  20330. },
  20331. load: function (scene, data, rootUrl) {
  20332. var parsedData = JSON.parse(data);
  20333. // Scene
  20334. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20335. scene.autoClear = parsedData.autoClear;
  20336. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20337. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20338. if (parsedData.gravity) {
  20339. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20340. }
  20341. // Fog
  20342. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20343. scene.fogMode = parsedData.fogMode;
  20344. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20345. scene.fogStart = parsedData.fogStart;
  20346. scene.fogEnd = parsedData.fogEnd;
  20347. scene.fogDensity = parsedData.fogDensity;
  20348. }
  20349. //Physics
  20350. if (parsedData.physicsEnabled) {
  20351. var physicsPlugin;
  20352. if (parsedData.physicsEngine === "cannon") {
  20353. physicsPlugin = new BABYLON.CannonJSPlugin();
  20354. }
  20355. else if (parsedData.physicsEngine === "oimo") {
  20356. physicsPlugin = new BABYLON.OimoJSPlugin();
  20357. }
  20358. //else - default engine, which is currently oimo
  20359. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20360. scene.enablePhysics(physicsGravity, physicsPlugin);
  20361. }
  20362. //collisions, if defined. otherwise, default is true
  20363. if (parsedData.collisionsEnabled != undefined) {
  20364. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20365. }
  20366. scene.workerCollisions = !!parsedData.workerCollisions;
  20367. // Lights
  20368. var index;
  20369. for (index = 0; index < parsedData.lights.length; index++) {
  20370. var parsedLight = parsedData.lights[index];
  20371. parseLight(parsedLight, scene);
  20372. }
  20373. // Materials
  20374. if (parsedData.materials) {
  20375. for (index = 0; index < parsedData.materials.length; index++) {
  20376. var parsedMaterial = parsedData.materials[index];
  20377. parseMaterial(parsedMaterial, scene, rootUrl);
  20378. }
  20379. }
  20380. if (parsedData.multiMaterials) {
  20381. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20382. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20383. parseMultiMaterial(parsedMultiMaterial, scene);
  20384. }
  20385. }
  20386. // Skeletons
  20387. if (parsedData.skeletons) {
  20388. for (index = 0; index < parsedData.skeletons.length; index++) {
  20389. var parsedSkeleton = parsedData.skeletons[index];
  20390. parseSkeleton(parsedSkeleton, scene);
  20391. }
  20392. }
  20393. // Geometries
  20394. var geometries = parsedData.geometries;
  20395. if (geometries) {
  20396. // Boxes
  20397. var boxes = geometries.boxes;
  20398. if (boxes) {
  20399. for (index = 0; index < boxes.length; index++) {
  20400. var parsedBox = boxes[index];
  20401. parseBox(parsedBox, scene);
  20402. }
  20403. }
  20404. // Spheres
  20405. var spheres = geometries.spheres;
  20406. if (spheres) {
  20407. for (index = 0; index < spheres.length; index++) {
  20408. var parsedSphere = spheres[index];
  20409. parseSphere(parsedSphere, scene);
  20410. }
  20411. }
  20412. // Cylinders
  20413. var cylinders = geometries.cylinders;
  20414. if (cylinders) {
  20415. for (index = 0; index < cylinders.length; index++) {
  20416. var parsedCylinder = cylinders[index];
  20417. parseCylinder(parsedCylinder, scene);
  20418. }
  20419. }
  20420. // Toruses
  20421. var toruses = geometries.toruses;
  20422. if (toruses) {
  20423. for (index = 0; index < toruses.length; index++) {
  20424. var parsedTorus = toruses[index];
  20425. parseTorus(parsedTorus, scene);
  20426. }
  20427. }
  20428. // Grounds
  20429. var grounds = geometries.grounds;
  20430. if (grounds) {
  20431. for (index = 0; index < grounds.length; index++) {
  20432. var parsedGround = grounds[index];
  20433. parseGround(parsedGround, scene);
  20434. }
  20435. }
  20436. // Planes
  20437. var planes = geometries.planes;
  20438. if (planes) {
  20439. for (index = 0; index < planes.length; index++) {
  20440. var parsedPlane = planes[index];
  20441. parsePlane(parsedPlane, scene);
  20442. }
  20443. }
  20444. // TorusKnots
  20445. var torusKnots = geometries.torusKnots;
  20446. if (torusKnots) {
  20447. for (index = 0; index < torusKnots.length; index++) {
  20448. var parsedTorusKnot = torusKnots[index];
  20449. parseTorusKnot(parsedTorusKnot, scene);
  20450. }
  20451. }
  20452. // VertexData
  20453. var vertexData = geometries.vertexData;
  20454. if (vertexData) {
  20455. for (index = 0; index < vertexData.length; index++) {
  20456. var parsedVertexData = vertexData[index];
  20457. parseVertexData(parsedVertexData, scene, rootUrl);
  20458. }
  20459. }
  20460. }
  20461. // Meshes
  20462. for (index = 0; index < parsedData.meshes.length; index++) {
  20463. var parsedMesh = parsedData.meshes[index];
  20464. parseMesh(parsedMesh, scene, rootUrl);
  20465. }
  20466. // Cameras
  20467. for (index = 0; index < parsedData.cameras.length; index++) {
  20468. var parsedCamera = parsedData.cameras[index];
  20469. parseCamera(parsedCamera, scene);
  20470. }
  20471. if (parsedData.activeCameraID) {
  20472. scene.setActiveCameraByID(parsedData.activeCameraID);
  20473. }
  20474. // Browsing all the graph to connect the dots
  20475. for (index = 0; index < scene.cameras.length; index++) {
  20476. var camera = scene.cameras[index];
  20477. if (camera._waitingParentId) {
  20478. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20479. camera._waitingParentId = undefined;
  20480. }
  20481. }
  20482. for (index = 0; index < scene.lights.length; index++) {
  20483. var light = scene.lights[index];
  20484. if (light._waitingParentId) {
  20485. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20486. light._waitingParentId = undefined;
  20487. }
  20488. }
  20489. // Sounds
  20490. if (BABYLON.AudioEngine && parsedData.sounds) {
  20491. for (index = 0; index < parsedData.sounds.length; index++) {
  20492. var parsedSound = parsedData.sounds[index];
  20493. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20494. parseSound(parsedSound, scene, rootUrl);
  20495. }
  20496. else {
  20497. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20498. }
  20499. }
  20500. }
  20501. // Connect parents & children and parse actions
  20502. for (index = 0; index < scene.meshes.length; index++) {
  20503. var mesh = scene.meshes[index];
  20504. if (mesh._waitingParentId) {
  20505. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20506. mesh._waitingParentId = undefined;
  20507. }
  20508. if (mesh._waitingActions) {
  20509. parseActions(mesh._waitingActions, mesh, scene);
  20510. mesh._waitingActions = undefined;
  20511. }
  20512. }
  20513. // freeze world matrix application
  20514. for (index = 0; index < scene.meshes.length; index++) {
  20515. var currentMesh = scene.meshes[index];
  20516. if (currentMesh._waitingFreezeWorldMatrix) {
  20517. currentMesh.freezeWorldMatrix();
  20518. currentMesh._waitingFreezeWorldMatrix = undefined;
  20519. }
  20520. }
  20521. // Particles Systems
  20522. if (parsedData.particleSystems) {
  20523. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20524. var parsedParticleSystem = parsedData.particleSystems[index];
  20525. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20526. }
  20527. }
  20528. // Lens flares
  20529. if (parsedData.lensFlareSystems) {
  20530. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20531. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20532. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20533. }
  20534. }
  20535. // Shadows
  20536. if (parsedData.shadowGenerators) {
  20537. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20538. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20539. parseShadowGenerator(parsedShadowGenerator, scene);
  20540. }
  20541. }
  20542. // Actions (scene)
  20543. if (parsedData.actions) {
  20544. parseActions(parsedData.actions, null, scene);
  20545. }
  20546. // Finish
  20547. return true;
  20548. }
  20549. });
  20550. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20551. })(BABYLON || (BABYLON = {}));
  20552. var BABYLON;
  20553. (function (BABYLON) {
  20554. var SpriteManager = (function () {
  20555. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20557. this.name = name;
  20558. this.cellSize = cellSize;
  20559. this.sprites = new Array();
  20560. this.renderingGroupId = 0;
  20561. this.layerMask = 0x0FFFFFFF;
  20562. this.fogEnabled = true;
  20563. this.isPickable = false;
  20564. this._vertexDeclaration = [4, 4, 4, 4];
  20565. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20566. this._capacity = capacity;
  20567. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20568. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20569. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20570. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20571. this._scene = scene;
  20572. this._scene.spriteManagers.push(this);
  20573. // VBO
  20574. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20575. var indices = [];
  20576. var index = 0;
  20577. for (var count = 0; count < capacity; count++) {
  20578. indices.push(index);
  20579. indices.push(index + 1);
  20580. indices.push(index + 2);
  20581. indices.push(index);
  20582. indices.push(index + 2);
  20583. indices.push(index + 3);
  20584. index += 4;
  20585. }
  20586. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20587. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20588. // Effects
  20589. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20590. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20591. }
  20592. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20593. var arrayOffset = index * 16;
  20594. if (offsetX === 0)
  20595. offsetX = this._epsilon;
  20596. else if (offsetX === 1)
  20597. offsetX = 1 - this._epsilon;
  20598. if (offsetY === 0)
  20599. offsetY = this._epsilon;
  20600. else if (offsetY === 1)
  20601. offsetY = 1 - this._epsilon;
  20602. this._vertices[arrayOffset] = sprite.position.x;
  20603. this._vertices[arrayOffset + 1] = sprite.position.y;
  20604. this._vertices[arrayOffset + 2] = sprite.position.z;
  20605. this._vertices[arrayOffset + 3] = sprite.angle;
  20606. this._vertices[arrayOffset + 4] = sprite.width;
  20607. this._vertices[arrayOffset + 5] = sprite.height;
  20608. this._vertices[arrayOffset + 6] = offsetX;
  20609. this._vertices[arrayOffset + 7] = offsetY;
  20610. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20611. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20612. var offset = (sprite.cellIndex / rowSize) >> 0;
  20613. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20614. this._vertices[arrayOffset + 11] = offset;
  20615. // Color
  20616. this._vertices[arrayOffset + 12] = sprite.color.r;
  20617. this._vertices[arrayOffset + 13] = sprite.color.g;
  20618. this._vertices[arrayOffset + 14] = sprite.color.b;
  20619. this._vertices[arrayOffset + 15] = sprite.color.a;
  20620. };
  20621. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20622. var count = Math.min(this._capacity, this.sprites.length);
  20623. var min = BABYLON.Vector3.Zero();
  20624. var max = BABYLON.Vector3.Zero();
  20625. var distance = Number.MAX_VALUE;
  20626. var currentSprite;
  20627. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20628. var cameraView = camera.getViewMatrix();
  20629. for (var index = 0; index < count; index++) {
  20630. var sprite = this.sprites[index];
  20631. if (!sprite) {
  20632. continue;
  20633. }
  20634. if (predicate) {
  20635. if (!predicate(sprite)) {
  20636. continue;
  20637. }
  20638. }
  20639. else if (!sprite.isPickable) {
  20640. continue;
  20641. }
  20642. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20643. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20644. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20645. if (ray.intersectsBoxMinMax(min, max)) {
  20646. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20647. if (distance > currentDistance) {
  20648. distance = currentDistance;
  20649. currentSprite = sprite;
  20650. if (fastCheck) {
  20651. break;
  20652. }
  20653. }
  20654. }
  20655. }
  20656. if (currentSprite) {
  20657. var result = new BABYLON.PickingInfo();
  20658. result.hit = true;
  20659. result.pickedSprite = currentSprite;
  20660. result.distance = distance;
  20661. return result;
  20662. }
  20663. return null;
  20664. };
  20665. SpriteManager.prototype.render = function () {
  20666. // Check
  20667. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20668. return;
  20669. var engine = this._scene.getEngine();
  20670. var baseSize = this._spriteTexture.getBaseSize();
  20671. // Sprites
  20672. var deltaTime = engine.getDeltaTime();
  20673. var max = Math.min(this._capacity, this.sprites.length);
  20674. var rowSize = baseSize.width / this.cellSize;
  20675. var offset = 0;
  20676. for (var index = 0; index < max; index++) {
  20677. var sprite = this.sprites[index];
  20678. if (!sprite) {
  20679. continue;
  20680. }
  20681. sprite._animate(deltaTime);
  20682. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20683. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20684. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20685. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20686. }
  20687. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20688. // Render
  20689. var effect = this._effectBase;
  20690. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20691. effect = this._effectFog;
  20692. }
  20693. engine.enableEffect(effect);
  20694. var viewMatrix = this._scene.getViewMatrix();
  20695. effect.setTexture("diffuseSampler", this._spriteTexture);
  20696. effect.setMatrix("view", viewMatrix);
  20697. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20698. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20699. // Fog
  20700. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20701. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20702. effect.setColor3("vFogColor", this._scene.fogColor);
  20703. }
  20704. // VBOs
  20705. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20706. // Draw order
  20707. engine.setDepthFunctionToLessOrEqual();
  20708. effect.setBool("alphaTest", true);
  20709. engine.setColorWrite(false);
  20710. engine.draw(true, 0, max * 6);
  20711. engine.setColorWrite(true);
  20712. effect.setBool("alphaTest", false);
  20713. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20714. engine.draw(true, 0, max * 6);
  20715. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20716. };
  20717. SpriteManager.prototype.dispose = function () {
  20718. if (this._vertexBuffer) {
  20719. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20720. this._vertexBuffer = null;
  20721. }
  20722. if (this._indexBuffer) {
  20723. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20724. this._indexBuffer = null;
  20725. }
  20726. if (this._spriteTexture) {
  20727. this._spriteTexture.dispose();
  20728. this._spriteTexture = null;
  20729. }
  20730. // Remove from scene
  20731. var index = this._scene.spriteManagers.indexOf(this);
  20732. this._scene.spriteManagers.splice(index, 1);
  20733. // Callback
  20734. if (this.onDispose) {
  20735. this.onDispose();
  20736. }
  20737. };
  20738. return SpriteManager;
  20739. })();
  20740. BABYLON.SpriteManager = SpriteManager;
  20741. })(BABYLON || (BABYLON = {}));
  20742. var BABYLON;
  20743. (function (BABYLON) {
  20744. var Sprite = (function () {
  20745. function Sprite(name, manager) {
  20746. this.name = name;
  20747. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20748. this.width = 1.0;
  20749. this.height = 1.0;
  20750. this.angle = 0;
  20751. this.cellIndex = 0;
  20752. this.invertU = 0;
  20753. this.invertV = 0;
  20754. this.animations = new Array();
  20755. this.isPickable = false;
  20756. this._animationStarted = false;
  20757. this._loopAnimation = false;
  20758. this._fromIndex = 0;
  20759. this._toIndex = 0;
  20760. this._delay = 0;
  20761. this._direction = 1;
  20762. this._frameCount = 0;
  20763. this._time = 0;
  20764. this._manager = manager;
  20765. this._manager.sprites.push(this);
  20766. this.position = BABYLON.Vector3.Zero();
  20767. }
  20768. Object.defineProperty(Sprite.prototype, "size", {
  20769. get: function () {
  20770. return this.width;
  20771. },
  20772. set: function (value) {
  20773. this.width = value;
  20774. this.height = value;
  20775. },
  20776. enumerable: true,
  20777. configurable: true
  20778. });
  20779. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20780. this._fromIndex = from;
  20781. this._toIndex = to;
  20782. this._loopAnimation = loop;
  20783. this._delay = delay;
  20784. this._animationStarted = true;
  20785. this._direction = from < to ? 1 : -1;
  20786. this.cellIndex = from;
  20787. this._time = 0;
  20788. };
  20789. Sprite.prototype.stopAnimation = function () {
  20790. this._animationStarted = false;
  20791. };
  20792. Sprite.prototype._animate = function (deltaTime) {
  20793. if (!this._animationStarted)
  20794. return;
  20795. this._time += deltaTime;
  20796. if (this._time > this._delay) {
  20797. this._time = this._time % this._delay;
  20798. this.cellIndex += this._direction;
  20799. if (this.cellIndex == this._toIndex) {
  20800. if (this._loopAnimation) {
  20801. this.cellIndex = this._fromIndex;
  20802. }
  20803. else {
  20804. this._animationStarted = false;
  20805. if (this.disposeWhenFinishedAnimating) {
  20806. this.dispose();
  20807. }
  20808. }
  20809. }
  20810. }
  20811. };
  20812. Sprite.prototype.dispose = function () {
  20813. for (var i = 0; i < this._manager.sprites.length; i++) {
  20814. if (this._manager.sprites[i] == this) {
  20815. this._manager.sprites.splice(i, 1);
  20816. }
  20817. }
  20818. };
  20819. return Sprite;
  20820. })();
  20821. BABYLON.Sprite = Sprite;
  20822. })(BABYLON || (BABYLON = {}));
  20823. var BABYLON;
  20824. (function (BABYLON) {
  20825. var Layer = (function () {
  20826. function Layer(name, imgUrl, scene, isBackground, color) {
  20827. this.name = name;
  20828. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20829. this._vertexDeclaration = [2];
  20830. this._vertexStrideSize = 2 * 4;
  20831. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20832. this.isBackground = isBackground === undefined ? true : isBackground;
  20833. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20834. this._scene = scene;
  20835. this._scene.layers.push(this);
  20836. // VBO
  20837. var vertices = [];
  20838. vertices.push(1, 1);
  20839. vertices.push(-1, 1);
  20840. vertices.push(-1, -1);
  20841. vertices.push(1, -1);
  20842. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20843. // Indices
  20844. var indices = [];
  20845. indices.push(0);
  20846. indices.push(1);
  20847. indices.push(2);
  20848. indices.push(0);
  20849. indices.push(2);
  20850. indices.push(3);
  20851. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20852. // Effects
  20853. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20854. }
  20855. Layer.prototype.render = function () {
  20856. // Check
  20857. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20858. return;
  20859. var engine = this._scene.getEngine();
  20860. // Render
  20861. engine.enableEffect(this._effect);
  20862. engine.setState(false);
  20863. // Texture
  20864. this._effect.setTexture("textureSampler", this.texture);
  20865. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20866. // Color
  20867. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20868. // VBOs
  20869. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20870. // Draw order
  20871. engine.setAlphaMode(this.alphaBlendingMode);
  20872. engine.draw(true, 0, 6);
  20873. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20874. };
  20875. Layer.prototype.dispose = function () {
  20876. if (this._vertexBuffer) {
  20877. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20878. this._vertexBuffer = null;
  20879. }
  20880. if (this._indexBuffer) {
  20881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20882. this._indexBuffer = null;
  20883. }
  20884. if (this.texture) {
  20885. this.texture.dispose();
  20886. this.texture = null;
  20887. }
  20888. // Remove from scene
  20889. var index = this._scene.layers.indexOf(this);
  20890. this._scene.layers.splice(index, 1);
  20891. // Callback
  20892. if (this.onDispose) {
  20893. this.onDispose();
  20894. }
  20895. };
  20896. return Layer;
  20897. })();
  20898. BABYLON.Layer = Layer;
  20899. })(BABYLON || (BABYLON = {}));
  20900. var BABYLON;
  20901. (function (BABYLON) {
  20902. var Particle = (function () {
  20903. function Particle() {
  20904. this.position = BABYLON.Vector3.Zero();
  20905. this.direction = BABYLON.Vector3.Zero();
  20906. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20907. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20908. this.lifeTime = 1.0;
  20909. this.age = 0;
  20910. this.size = 0;
  20911. this.angle = 0;
  20912. this.angularSpeed = 0;
  20913. }
  20914. Particle.prototype.copyTo = function (other) {
  20915. other.position.copyFrom(this.position);
  20916. other.direction.copyFrom(this.direction);
  20917. other.color.copyFrom(this.color);
  20918. other.colorStep.copyFrom(this.colorStep);
  20919. other.lifeTime = this.lifeTime;
  20920. other.age = this.age;
  20921. other.size = this.size;
  20922. other.angle = this.angle;
  20923. other.angularSpeed = this.angularSpeed;
  20924. };
  20925. return Particle;
  20926. })();
  20927. BABYLON.Particle = Particle;
  20928. })(BABYLON || (BABYLON = {}));
  20929. var BABYLON;
  20930. (function (BABYLON) {
  20931. var randomNumber = function (min, max) {
  20932. if (min === max) {
  20933. return (min);
  20934. }
  20935. var random = Math.random();
  20936. return ((random * (max - min)) + min);
  20937. };
  20938. var ParticleSystem = (function () {
  20939. function ParticleSystem(name, capacity, scene, customEffect) {
  20940. var _this = this;
  20941. this.name = name;
  20942. this.renderingGroupId = 0;
  20943. this.emitter = null;
  20944. this.emitRate = 10;
  20945. this.manualEmitCount = -1;
  20946. this.updateSpeed = 0.01;
  20947. this.targetStopDuration = 0;
  20948. this.disposeOnStop = false;
  20949. this.minEmitPower = 1;
  20950. this.maxEmitPower = 1;
  20951. this.minLifeTime = 1;
  20952. this.maxLifeTime = 1;
  20953. this.minSize = 1;
  20954. this.maxSize = 1;
  20955. this.minAngularSpeed = 0;
  20956. this.maxAngularSpeed = 0;
  20957. this.layerMask = 0x0FFFFFFF;
  20958. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20959. this.forceDepthWrite = false;
  20960. this.gravity = BABYLON.Vector3.Zero();
  20961. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20962. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20963. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20964. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20965. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20966. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20967. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20968. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20969. this.particles = new Array();
  20970. this._vertexDeclaration = [3, 4, 4];
  20971. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20972. this._stockParticles = new Array();
  20973. this._newPartsExcess = 0;
  20974. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20975. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20976. this._scaledDirection = BABYLON.Vector3.Zero();
  20977. this._scaledGravity = BABYLON.Vector3.Zero();
  20978. this._currentRenderId = -1;
  20979. this._started = false;
  20980. this._stopped = false;
  20981. this._actualFrame = 0;
  20982. this.id = name;
  20983. this._capacity = capacity;
  20984. this._scene = scene;
  20985. this._customEffect = customEffect;
  20986. scene.particleSystems.push(this);
  20987. // VBO
  20988. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20989. var indices = [];
  20990. var index = 0;
  20991. for (var count = 0; count < capacity; count++) {
  20992. indices.push(index);
  20993. indices.push(index + 1);
  20994. indices.push(index + 2);
  20995. indices.push(index);
  20996. indices.push(index + 2);
  20997. indices.push(index + 3);
  20998. index += 4;
  20999. }
  21000. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21001. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21002. // Default behaviors
  21003. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21004. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21005. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21006. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21007. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21008. };
  21009. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21010. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21011. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21012. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21014. };
  21015. this.updateFunction = function (particles) {
  21016. for (var index = 0; index < particles.length; index++) {
  21017. var particle = particles[index];
  21018. particle.age += _this._scaledUpdateSpeed;
  21019. if (particle.age >= particle.lifeTime) {
  21020. _this.recycleParticle(particle);
  21021. index--;
  21022. continue;
  21023. }
  21024. else {
  21025. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21026. particle.color.addInPlace(_this._scaledColorStep);
  21027. if (particle.color.a < 0)
  21028. particle.color.a = 0;
  21029. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21030. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21031. particle.position.addInPlace(_this._scaledDirection);
  21032. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21033. particle.direction.addInPlace(_this._scaledGravity);
  21034. }
  21035. }
  21036. };
  21037. }
  21038. ParticleSystem.prototype.recycleParticle = function (particle) {
  21039. var lastParticle = this.particles.pop();
  21040. if (lastParticle !== particle) {
  21041. lastParticle.copyTo(particle);
  21042. this._stockParticles.push(lastParticle);
  21043. }
  21044. };
  21045. ParticleSystem.prototype.getCapacity = function () {
  21046. return this._capacity;
  21047. };
  21048. ParticleSystem.prototype.isAlive = function () {
  21049. return this._alive;
  21050. };
  21051. ParticleSystem.prototype.isStarted = function () {
  21052. return this._started;
  21053. };
  21054. ParticleSystem.prototype.start = function () {
  21055. this._started = true;
  21056. this._stopped = false;
  21057. this._actualFrame = 0;
  21058. };
  21059. ParticleSystem.prototype.stop = function () {
  21060. this._stopped = true;
  21061. };
  21062. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21063. var offset = index * 11;
  21064. this._vertices[offset] = particle.position.x;
  21065. this._vertices[offset + 1] = particle.position.y;
  21066. this._vertices[offset + 2] = particle.position.z;
  21067. this._vertices[offset + 3] = particle.color.r;
  21068. this._vertices[offset + 4] = particle.color.g;
  21069. this._vertices[offset + 5] = particle.color.b;
  21070. this._vertices[offset + 6] = particle.color.a;
  21071. this._vertices[offset + 7] = particle.angle;
  21072. this._vertices[offset + 8] = particle.size;
  21073. this._vertices[offset + 9] = offsetX;
  21074. this._vertices[offset + 10] = offsetY;
  21075. };
  21076. ParticleSystem.prototype._update = function (newParticles) {
  21077. // Update current
  21078. this._alive = this.particles.length > 0;
  21079. this.updateFunction(this.particles);
  21080. // Add new ones
  21081. var worldMatrix;
  21082. if (this.emitter.position) {
  21083. worldMatrix = this.emitter.getWorldMatrix();
  21084. }
  21085. else {
  21086. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21087. }
  21088. for (var index = 0; index < newParticles; index++) {
  21089. if (this.particles.length === this._capacity) {
  21090. break;
  21091. }
  21092. if (this._stockParticles.length !== 0) {
  21093. var particle = this._stockParticles.pop();
  21094. particle.age = 0;
  21095. }
  21096. else {
  21097. particle = new BABYLON.Particle();
  21098. }
  21099. this.particles.push(particle);
  21100. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21101. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21102. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21103. particle.size = randomNumber(this.minSize, this.maxSize);
  21104. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21105. this.startPositionFunction(worldMatrix, particle.position, particle);
  21106. var step = randomNumber(0, 1.0);
  21107. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21108. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21109. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21110. }
  21111. };
  21112. ParticleSystem.prototype._getEffect = function () {
  21113. if (this._customEffect) {
  21114. return this._customEffect;
  21115. }
  21116. ;
  21117. var defines = [];
  21118. if (this._scene.clipPlane) {
  21119. defines.push("#define CLIPPLANE");
  21120. }
  21121. // Effect
  21122. var join = defines.join("\n");
  21123. if (this._cachedDefines !== join) {
  21124. this._cachedDefines = join;
  21125. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21126. }
  21127. return this._effect;
  21128. };
  21129. ParticleSystem.prototype.animate = function () {
  21130. if (!this._started)
  21131. return;
  21132. var effect = this._getEffect();
  21133. // Check
  21134. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21135. return;
  21136. if (this._currentRenderId === this._scene.getRenderId()) {
  21137. return;
  21138. }
  21139. this._currentRenderId = this._scene.getRenderId();
  21140. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21141. // determine the number of particles we need to create
  21142. var emitCout;
  21143. if (this.manualEmitCount > -1) {
  21144. emitCout = this.manualEmitCount;
  21145. this.manualEmitCount = 0;
  21146. }
  21147. else {
  21148. emitCout = this.emitRate;
  21149. }
  21150. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21151. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21152. if (this._newPartsExcess > 1.0) {
  21153. newParticles += this._newPartsExcess >> 0;
  21154. this._newPartsExcess -= this._newPartsExcess >> 0;
  21155. }
  21156. this._alive = false;
  21157. if (!this._stopped) {
  21158. this._actualFrame += this._scaledUpdateSpeed;
  21159. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21160. this.stop();
  21161. }
  21162. else {
  21163. newParticles = 0;
  21164. }
  21165. this._update(newParticles);
  21166. // Stopped?
  21167. if (this._stopped) {
  21168. if (!this._alive) {
  21169. this._started = false;
  21170. if (this.disposeOnStop) {
  21171. this._scene._toBeDisposed.push(this);
  21172. }
  21173. }
  21174. }
  21175. // Update VBO
  21176. var offset = 0;
  21177. for (var index = 0; index < this.particles.length; index++) {
  21178. var particle = this.particles[index];
  21179. this._appendParticleVertex(offset++, particle, 0, 0);
  21180. this._appendParticleVertex(offset++, particle, 1, 0);
  21181. this._appendParticleVertex(offset++, particle, 1, 1);
  21182. this._appendParticleVertex(offset++, particle, 0, 1);
  21183. }
  21184. var engine = this._scene.getEngine();
  21185. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21186. };
  21187. ParticleSystem.prototype.render = function () {
  21188. var effect = this._getEffect();
  21189. // Check
  21190. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21191. return 0;
  21192. var engine = this._scene.getEngine();
  21193. // Render
  21194. engine.enableEffect(effect);
  21195. engine.setState(false);
  21196. var viewMatrix = this._scene.getViewMatrix();
  21197. effect.setTexture("diffuseSampler", this.particleTexture);
  21198. effect.setMatrix("view", viewMatrix);
  21199. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21200. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21201. if (this._scene.clipPlane) {
  21202. var clipPlane = this._scene.clipPlane;
  21203. var invView = viewMatrix.clone();
  21204. invView.invert();
  21205. effect.setMatrix("invView", invView);
  21206. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21207. }
  21208. // VBOs
  21209. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21210. // Draw order
  21211. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21212. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21213. }
  21214. else {
  21215. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21216. }
  21217. if (this.forceDepthWrite) {
  21218. engine.setDepthWrite(true);
  21219. }
  21220. engine.draw(true, 0, this.particles.length * 6);
  21221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21222. return this.particles.length;
  21223. };
  21224. ParticleSystem.prototype.dispose = function () {
  21225. if (this._vertexBuffer) {
  21226. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21227. this._vertexBuffer = null;
  21228. }
  21229. if (this._indexBuffer) {
  21230. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21231. this._indexBuffer = null;
  21232. }
  21233. if (this.particleTexture) {
  21234. this.particleTexture.dispose();
  21235. this.particleTexture = null;
  21236. }
  21237. // Remove from scene
  21238. var index = this._scene.particleSystems.indexOf(this);
  21239. this._scene.particleSystems.splice(index, 1);
  21240. // Callback
  21241. if (this.onDispose) {
  21242. this.onDispose();
  21243. }
  21244. };
  21245. // Clone
  21246. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21247. var result = new ParticleSystem(name, this._capacity, this._scene);
  21248. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21249. if (newEmitter === undefined) {
  21250. newEmitter = this.emitter;
  21251. }
  21252. result.emitter = newEmitter;
  21253. if (this.particleTexture) {
  21254. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21255. }
  21256. result.start();
  21257. return result;
  21258. };
  21259. // Statics
  21260. ParticleSystem.BLENDMODE_ONEONE = 0;
  21261. ParticleSystem.BLENDMODE_STANDARD = 1;
  21262. return ParticleSystem;
  21263. })();
  21264. BABYLON.ParticleSystem = ParticleSystem;
  21265. })(BABYLON || (BABYLON = {}));
  21266. var BABYLON;
  21267. (function (BABYLON) {
  21268. var AnimationRange = (function () {
  21269. function AnimationRange(name, from, to) {
  21270. this.name = name;
  21271. this.from = from;
  21272. this.to = to;
  21273. }
  21274. return AnimationRange;
  21275. })();
  21276. BABYLON.AnimationRange = AnimationRange;
  21277. /**
  21278. * Composed of a frame, and an action function
  21279. */
  21280. var AnimationEvent = (function () {
  21281. function AnimationEvent(frame, action, onlyOnce) {
  21282. this.frame = frame;
  21283. this.action = action;
  21284. this.onlyOnce = onlyOnce;
  21285. this.isDone = false;
  21286. }
  21287. return AnimationEvent;
  21288. })();
  21289. BABYLON.AnimationEvent = AnimationEvent;
  21290. var Animation = (function () {
  21291. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21292. this.name = name;
  21293. this.targetProperty = targetProperty;
  21294. this.framePerSecond = framePerSecond;
  21295. this.dataType = dataType;
  21296. this.loopMode = loopMode;
  21297. this._offsetsCache = {};
  21298. this._highLimitsCache = {};
  21299. this._stopped = false;
  21300. // The set of event that will be linked to this animation
  21301. this._events = new Array();
  21302. this.allowMatricesInterpolation = false;
  21303. this._ranges = new Array();
  21304. this.targetPropertyPath = targetProperty.split(".");
  21305. this.dataType = dataType;
  21306. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21307. }
  21308. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21309. var dataType = undefined;
  21310. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21311. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21312. }
  21313. else if (from instanceof BABYLON.Quaternion) {
  21314. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21315. }
  21316. else if (from instanceof BABYLON.Vector3) {
  21317. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21318. }
  21319. else if (from instanceof BABYLON.Vector2) {
  21320. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21321. }
  21322. else if (from instanceof BABYLON.Color3) {
  21323. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21324. }
  21325. if (dataType == undefined) {
  21326. return null;
  21327. }
  21328. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21329. var keys = [];
  21330. keys.push({ frame: 0, value: from });
  21331. keys.push({ frame: totalFrame, value: to });
  21332. animation.setKeys(keys);
  21333. if (easingFunction !== undefined) {
  21334. animation.setEasingFunction(easingFunction);
  21335. }
  21336. return animation;
  21337. };
  21338. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21339. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21340. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21341. };
  21342. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21343. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21344. node.animations.push(animation);
  21345. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21346. };
  21347. // Methods
  21348. /**
  21349. * Add an event to this animation.
  21350. */
  21351. Animation.prototype.addEvent = function (event) {
  21352. this._events.push(event);
  21353. };
  21354. /**
  21355. * Remove all events found at the given frame
  21356. * @param frame
  21357. */
  21358. Animation.prototype.removeEvents = function (frame) {
  21359. for (var index = 0; index < this._events.length; index++) {
  21360. if (this._events[index].frame === frame) {
  21361. this._events.splice(index, 1);
  21362. index--;
  21363. }
  21364. }
  21365. };
  21366. Animation.prototype.createRange = function (name, from, to) {
  21367. this._ranges.push(new AnimationRange(name, from, to));
  21368. };
  21369. Animation.prototype.deleteRange = function (name) {
  21370. for (var index = 0; index < this._ranges.length; index++) {
  21371. if (this._ranges[index].name === name) {
  21372. this._ranges.splice(index, 1);
  21373. return;
  21374. }
  21375. }
  21376. };
  21377. Animation.prototype.getRange = function (name) {
  21378. for (var index = 0; index < this._ranges.length; index++) {
  21379. if (this._ranges[index].name === name) {
  21380. return this._ranges[index];
  21381. }
  21382. }
  21383. return null;
  21384. };
  21385. Animation.prototype.reset = function () {
  21386. this._offsetsCache = {};
  21387. this._highLimitsCache = {};
  21388. this.currentFrame = 0;
  21389. };
  21390. Animation.prototype.isStopped = function () {
  21391. return this._stopped;
  21392. };
  21393. Animation.prototype.getKeys = function () {
  21394. return this._keys;
  21395. };
  21396. Animation.prototype.getEasingFunction = function () {
  21397. return this._easingFunction;
  21398. };
  21399. Animation.prototype.setEasingFunction = function (easingFunction) {
  21400. this._easingFunction = easingFunction;
  21401. };
  21402. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21403. return startValue + (endValue - startValue) * gradient;
  21404. };
  21405. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21406. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21407. };
  21408. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21409. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21410. };
  21411. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21412. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21413. };
  21414. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21415. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21416. };
  21417. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21418. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21419. };
  21420. Animation.prototype.clone = function () {
  21421. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21422. if (this._keys) {
  21423. clone.setKeys(this._keys);
  21424. }
  21425. return clone;
  21426. };
  21427. Animation.prototype.setKeys = function (values) {
  21428. this._keys = values.slice(0);
  21429. this._offsetsCache = {};
  21430. this._highLimitsCache = {};
  21431. };
  21432. Animation.prototype._getKeyValue = function (value) {
  21433. if (typeof value === "function") {
  21434. return value();
  21435. }
  21436. return value;
  21437. };
  21438. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21439. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21440. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21441. }
  21442. this.currentFrame = currentFrame;
  21443. // Try to get a hash to find the right key
  21444. 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));
  21445. if (this._keys[startKey].frame >= currentFrame) {
  21446. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21447. startKey--;
  21448. }
  21449. }
  21450. for (var key = startKey; key < this._keys.length; key++) {
  21451. if (this._keys[key + 1].frame >= currentFrame) {
  21452. var startValue = this._getKeyValue(this._keys[key].value);
  21453. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21454. // gradient : percent of currentFrame between the frame inf and the frame sup
  21455. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21456. // check for easingFunction and correction of gradient
  21457. if (this._easingFunction != null) {
  21458. gradient = this._easingFunction.ease(gradient);
  21459. }
  21460. switch (this.dataType) {
  21461. // Float
  21462. case Animation.ANIMATIONTYPE_FLOAT:
  21463. switch (loopMode) {
  21464. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21465. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21466. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21467. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21468. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21469. }
  21470. break;
  21471. // Quaternion
  21472. case Animation.ANIMATIONTYPE_QUATERNION:
  21473. var quaternion = null;
  21474. switch (loopMode) {
  21475. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21476. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21477. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21478. break;
  21479. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21480. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21481. break;
  21482. }
  21483. return quaternion;
  21484. // Vector3
  21485. case Animation.ANIMATIONTYPE_VECTOR3:
  21486. switch (loopMode) {
  21487. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21488. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21489. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21490. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21491. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21492. }
  21493. // Vector2
  21494. case Animation.ANIMATIONTYPE_VECTOR2:
  21495. switch (loopMode) {
  21496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21498. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21500. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21501. }
  21502. // Color3
  21503. case Animation.ANIMATIONTYPE_COLOR3:
  21504. switch (loopMode) {
  21505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21507. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21508. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21509. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21510. }
  21511. // Matrix
  21512. case Animation.ANIMATIONTYPE_MATRIX:
  21513. switch (loopMode) {
  21514. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21515. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21516. if (this.allowMatricesInterpolation) {
  21517. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21518. }
  21519. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21520. return startValue;
  21521. }
  21522. default:
  21523. break;
  21524. }
  21525. break;
  21526. }
  21527. }
  21528. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21529. };
  21530. Animation.prototype.setValue = function (currentValue) {
  21531. // Set value
  21532. if (this.targetPropertyPath.length > 1) {
  21533. var property = this._target[this.targetPropertyPath[0]];
  21534. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21535. property = property[this.targetPropertyPath[index]];
  21536. }
  21537. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21538. }
  21539. else {
  21540. this._target[this.targetPropertyPath[0]] = currentValue;
  21541. }
  21542. if (this._target.markAsDirty) {
  21543. this._target.markAsDirty(this.targetProperty);
  21544. }
  21545. };
  21546. Animation.prototype.goToFrame = function (frame) {
  21547. if (frame < this._keys[0].frame) {
  21548. frame = this._keys[0].frame;
  21549. }
  21550. else if (frame > this._keys[this._keys.length - 1].frame) {
  21551. frame = this._keys[this._keys.length - 1].frame;
  21552. }
  21553. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21554. this.setValue(currentValue);
  21555. };
  21556. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21557. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21558. this._stopped = true;
  21559. return false;
  21560. }
  21561. var returnValue = true;
  21562. // Adding a start key at frame 0 if missing
  21563. if (this._keys[0].frame !== 0) {
  21564. var newKey = { frame: 0, value: this._keys[0].value };
  21565. this._keys.splice(0, 0, newKey);
  21566. }
  21567. // Check limits
  21568. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21569. from = this._keys[0].frame;
  21570. }
  21571. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21572. to = this._keys[this._keys.length - 1].frame;
  21573. }
  21574. // Compute ratio
  21575. var range = to - from;
  21576. var offsetValue;
  21577. // ratio represents the frame delta between from and to
  21578. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21579. var highLimitValue = 0;
  21580. if (ratio > range && !loop) {
  21581. returnValue = false;
  21582. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21583. }
  21584. else {
  21585. // Get max value if required
  21586. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21587. var keyOffset = to.toString() + from.toString();
  21588. if (!this._offsetsCache[keyOffset]) {
  21589. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21590. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21591. switch (this.dataType) {
  21592. // Float
  21593. case Animation.ANIMATIONTYPE_FLOAT:
  21594. this._offsetsCache[keyOffset] = toValue - fromValue;
  21595. break;
  21596. // Quaternion
  21597. case Animation.ANIMATIONTYPE_QUATERNION:
  21598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21599. break;
  21600. // Vector3
  21601. case Animation.ANIMATIONTYPE_VECTOR3:
  21602. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21603. // Vector2
  21604. case Animation.ANIMATIONTYPE_VECTOR2:
  21605. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21606. // Color3
  21607. case Animation.ANIMATIONTYPE_COLOR3:
  21608. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21609. default:
  21610. break;
  21611. }
  21612. this._highLimitsCache[keyOffset] = toValue;
  21613. }
  21614. highLimitValue = this._highLimitsCache[keyOffset];
  21615. offsetValue = this._offsetsCache[keyOffset];
  21616. }
  21617. }
  21618. if (offsetValue === undefined) {
  21619. switch (this.dataType) {
  21620. // Float
  21621. case Animation.ANIMATIONTYPE_FLOAT:
  21622. offsetValue = 0;
  21623. break;
  21624. // Quaternion
  21625. case Animation.ANIMATIONTYPE_QUATERNION:
  21626. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21627. break;
  21628. // Vector3
  21629. case Animation.ANIMATIONTYPE_VECTOR3:
  21630. offsetValue = BABYLON.Vector3.Zero();
  21631. break;
  21632. // Vector2
  21633. case Animation.ANIMATIONTYPE_VECTOR2:
  21634. offsetValue = BABYLON.Vector2.Zero();
  21635. break;
  21636. // Color3
  21637. case Animation.ANIMATIONTYPE_COLOR3:
  21638. offsetValue = BABYLON.Color3.Black();
  21639. }
  21640. }
  21641. // Compute value
  21642. var repeatCount = (ratio / range) >> 0;
  21643. var currentFrame = returnValue ? from + ratio % range : to;
  21644. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21645. // Check events
  21646. for (var index = 0; index < this._events.length; index++) {
  21647. if (currentFrame >= this._events[index].frame) {
  21648. var event = this._events[index];
  21649. if (!event.isDone) {
  21650. // If event should be done only once, remove it.
  21651. if (event.onlyOnce) {
  21652. this._events.splice(index, 1);
  21653. index--;
  21654. }
  21655. event.isDone = true;
  21656. event.action();
  21657. } // Don't do anything if the event has already be done.
  21658. }
  21659. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21660. // reset event, the animation is looping
  21661. this._events[index].isDone = false;
  21662. }
  21663. }
  21664. // Set value
  21665. this.setValue(currentValue);
  21666. if (!returnValue) {
  21667. this._stopped = true;
  21668. }
  21669. return returnValue;
  21670. };
  21671. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21672. get: function () {
  21673. return Animation._ANIMATIONTYPE_FLOAT;
  21674. },
  21675. enumerable: true,
  21676. configurable: true
  21677. });
  21678. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21679. get: function () {
  21680. return Animation._ANIMATIONTYPE_VECTOR3;
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21686. get: function () {
  21687. return Animation._ANIMATIONTYPE_VECTOR2;
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21693. get: function () {
  21694. return Animation._ANIMATIONTYPE_QUATERNION;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21700. get: function () {
  21701. return Animation._ANIMATIONTYPE_MATRIX;
  21702. },
  21703. enumerable: true,
  21704. configurable: true
  21705. });
  21706. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21707. get: function () {
  21708. return Animation._ANIMATIONTYPE_COLOR3;
  21709. },
  21710. enumerable: true,
  21711. configurable: true
  21712. });
  21713. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21714. get: function () {
  21715. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21716. },
  21717. enumerable: true,
  21718. configurable: true
  21719. });
  21720. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21721. get: function () {
  21722. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21723. },
  21724. enumerable: true,
  21725. configurable: true
  21726. });
  21727. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21728. get: function () {
  21729. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. // Statics
  21735. Animation._ANIMATIONTYPE_FLOAT = 0;
  21736. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21737. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21738. Animation._ANIMATIONTYPE_MATRIX = 3;
  21739. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21740. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21741. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21742. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21743. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21744. return Animation;
  21745. })();
  21746. BABYLON.Animation = Animation;
  21747. })(BABYLON || (BABYLON = {}));
  21748. var BABYLON;
  21749. (function (BABYLON) {
  21750. var Animatable = (function () {
  21751. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21752. if (fromFrame === void 0) { fromFrame = 0; }
  21753. if (toFrame === void 0) { toFrame = 100; }
  21754. if (loopAnimation === void 0) { loopAnimation = false; }
  21755. if (speedRatio === void 0) { speedRatio = 1.0; }
  21756. this.target = target;
  21757. this.fromFrame = fromFrame;
  21758. this.toFrame = toFrame;
  21759. this.loopAnimation = loopAnimation;
  21760. this.speedRatio = speedRatio;
  21761. this.onAnimationEnd = onAnimationEnd;
  21762. this._animations = new Array();
  21763. this._paused = false;
  21764. this.animationStarted = false;
  21765. if (animations) {
  21766. this.appendAnimations(target, animations);
  21767. }
  21768. this._scene = scene;
  21769. scene._activeAnimatables.push(this);
  21770. }
  21771. // Methods
  21772. Animatable.prototype.getAnimations = function () {
  21773. return this._animations;
  21774. };
  21775. Animatable.prototype.appendAnimations = function (target, animations) {
  21776. for (var index = 0; index < animations.length; index++) {
  21777. var animation = animations[index];
  21778. animation._target = target;
  21779. this._animations.push(animation);
  21780. }
  21781. };
  21782. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21783. var animations = this._animations;
  21784. for (var index = 0; index < animations.length; index++) {
  21785. if (animations[index].targetProperty === property) {
  21786. return animations[index];
  21787. }
  21788. }
  21789. return null;
  21790. };
  21791. Animatable.prototype.reset = function () {
  21792. var animations = this._animations;
  21793. for (var index = 0; index < animations.length; index++) {
  21794. animations[index].reset();
  21795. }
  21796. this._localDelayOffset = null;
  21797. this._pausedDelay = null;
  21798. };
  21799. Animatable.prototype.goToFrame = function (frame) {
  21800. var animations = this._animations;
  21801. for (var index = 0; index < animations.length; index++) {
  21802. animations[index].goToFrame(frame);
  21803. }
  21804. };
  21805. Animatable.prototype.pause = function () {
  21806. if (this._paused) {
  21807. return;
  21808. }
  21809. this._paused = true;
  21810. };
  21811. Animatable.prototype.restart = function () {
  21812. this._paused = false;
  21813. };
  21814. Animatable.prototype.stop = function () {
  21815. var index = this._scene._activeAnimatables.indexOf(this);
  21816. if (index > -1) {
  21817. this._scene._activeAnimatables.splice(index, 1);
  21818. }
  21819. if (this.onAnimationEnd) {
  21820. this.onAnimationEnd();
  21821. }
  21822. };
  21823. Animatable.prototype._animate = function (delay) {
  21824. if (this._paused) {
  21825. this.animationStarted = false;
  21826. if (!this._pausedDelay) {
  21827. this._pausedDelay = delay;
  21828. }
  21829. return true;
  21830. }
  21831. if (!this._localDelayOffset) {
  21832. this._localDelayOffset = delay;
  21833. }
  21834. else if (this._pausedDelay) {
  21835. this._localDelayOffset += delay - this._pausedDelay;
  21836. this._pausedDelay = null;
  21837. }
  21838. // Animating
  21839. var running = false;
  21840. var animations = this._animations;
  21841. var index;
  21842. for (index = 0; index < animations.length; index++) {
  21843. var animation = animations[index];
  21844. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21845. running = running || isRunning;
  21846. }
  21847. this.animationStarted = running;
  21848. if (!running) {
  21849. // Remove from active animatables
  21850. index = this._scene._activeAnimatables.indexOf(this);
  21851. this._scene._activeAnimatables.splice(index, 1);
  21852. }
  21853. if (!running && this.onAnimationEnd) {
  21854. this.onAnimationEnd();
  21855. }
  21856. return running;
  21857. };
  21858. return Animatable;
  21859. })();
  21860. BABYLON.Animatable = Animatable;
  21861. })(BABYLON || (BABYLON = {}));
  21862. var BABYLON;
  21863. (function (BABYLON) {
  21864. var EasingFunction = (function () {
  21865. function EasingFunction() {
  21866. // Properties
  21867. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21868. }
  21869. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21870. get: function () {
  21871. return EasingFunction._EASINGMODE_EASEIN;
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21877. get: function () {
  21878. return EasingFunction._EASINGMODE_EASEOUT;
  21879. },
  21880. enumerable: true,
  21881. configurable: true
  21882. });
  21883. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21884. get: function () {
  21885. return EasingFunction._EASINGMODE_EASEINOUT;
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21891. var n = Math.min(Math.max(easingMode, 0), 2);
  21892. this._easingMode = n;
  21893. };
  21894. EasingFunction.prototype.getEasingMode = function () {
  21895. return this._easingMode;
  21896. };
  21897. EasingFunction.prototype.easeInCore = function (gradient) {
  21898. throw new Error('You must implement this method');
  21899. };
  21900. EasingFunction.prototype.ease = function (gradient) {
  21901. switch (this._easingMode) {
  21902. case EasingFunction.EASINGMODE_EASEIN:
  21903. return this.easeInCore(gradient);
  21904. case EasingFunction.EASINGMODE_EASEOUT:
  21905. return (1 - this.easeInCore(1 - gradient));
  21906. }
  21907. if (gradient >= 0.5) {
  21908. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21909. }
  21910. return (this.easeInCore(gradient * 2) * 0.5);
  21911. };
  21912. //Statics
  21913. EasingFunction._EASINGMODE_EASEIN = 0;
  21914. EasingFunction._EASINGMODE_EASEOUT = 1;
  21915. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21916. return EasingFunction;
  21917. })();
  21918. BABYLON.EasingFunction = EasingFunction;
  21919. var CircleEase = (function (_super) {
  21920. __extends(CircleEase, _super);
  21921. function CircleEase() {
  21922. _super.apply(this, arguments);
  21923. }
  21924. CircleEase.prototype.easeInCore = function (gradient) {
  21925. gradient = Math.max(0, Math.min(1, gradient));
  21926. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21927. };
  21928. return CircleEase;
  21929. })(EasingFunction);
  21930. BABYLON.CircleEase = CircleEase;
  21931. var BackEase = (function (_super) {
  21932. __extends(BackEase, _super);
  21933. function BackEase(amplitude) {
  21934. if (amplitude === void 0) { amplitude = 1; }
  21935. _super.call(this);
  21936. this.amplitude = amplitude;
  21937. }
  21938. BackEase.prototype.easeInCore = function (gradient) {
  21939. var num = Math.max(0, this.amplitude);
  21940. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21941. };
  21942. return BackEase;
  21943. })(EasingFunction);
  21944. BABYLON.BackEase = BackEase;
  21945. var BounceEase = (function (_super) {
  21946. __extends(BounceEase, _super);
  21947. function BounceEase(bounces, bounciness) {
  21948. if (bounces === void 0) { bounces = 3; }
  21949. if (bounciness === void 0) { bounciness = 2; }
  21950. _super.call(this);
  21951. this.bounces = bounces;
  21952. this.bounciness = bounciness;
  21953. }
  21954. BounceEase.prototype.easeInCore = function (gradient) {
  21955. var y = Math.max(0.0, this.bounces);
  21956. var bounciness = this.bounciness;
  21957. if (bounciness <= 1.0) {
  21958. bounciness = 1.001;
  21959. }
  21960. var num9 = Math.pow(bounciness, y);
  21961. var num5 = 1.0 - bounciness;
  21962. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21963. var num15 = gradient * num4;
  21964. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21965. var num3 = Math.floor(num65);
  21966. var num13 = num3 + 1.0;
  21967. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21968. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21969. var num7 = (num8 + num12) * 0.5;
  21970. var num6 = gradient - num7;
  21971. var num2 = num7 - num8;
  21972. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21973. };
  21974. return BounceEase;
  21975. })(EasingFunction);
  21976. BABYLON.BounceEase = BounceEase;
  21977. var CubicEase = (function (_super) {
  21978. __extends(CubicEase, _super);
  21979. function CubicEase() {
  21980. _super.apply(this, arguments);
  21981. }
  21982. CubicEase.prototype.easeInCore = function (gradient) {
  21983. return (gradient * gradient * gradient);
  21984. };
  21985. return CubicEase;
  21986. })(EasingFunction);
  21987. BABYLON.CubicEase = CubicEase;
  21988. var ElasticEase = (function (_super) {
  21989. __extends(ElasticEase, _super);
  21990. function ElasticEase(oscillations, springiness) {
  21991. if (oscillations === void 0) { oscillations = 3; }
  21992. if (springiness === void 0) { springiness = 3; }
  21993. _super.call(this);
  21994. this.oscillations = oscillations;
  21995. this.springiness = springiness;
  21996. }
  21997. ElasticEase.prototype.easeInCore = function (gradient) {
  21998. var num2;
  21999. var num3 = Math.max(0.0, this.oscillations);
  22000. var num = Math.max(0.0, this.springiness);
  22001. if (num == 0) {
  22002. num2 = gradient;
  22003. }
  22004. else {
  22005. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22006. }
  22007. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22008. };
  22009. return ElasticEase;
  22010. })(EasingFunction);
  22011. BABYLON.ElasticEase = ElasticEase;
  22012. var ExponentialEase = (function (_super) {
  22013. __extends(ExponentialEase, _super);
  22014. function ExponentialEase(exponent) {
  22015. if (exponent === void 0) { exponent = 2; }
  22016. _super.call(this);
  22017. this.exponent = exponent;
  22018. }
  22019. ExponentialEase.prototype.easeInCore = function (gradient) {
  22020. if (this.exponent <= 0) {
  22021. return gradient;
  22022. }
  22023. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22024. };
  22025. return ExponentialEase;
  22026. })(EasingFunction);
  22027. BABYLON.ExponentialEase = ExponentialEase;
  22028. var PowerEase = (function (_super) {
  22029. __extends(PowerEase, _super);
  22030. function PowerEase(power) {
  22031. if (power === void 0) { power = 2; }
  22032. _super.call(this);
  22033. this.power = power;
  22034. }
  22035. PowerEase.prototype.easeInCore = function (gradient) {
  22036. var y = Math.max(0.0, this.power);
  22037. return Math.pow(gradient, y);
  22038. };
  22039. return PowerEase;
  22040. })(EasingFunction);
  22041. BABYLON.PowerEase = PowerEase;
  22042. var QuadraticEase = (function (_super) {
  22043. __extends(QuadraticEase, _super);
  22044. function QuadraticEase() {
  22045. _super.apply(this, arguments);
  22046. }
  22047. QuadraticEase.prototype.easeInCore = function (gradient) {
  22048. return (gradient * gradient);
  22049. };
  22050. return QuadraticEase;
  22051. })(EasingFunction);
  22052. BABYLON.QuadraticEase = QuadraticEase;
  22053. var QuarticEase = (function (_super) {
  22054. __extends(QuarticEase, _super);
  22055. function QuarticEase() {
  22056. _super.apply(this, arguments);
  22057. }
  22058. QuarticEase.prototype.easeInCore = function (gradient) {
  22059. return (gradient * gradient * gradient * gradient);
  22060. };
  22061. return QuarticEase;
  22062. })(EasingFunction);
  22063. BABYLON.QuarticEase = QuarticEase;
  22064. var QuinticEase = (function (_super) {
  22065. __extends(QuinticEase, _super);
  22066. function QuinticEase() {
  22067. _super.apply(this, arguments);
  22068. }
  22069. QuinticEase.prototype.easeInCore = function (gradient) {
  22070. return (gradient * gradient * gradient * gradient * gradient);
  22071. };
  22072. return QuinticEase;
  22073. })(EasingFunction);
  22074. BABYLON.QuinticEase = QuinticEase;
  22075. var SineEase = (function (_super) {
  22076. __extends(SineEase, _super);
  22077. function SineEase() {
  22078. _super.apply(this, arguments);
  22079. }
  22080. SineEase.prototype.easeInCore = function (gradient) {
  22081. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22082. };
  22083. return SineEase;
  22084. })(EasingFunction);
  22085. BABYLON.SineEase = SineEase;
  22086. var BezierCurveEase = (function (_super) {
  22087. __extends(BezierCurveEase, _super);
  22088. function BezierCurveEase(x1, y1, x2, y2) {
  22089. if (x1 === void 0) { x1 = 0; }
  22090. if (y1 === void 0) { y1 = 0; }
  22091. if (x2 === void 0) { x2 = 1; }
  22092. if (y2 === void 0) { y2 = 1; }
  22093. _super.call(this);
  22094. this.x1 = x1;
  22095. this.y1 = y1;
  22096. this.x2 = x2;
  22097. this.y2 = y2;
  22098. }
  22099. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22100. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22101. };
  22102. return BezierCurveEase;
  22103. })(EasingFunction);
  22104. BABYLON.BezierCurveEase = BezierCurveEase;
  22105. })(BABYLON || (BABYLON = {}));
  22106. var BABYLON;
  22107. (function (BABYLON) {
  22108. var Bone = (function (_super) {
  22109. __extends(Bone, _super);
  22110. function Bone(name, skeleton, parentBone, matrix) {
  22111. _super.call(this, name, skeleton.getScene());
  22112. this.name = name;
  22113. this.children = new Array();
  22114. this.animations = new Array();
  22115. this._worldTransform = new BABYLON.Matrix();
  22116. this._absoluteTransform = new BABYLON.Matrix();
  22117. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22118. this._skeleton = skeleton;
  22119. this._matrix = matrix;
  22120. this._baseMatrix = matrix;
  22121. skeleton.bones.push(this);
  22122. if (parentBone) {
  22123. this._parent = parentBone;
  22124. parentBone.children.push(this);
  22125. }
  22126. else {
  22127. this._parent = null;
  22128. }
  22129. this._updateDifferenceMatrix();
  22130. }
  22131. // Members
  22132. Bone.prototype.getParent = function () {
  22133. return this._parent;
  22134. };
  22135. Bone.prototype.getLocalMatrix = function () {
  22136. return this._matrix;
  22137. };
  22138. Bone.prototype.getBaseMatrix = function () {
  22139. return this._baseMatrix;
  22140. };
  22141. Bone.prototype.getWorldMatrix = function () {
  22142. return this._worldTransform;
  22143. };
  22144. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22145. return this._invertedAbsoluteTransform;
  22146. };
  22147. Bone.prototype.getAbsoluteMatrix = function () {
  22148. var matrix = this._matrix.clone();
  22149. var parent = this._parent;
  22150. while (parent) {
  22151. matrix = matrix.multiply(parent.getLocalMatrix());
  22152. parent = parent.getParent();
  22153. }
  22154. return matrix;
  22155. };
  22156. // Methods
  22157. Bone.prototype.updateMatrix = function (matrix) {
  22158. this._matrix = matrix;
  22159. this._skeleton._markAsDirty();
  22160. this._updateDifferenceMatrix();
  22161. };
  22162. Bone.prototype._updateDifferenceMatrix = function () {
  22163. if (this._parent) {
  22164. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22165. }
  22166. else {
  22167. this._absoluteTransform.copyFrom(this._matrix);
  22168. }
  22169. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22170. for (var index = 0; index < this.children.length; index++) {
  22171. this.children[index]._updateDifferenceMatrix();
  22172. }
  22173. };
  22174. Bone.prototype.markAsDirty = function () {
  22175. this._currentRenderId++;
  22176. this._skeleton._markAsDirty();
  22177. };
  22178. return Bone;
  22179. })(BABYLON.Node);
  22180. BABYLON.Bone = Bone;
  22181. })(BABYLON || (BABYLON = {}));
  22182. var BABYLON;
  22183. (function (BABYLON) {
  22184. var Skeleton = (function () {
  22185. function Skeleton(name, id, scene) {
  22186. this.name = name;
  22187. this.id = id;
  22188. this.bones = new Array();
  22189. this._isDirty = true;
  22190. this._identity = BABYLON.Matrix.Identity();
  22191. this._ranges = new Array();
  22192. this.bones = [];
  22193. this._scene = scene;
  22194. scene.skeletons.push(this);
  22195. this.prepare();
  22196. //make sure it will recalculate the matrix next time prepare is called.
  22197. this._isDirty = true;
  22198. }
  22199. // Members
  22200. Skeleton.prototype.getTransformMatrices = function () {
  22201. return this._transformMatrices;
  22202. };
  22203. Skeleton.prototype.getScene = function () {
  22204. return this._scene;
  22205. };
  22206. // Methods
  22207. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22208. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22209. };
  22210. Skeleton.prototype.deleteAnimationRange = function (name) {
  22211. for (var index = 0; index < this._ranges.length; index++) {
  22212. if (this._ranges[index].name === name) {
  22213. this._ranges.splice(index, 1);
  22214. return;
  22215. }
  22216. }
  22217. };
  22218. Skeleton.prototype.getAnimationRange = function (name) {
  22219. for (var index = 0; index < this._ranges.length; index++) {
  22220. if (this._ranges[index].name === name) {
  22221. return this._ranges[index];
  22222. }
  22223. }
  22224. return null;
  22225. };
  22226. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22227. var range = this.getAnimationRange(name);
  22228. if (!range) {
  22229. return null;
  22230. }
  22231. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22232. };
  22233. Skeleton.prototype._markAsDirty = function () {
  22234. this._isDirty = true;
  22235. };
  22236. Skeleton.prototype.prepare = function () {
  22237. if (!this._isDirty) {
  22238. return;
  22239. }
  22240. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22241. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22242. }
  22243. for (var index = 0; index < this.bones.length; index++) {
  22244. var bone = this.bones[index];
  22245. var parentBone = bone.getParent();
  22246. if (parentBone) {
  22247. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22248. }
  22249. else {
  22250. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22251. }
  22252. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22253. }
  22254. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22255. this._isDirty = false;
  22256. this._scene._activeBones += this.bones.length;
  22257. };
  22258. Skeleton.prototype.getAnimatables = function () {
  22259. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22260. this._animatables = [];
  22261. for (var index = 0; index < this.bones.length; index++) {
  22262. this._animatables.push(this.bones[index]);
  22263. }
  22264. }
  22265. return this._animatables;
  22266. };
  22267. Skeleton.prototype.clone = function (name, id) {
  22268. var result = new Skeleton(name, id || name, this._scene);
  22269. for (var index = 0; index < this.bones.length; index++) {
  22270. var source = this.bones[index];
  22271. var parentBone = null;
  22272. if (source.getParent()) {
  22273. var parentIndex = this.bones.indexOf(source.getParent());
  22274. parentBone = result.bones[parentIndex];
  22275. }
  22276. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22277. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22278. }
  22279. return result;
  22280. };
  22281. Skeleton.prototype.dispose = function () {
  22282. // Animations
  22283. this.getScene().stopAnimation(this);
  22284. // Remove from scene
  22285. this.getScene().removeSkeleton(this);
  22286. };
  22287. return Skeleton;
  22288. })();
  22289. BABYLON.Skeleton = Skeleton;
  22290. })(BABYLON || (BABYLON = {}));
  22291. var BABYLON;
  22292. (function (BABYLON) {
  22293. var PostProcess = (function () {
  22294. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22297. this.name = name;
  22298. this.width = -1;
  22299. this.height = -1;
  22300. this._reusable = false;
  22301. this._textures = new BABYLON.SmartArray(2);
  22302. this._currentRenderTextureInd = 0;
  22303. if (camera != null) {
  22304. this._camera = camera;
  22305. this._scene = camera.getScene();
  22306. camera.attachPostProcess(this);
  22307. this._engine = this._scene.getEngine();
  22308. }
  22309. else {
  22310. this._engine = engine;
  22311. }
  22312. this._renderRatio = ratio;
  22313. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22314. this._reusable = reusable || false;
  22315. this._textureType = textureType;
  22316. this._samplers = samplers || [];
  22317. this._samplers.push("textureSampler");
  22318. this._fragmentUrl = fragmentUrl;
  22319. this._parameters = parameters || [];
  22320. this.updateEffect(defines);
  22321. }
  22322. PostProcess.prototype.updateEffect = function (defines) {
  22323. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22324. };
  22325. PostProcess.prototype.isReusable = function () {
  22326. return this._reusable;
  22327. };
  22328. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22329. camera = camera || this._camera;
  22330. var scene = camera.getScene();
  22331. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22332. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22333. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22334. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22335. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22336. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22337. if (this._textures.length > 0) {
  22338. for (var i = 0; i < this._textures.length; i++) {
  22339. this._engine._releaseTexture(this._textures.data[i]);
  22340. }
  22341. this._textures.reset();
  22342. }
  22343. this.width = desiredWidth;
  22344. this.height = desiredHeight;
  22345. 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 }));
  22346. if (this._reusable) {
  22347. 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 }));
  22348. }
  22349. if (this.onSizeChanged) {
  22350. this.onSizeChanged();
  22351. }
  22352. }
  22353. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22354. if (this.onActivate) {
  22355. this.onActivate(camera);
  22356. }
  22357. // Clear
  22358. if (this.clearColor) {
  22359. this._engine.clear(this.clearColor, true, true);
  22360. }
  22361. else {
  22362. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22363. }
  22364. if (this._reusable) {
  22365. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22366. }
  22367. };
  22368. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22369. get: function () {
  22370. return this._effect.isSupported;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. PostProcess.prototype.apply = function () {
  22376. // Check
  22377. if (!this._effect.isReady())
  22378. return null;
  22379. // States
  22380. this._engine.enableEffect(this._effect);
  22381. this._engine.setState(false);
  22382. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22383. this._engine.setDepthBuffer(false);
  22384. this._engine.setDepthWrite(false);
  22385. // Texture
  22386. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22387. // Parameters
  22388. if (this.onApply) {
  22389. this.onApply(this._effect);
  22390. }
  22391. return this._effect;
  22392. };
  22393. PostProcess.prototype.dispose = function (camera) {
  22394. camera = camera || this._camera;
  22395. if (this._textures.length > 0) {
  22396. for (var i = 0; i < this._textures.length; i++) {
  22397. this._engine._releaseTexture(this._textures.data[i]);
  22398. }
  22399. this._textures.reset();
  22400. }
  22401. if (!camera) {
  22402. return;
  22403. }
  22404. camera.detachPostProcess(this);
  22405. var index = camera._postProcesses.indexOf(this);
  22406. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22407. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22408. }
  22409. };
  22410. return PostProcess;
  22411. })();
  22412. BABYLON.PostProcess = PostProcess;
  22413. })(BABYLON || (BABYLON = {}));
  22414. var BABYLON;
  22415. (function (BABYLON) {
  22416. var PostProcessManager = (function () {
  22417. function PostProcessManager(scene) {
  22418. this._vertexDeclaration = [2];
  22419. this._vertexStrideSize = 2 * 4;
  22420. this._scene = scene;
  22421. }
  22422. PostProcessManager.prototype._prepareBuffers = function () {
  22423. if (this._vertexBuffer) {
  22424. return;
  22425. }
  22426. // VBO
  22427. var vertices = [];
  22428. vertices.push(1, 1);
  22429. vertices.push(-1, 1);
  22430. vertices.push(-1, -1);
  22431. vertices.push(1, -1);
  22432. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22433. // Indices
  22434. var indices = [];
  22435. indices.push(0);
  22436. indices.push(1);
  22437. indices.push(2);
  22438. indices.push(0);
  22439. indices.push(2);
  22440. indices.push(3);
  22441. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22442. };
  22443. // Methods
  22444. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22445. var postProcesses = this._scene.activeCamera._postProcesses;
  22446. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22447. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22448. return false;
  22449. }
  22450. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22451. return true;
  22452. };
  22453. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22454. var engine = this._scene.getEngine();
  22455. for (var index = 0; index < postProcesses.length; index++) {
  22456. if (index < postProcesses.length - 1) {
  22457. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22458. }
  22459. else {
  22460. if (targetTexture) {
  22461. engine.bindFramebuffer(targetTexture);
  22462. }
  22463. else {
  22464. engine.restoreDefaultFramebuffer();
  22465. }
  22466. }
  22467. var pp = postProcesses[index];
  22468. var effect = pp.apply();
  22469. if (effect) {
  22470. if (pp.onBeforeRender) {
  22471. pp.onBeforeRender(effect);
  22472. }
  22473. // VBOs
  22474. this._prepareBuffers();
  22475. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22476. // Draw order
  22477. engine.draw(true, 0, 6);
  22478. if (pp.onAfterRender) {
  22479. pp.onAfterRender(effect);
  22480. }
  22481. }
  22482. }
  22483. // Restore depth buffer
  22484. engine.setDepthBuffer(true);
  22485. engine.setDepthWrite(true);
  22486. };
  22487. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22488. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22489. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22490. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22491. return;
  22492. }
  22493. var engine = this._scene.getEngine();
  22494. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22495. if (index < postProcessesTakenIndices.length - 1) {
  22496. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22497. }
  22498. else {
  22499. if (targetTexture) {
  22500. engine.bindFramebuffer(targetTexture, faceIndex);
  22501. }
  22502. else {
  22503. engine.restoreDefaultFramebuffer();
  22504. }
  22505. }
  22506. if (doNotPresent) {
  22507. break;
  22508. }
  22509. var pp = postProcesses[postProcessesTakenIndices[index]];
  22510. var effect = pp.apply();
  22511. if (effect) {
  22512. if (pp.onBeforeRender) {
  22513. pp.onBeforeRender(effect);
  22514. }
  22515. // VBOs
  22516. this._prepareBuffers();
  22517. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22518. // Draw order
  22519. engine.draw(true, 0, 6);
  22520. if (pp.onAfterRender) {
  22521. pp.onAfterRender(effect);
  22522. }
  22523. }
  22524. }
  22525. // Restore depth buffer
  22526. engine.setDepthBuffer(true);
  22527. engine.setDepthWrite(true);
  22528. };
  22529. PostProcessManager.prototype.dispose = function () {
  22530. if (this._vertexBuffer) {
  22531. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22532. this._vertexBuffer = null;
  22533. }
  22534. if (this._indexBuffer) {
  22535. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22536. this._indexBuffer = null;
  22537. }
  22538. };
  22539. return PostProcessManager;
  22540. })();
  22541. BABYLON.PostProcessManager = PostProcessManager;
  22542. })(BABYLON || (BABYLON = {}));
  22543. var BABYLON;
  22544. (function (BABYLON) {
  22545. var PassPostProcess = (function (_super) {
  22546. __extends(PassPostProcess, _super);
  22547. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22548. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22549. }
  22550. return PassPostProcess;
  22551. })(BABYLON.PostProcess);
  22552. BABYLON.PassPostProcess = PassPostProcess;
  22553. })(BABYLON || (BABYLON = {}));
  22554. var BABYLON;
  22555. (function (BABYLON) {
  22556. var PhysicsEngine = (function () {
  22557. function PhysicsEngine(plugin) {
  22558. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22559. }
  22560. PhysicsEngine.prototype._initialize = function (gravity) {
  22561. this._currentPlugin.initialize();
  22562. this._setGravity(gravity);
  22563. };
  22564. PhysicsEngine.prototype._runOneStep = function (delta) {
  22565. if (delta > 0.1) {
  22566. delta = 0.1;
  22567. }
  22568. else if (delta <= 0) {
  22569. delta = 1.0 / 60.0;
  22570. }
  22571. this._currentPlugin.runOneStep(delta);
  22572. };
  22573. PhysicsEngine.prototype._setGravity = function (gravity) {
  22574. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22575. this._currentPlugin.setGravity(this.gravity);
  22576. };
  22577. PhysicsEngine.prototype._getGravity = function () {
  22578. return this._currentPlugin.getGravity();
  22579. };
  22580. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22581. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22582. };
  22583. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22584. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22585. };
  22586. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22587. this._currentPlugin.unregisterMesh(mesh);
  22588. };
  22589. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22590. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22591. };
  22592. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22593. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22594. };
  22595. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22596. this._currentPlugin.updateBodyPosition(mesh);
  22597. };
  22598. PhysicsEngine.prototype.dispose = function () {
  22599. this._currentPlugin.dispose();
  22600. };
  22601. PhysicsEngine.prototype.isSupported = function () {
  22602. return this._currentPlugin.isSupported();
  22603. };
  22604. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22605. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22606. };
  22607. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  22608. return this._currentPlugin.name;
  22609. };
  22610. // Statics
  22611. PhysicsEngine.NoImpostor = 0;
  22612. PhysicsEngine.SphereImpostor = 1;
  22613. PhysicsEngine.BoxImpostor = 2;
  22614. PhysicsEngine.PlaneImpostor = 3;
  22615. PhysicsEngine.MeshImpostor = 4;
  22616. PhysicsEngine.CapsuleImpostor = 5;
  22617. PhysicsEngine.ConeImpostor = 6;
  22618. PhysicsEngine.CylinderImpostor = 7;
  22619. PhysicsEngine.ConvexHullImpostor = 8;
  22620. PhysicsEngine.HeightmapImpostor = 9;
  22621. PhysicsEngine.Epsilon = 0.001;
  22622. return PhysicsEngine;
  22623. })();
  22624. BABYLON.PhysicsEngine = PhysicsEngine;
  22625. })(BABYLON || (BABYLON = {}));
  22626. var BABYLON;
  22627. (function (BABYLON) {
  22628. var VertexData = (function () {
  22629. function VertexData() {
  22630. }
  22631. VertexData.prototype.set = function (data, kind) {
  22632. switch (kind) {
  22633. case BABYLON.VertexBuffer.PositionKind:
  22634. this.positions = data;
  22635. break;
  22636. case BABYLON.VertexBuffer.NormalKind:
  22637. this.normals = data;
  22638. break;
  22639. case BABYLON.VertexBuffer.UVKind:
  22640. this.uvs = data;
  22641. break;
  22642. case BABYLON.VertexBuffer.UV2Kind:
  22643. this.uvs2 = data;
  22644. break;
  22645. case BABYLON.VertexBuffer.UV3Kind:
  22646. this.uvs3 = data;
  22647. break;
  22648. case BABYLON.VertexBuffer.UV4Kind:
  22649. this.uvs4 = data;
  22650. break;
  22651. case BABYLON.VertexBuffer.UV5Kind:
  22652. this.uvs5 = data;
  22653. break;
  22654. case BABYLON.VertexBuffer.UV6Kind:
  22655. this.uvs6 = data;
  22656. break;
  22657. case BABYLON.VertexBuffer.ColorKind:
  22658. this.colors = data;
  22659. break;
  22660. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22661. this.matricesIndices = data;
  22662. break;
  22663. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22664. this.matricesWeights = data;
  22665. break;
  22666. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22667. this.matricesIndicesExtra = data;
  22668. break;
  22669. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22670. this.matricesWeightsExtra = data;
  22671. break;
  22672. }
  22673. };
  22674. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22675. this._applyTo(mesh, updatable);
  22676. };
  22677. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22678. this._applyTo(geometry, updatable);
  22679. };
  22680. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22681. this._update(mesh);
  22682. };
  22683. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22684. this._update(geometry);
  22685. };
  22686. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22687. if (this.positions) {
  22688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22689. }
  22690. if (this.normals) {
  22691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22692. }
  22693. if (this.uvs) {
  22694. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22695. }
  22696. if (this.uvs2) {
  22697. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22698. }
  22699. if (this.uvs3) {
  22700. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22701. }
  22702. if (this.uvs4) {
  22703. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22704. }
  22705. if (this.uvs5) {
  22706. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22707. }
  22708. if (this.uvs6) {
  22709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22710. }
  22711. if (this.colors) {
  22712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22713. }
  22714. if (this.matricesIndices) {
  22715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22716. }
  22717. if (this.matricesWeights) {
  22718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22719. }
  22720. if (this.matricesIndicesExtra) {
  22721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  22722. }
  22723. if (this.matricesWeightsExtra) {
  22724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  22725. }
  22726. if (this.indices) {
  22727. meshOrGeometry.setIndices(this.indices);
  22728. }
  22729. };
  22730. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22731. if (this.positions) {
  22732. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22733. }
  22734. if (this.normals) {
  22735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22736. }
  22737. if (this.uvs) {
  22738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22739. }
  22740. if (this.uvs2) {
  22741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22742. }
  22743. if (this.uvs3) {
  22744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22745. }
  22746. if (this.uvs4) {
  22747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22748. }
  22749. if (this.uvs5) {
  22750. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22751. }
  22752. if (this.uvs6) {
  22753. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22754. }
  22755. if (this.colors) {
  22756. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22757. }
  22758. if (this.matricesIndices) {
  22759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22760. }
  22761. if (this.matricesWeights) {
  22762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22763. }
  22764. if (this.matricesIndicesExtra) {
  22765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  22766. }
  22767. if (this.matricesWeightsExtra) {
  22768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  22769. }
  22770. if (this.indices) {
  22771. meshOrGeometry.setIndices(this.indices);
  22772. }
  22773. };
  22774. VertexData.prototype.transform = function (matrix) {
  22775. var transformed = BABYLON.Vector3.Zero();
  22776. var index;
  22777. if (this.positions) {
  22778. var position = BABYLON.Vector3.Zero();
  22779. for (index = 0; index < this.positions.length; index += 3) {
  22780. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22781. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22782. this.positions[index] = transformed.x;
  22783. this.positions[index + 1] = transformed.y;
  22784. this.positions[index + 2] = transformed.z;
  22785. }
  22786. }
  22787. if (this.normals) {
  22788. var normal = BABYLON.Vector3.Zero();
  22789. for (index = 0; index < this.normals.length; index += 3) {
  22790. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22791. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22792. this.normals[index] = transformed.x;
  22793. this.normals[index + 1] = transformed.y;
  22794. this.normals[index + 2] = transformed.z;
  22795. }
  22796. }
  22797. };
  22798. VertexData.prototype.merge = function (other) {
  22799. var index;
  22800. if (other.indices) {
  22801. if (!this.indices) {
  22802. this.indices = [];
  22803. }
  22804. var offset = this.positions ? this.positions.length / 3 : 0;
  22805. for (index = 0; index < other.indices.length; index++) {
  22806. this.indices.push(other.indices[index] + offset);
  22807. }
  22808. }
  22809. if (other.positions) {
  22810. if (!this.positions) {
  22811. this.positions = [];
  22812. }
  22813. for (index = 0; index < other.positions.length; index++) {
  22814. this.positions.push(other.positions[index]);
  22815. }
  22816. }
  22817. if (other.normals) {
  22818. if (!this.normals) {
  22819. this.normals = [];
  22820. }
  22821. for (index = 0; index < other.normals.length; index++) {
  22822. this.normals.push(other.normals[index]);
  22823. }
  22824. }
  22825. if (other.uvs) {
  22826. if (!this.uvs) {
  22827. this.uvs = [];
  22828. }
  22829. for (index = 0; index < other.uvs.length; index++) {
  22830. this.uvs.push(other.uvs[index]);
  22831. }
  22832. }
  22833. if (other.uvs2) {
  22834. if (!this.uvs2) {
  22835. this.uvs2 = [];
  22836. }
  22837. for (index = 0; index < other.uvs2.length; index++) {
  22838. this.uvs2.push(other.uvs2[index]);
  22839. }
  22840. }
  22841. if (other.uvs3) {
  22842. if (!this.uvs3) {
  22843. this.uvs3 = [];
  22844. }
  22845. for (index = 0; index < other.uvs3.length; index++) {
  22846. this.uvs3.push(other.uvs3[index]);
  22847. }
  22848. }
  22849. if (other.uvs4) {
  22850. if (!this.uvs4) {
  22851. this.uvs4 = [];
  22852. }
  22853. for (index = 0; index < other.uvs4.length; index++) {
  22854. this.uvs4.push(other.uvs4[index]);
  22855. }
  22856. }
  22857. if (other.uvs5) {
  22858. if (!this.uvs5) {
  22859. this.uvs5 = [];
  22860. }
  22861. for (index = 0; index < other.uvs5.length; index++) {
  22862. this.uvs5.push(other.uvs5[index]);
  22863. }
  22864. }
  22865. if (other.uvs6) {
  22866. if (!this.uvs6) {
  22867. this.uvs6 = [];
  22868. }
  22869. for (index = 0; index < other.uvs6.length; index++) {
  22870. this.uvs6.push(other.uvs6[index]);
  22871. }
  22872. }
  22873. if (other.matricesIndices) {
  22874. if (!this.matricesIndices) {
  22875. this.matricesIndices = [];
  22876. }
  22877. for (index = 0; index < other.matricesIndices.length; index++) {
  22878. this.matricesIndices.push(other.matricesIndices[index]);
  22879. }
  22880. }
  22881. if (other.matricesWeights) {
  22882. if (!this.matricesWeights) {
  22883. this.matricesWeights = [];
  22884. }
  22885. for (index = 0; index < other.matricesWeights.length; index++) {
  22886. this.matricesWeights.push(other.matricesWeights[index]);
  22887. }
  22888. }
  22889. if (other.matricesIndicesExtra) {
  22890. if (!this.matricesIndicesExtra) {
  22891. this.matricesIndicesExtra = [];
  22892. }
  22893. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  22894. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  22895. }
  22896. }
  22897. if (other.matricesWeightsExtra) {
  22898. if (!this.matricesWeightsExtra) {
  22899. this.matricesWeightsExtra = [];
  22900. }
  22901. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  22902. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  22903. }
  22904. }
  22905. if (other.colors) {
  22906. if (!this.colors) {
  22907. this.colors = [];
  22908. }
  22909. for (index = 0; index < other.colors.length; index++) {
  22910. this.colors.push(other.colors[index]);
  22911. }
  22912. }
  22913. };
  22914. // Statics
  22915. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22916. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22917. };
  22918. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22919. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22920. };
  22921. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22922. var result = new VertexData();
  22923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22924. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22925. }
  22926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22927. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22928. }
  22929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22930. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22931. }
  22932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22933. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22934. }
  22935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22936. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22937. }
  22938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22939. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22940. }
  22941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22942. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22943. }
  22944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22945. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22946. }
  22947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22948. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22949. }
  22950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22951. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22952. }
  22953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22954. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22955. }
  22956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  22957. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  22958. }
  22959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  22960. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  22961. }
  22962. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22963. return result;
  22964. };
  22965. VertexData.CreateRibbon = function (options) {
  22966. var pathArray = options.pathArray;
  22967. var closeArray = options.closeArray || false;
  22968. var closePath = options.closePath || false;
  22969. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22970. var offset = options.offset || defaultOffset;
  22971. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22972. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22973. var positions = [];
  22974. var indices = [];
  22975. var normals = [];
  22976. var uvs = [];
  22977. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22978. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22979. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22980. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22981. var minlg; // minimal length among all paths from pathArray
  22982. var lg = []; // array of path lengths : nb of vertex per path
  22983. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22984. var p; // path iterator
  22985. var i; // point iterator
  22986. var j; // point iterator
  22987. // if single path in pathArray
  22988. if (pathArray.length < 2) {
  22989. var ar1 = [];
  22990. var ar2 = [];
  22991. for (i = 0; i < pathArray[0].length - offset; i++) {
  22992. ar1.push(pathArray[0][i]);
  22993. ar2.push(pathArray[0][i + offset]);
  22994. }
  22995. pathArray = [ar1, ar2];
  22996. }
  22997. // positions and horizontal distances (u)
  22998. var idc = 0;
  22999. var closePathCorr = (closePath) ? 1 : 0;
  23000. var path;
  23001. var l;
  23002. minlg = pathArray[0].length;
  23003. var vectlg;
  23004. var dist;
  23005. for (p = 0; p < pathArray.length; p++) {
  23006. uTotalDistance[p] = 0;
  23007. us[p] = [0];
  23008. path = pathArray[p];
  23009. l = path.length;
  23010. minlg = (minlg < l) ? minlg : l;
  23011. j = 0;
  23012. while (j < l) {
  23013. positions.push(path[j].x, path[j].y, path[j].z);
  23014. if (j > 0) {
  23015. vectlg = path[j].subtract(path[j - 1]).length();
  23016. dist = vectlg + uTotalDistance[p];
  23017. us[p].push(dist);
  23018. uTotalDistance[p] = dist;
  23019. }
  23020. j++;
  23021. }
  23022. if (closePath) {
  23023. j--;
  23024. positions.push(path[0].x, path[0].y, path[0].z);
  23025. vectlg = path[j].subtract(path[0]).length();
  23026. dist = vectlg + uTotalDistance[p];
  23027. us[p].push(dist);
  23028. uTotalDistance[p] = dist;
  23029. }
  23030. lg[p] = l + closePathCorr;
  23031. idx[p] = idc;
  23032. idc += (l + closePathCorr);
  23033. }
  23034. // vertical distances (v)
  23035. var path1;
  23036. var path2;
  23037. var vertex1;
  23038. var vertex2;
  23039. for (i = 0; i < minlg + closePathCorr; i++) {
  23040. vTotalDistance[i] = 0;
  23041. vs[i] = [0];
  23042. for (p = 0; p < pathArray.length - 1; p++) {
  23043. path1 = pathArray[p];
  23044. path2 = pathArray[p + 1];
  23045. if (i === minlg) {
  23046. vertex1 = path1[0];
  23047. vertex2 = path2[0];
  23048. }
  23049. else {
  23050. vertex1 = path1[i];
  23051. vertex2 = path2[i];
  23052. }
  23053. vectlg = vertex2.subtract(vertex1).length();
  23054. dist = vectlg + vTotalDistance[i];
  23055. vs[i].push(dist);
  23056. vTotalDistance[i] = dist;
  23057. }
  23058. if (closeArray) {
  23059. path1 = pathArray[p];
  23060. path2 = pathArray[0];
  23061. if (i === minlg) {
  23062. vertex2 = path2[0];
  23063. }
  23064. vectlg = vertex2.subtract(vertex1).length();
  23065. dist = vectlg + vTotalDistance[i];
  23066. vTotalDistance[i] = dist;
  23067. }
  23068. }
  23069. // uvs
  23070. var u;
  23071. var v;
  23072. for (p = 0; p < pathArray.length; p++) {
  23073. for (i = 0; i < minlg + closePathCorr; i++) {
  23074. u = us[p][i] / uTotalDistance[p];
  23075. v = vs[i][p] / vTotalDistance[i];
  23076. uvs.push(u, v);
  23077. }
  23078. }
  23079. // indices
  23080. p = 0; // path index
  23081. var pi = 0; // positions array index
  23082. var l1 = lg[p] - 1; // path1 length
  23083. var l2 = lg[p + 1] - 1; // path2 length
  23084. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23085. var shft = idx[1] - idx[0]; // shift
  23086. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23087. while (pi <= min && p < path1nb) {
  23088. // 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
  23089. indices.push(pi, pi + shft, pi + 1);
  23090. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23091. pi += 1;
  23092. if (pi === min) {
  23093. p++;
  23094. if (p === lg.length - 1) {
  23095. shft = idx[0] - idx[p];
  23096. l1 = lg[p] - 1;
  23097. l2 = lg[0] - 1;
  23098. }
  23099. else {
  23100. shft = idx[p + 1] - idx[p];
  23101. l1 = lg[p] - 1;
  23102. l2 = lg[p + 1] - 1;
  23103. }
  23104. pi = idx[p];
  23105. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23106. }
  23107. }
  23108. // normals
  23109. VertexData.ComputeNormals(positions, indices, normals);
  23110. if (closePath) {
  23111. var indexFirst = 0;
  23112. var indexLast = 0;
  23113. for (p = 0; p < pathArray.length; p++) {
  23114. indexFirst = idx[p] * 3;
  23115. if (p + 1 < pathArray.length) {
  23116. indexLast = (idx[p + 1] - 1) * 3;
  23117. }
  23118. else {
  23119. indexLast = normals.length - 3;
  23120. }
  23121. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23122. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23123. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23124. normals[indexLast] = normals[indexFirst];
  23125. normals[indexLast + 1] = normals[indexFirst + 1];
  23126. normals[indexLast + 2] = normals[indexFirst + 2];
  23127. }
  23128. }
  23129. // sides
  23130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23131. // Result
  23132. var vertexData = new VertexData();
  23133. vertexData.indices = indices;
  23134. vertexData.positions = positions;
  23135. vertexData.normals = normals;
  23136. vertexData.uvs = uvs;
  23137. if (closePath) {
  23138. vertexData._idx = idx;
  23139. }
  23140. return vertexData;
  23141. };
  23142. VertexData.CreateBox = function (options) {
  23143. var normalsSource = [
  23144. new BABYLON.Vector3(0, 0, 1),
  23145. new BABYLON.Vector3(0, 0, -1),
  23146. new BABYLON.Vector3(1, 0, 0),
  23147. new BABYLON.Vector3(-1, 0, 0),
  23148. new BABYLON.Vector3(0, 1, 0),
  23149. new BABYLON.Vector3(0, -1, 0)
  23150. ];
  23151. var indices = [];
  23152. var positions = [];
  23153. var normals = [];
  23154. var uvs = [];
  23155. var width = options.width || options.size || 1;
  23156. var height = options.height || options.size || 1;
  23157. var depth = options.depth || options.size || 1;
  23158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23159. var faceUV = options.faceUV || new Array(6);
  23160. var faceColors = options.faceColors;
  23161. var colors = [];
  23162. // default face colors and UV if undefined
  23163. for (var f = 0; f < 6; f++) {
  23164. if (faceUV[f] === undefined) {
  23165. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23166. }
  23167. if (faceColors && faceColors[f] === undefined) {
  23168. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23169. }
  23170. }
  23171. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23172. // Create each face in turn.
  23173. for (var index = 0; index < normalsSource.length; index++) {
  23174. var normal = normalsSource[index];
  23175. // Get two vectors perpendicular to the face normal and to each other.
  23176. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23177. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23178. // Six indices (two triangles) per face.
  23179. var verticesLength = positions.length / 3;
  23180. indices.push(verticesLength);
  23181. indices.push(verticesLength + 1);
  23182. indices.push(verticesLength + 2);
  23183. indices.push(verticesLength);
  23184. indices.push(verticesLength + 2);
  23185. indices.push(verticesLength + 3);
  23186. // Four vertices per face.
  23187. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23188. positions.push(vertex.x, vertex.y, vertex.z);
  23189. normals.push(normal.x, normal.y, normal.z);
  23190. uvs.push(faceUV[index].z, faceUV[index].w);
  23191. if (faceColors) {
  23192. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23193. }
  23194. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23195. positions.push(vertex.x, vertex.y, vertex.z);
  23196. normals.push(normal.x, normal.y, normal.z);
  23197. uvs.push(faceUV[index].x, faceUV[index].w);
  23198. if (faceColors) {
  23199. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23200. }
  23201. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23202. positions.push(vertex.x, vertex.y, vertex.z);
  23203. normals.push(normal.x, normal.y, normal.z);
  23204. uvs.push(faceUV[index].x, faceUV[index].y);
  23205. if (faceColors) {
  23206. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23207. }
  23208. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23209. positions.push(vertex.x, vertex.y, vertex.z);
  23210. normals.push(normal.x, normal.y, normal.z);
  23211. uvs.push(faceUV[index].z, faceUV[index].y);
  23212. if (faceColors) {
  23213. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23214. }
  23215. }
  23216. // sides
  23217. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23218. // Result
  23219. var vertexData = new VertexData();
  23220. vertexData.indices = indices;
  23221. vertexData.positions = positions;
  23222. vertexData.normals = normals;
  23223. vertexData.uvs = uvs;
  23224. if (faceColors) {
  23225. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23226. vertexData.colors = totalColors;
  23227. }
  23228. return vertexData;
  23229. };
  23230. VertexData.CreateSphere = function (options) {
  23231. var segments = options.segments || 32;
  23232. var diameterX = options.diameterX || options.diameter || 1;
  23233. var diameterY = options.diameterY || options.diameter || 1;
  23234. var diameterZ = options.diameterZ || options.diameter || 1;
  23235. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23236. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23238. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23239. var totalZRotationSteps = 2 + segments;
  23240. var totalYRotationSteps = 2 * totalZRotationSteps;
  23241. var indices = [];
  23242. var positions = [];
  23243. var normals = [];
  23244. var uvs = [];
  23245. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23246. var normalizedZ = zRotationStep / totalZRotationSteps;
  23247. var angleZ = normalizedZ * Math.PI * slice;
  23248. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23249. var normalizedY = yRotationStep / totalYRotationSteps;
  23250. var angleY = normalizedY * Math.PI * 2 * arc;
  23251. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23252. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23253. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23254. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23255. var vertex = complete.multiply(radius);
  23256. var normal = complete.divide(radius).normalize();
  23257. positions.push(vertex.x, vertex.y, vertex.z);
  23258. normals.push(normal.x, normal.y, normal.z);
  23259. uvs.push(normalizedY, normalizedZ);
  23260. }
  23261. if (zRotationStep > 0) {
  23262. var verticesCount = positions.length / 3;
  23263. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23264. indices.push((firstIndex));
  23265. indices.push((firstIndex + 1));
  23266. indices.push(firstIndex + totalYRotationSteps + 1);
  23267. indices.push((firstIndex + totalYRotationSteps + 1));
  23268. indices.push((firstIndex + 1));
  23269. indices.push((firstIndex + totalYRotationSteps + 2));
  23270. }
  23271. }
  23272. }
  23273. // Sides
  23274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23275. // Result
  23276. var vertexData = new VertexData();
  23277. vertexData.indices = indices;
  23278. vertexData.positions = positions;
  23279. vertexData.normals = normals;
  23280. vertexData.uvs = uvs;
  23281. return vertexData;
  23282. };
  23283. // Cylinder and cone
  23284. VertexData.CreateCylinder = function (options) {
  23285. var height = options.height || 2;
  23286. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23287. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23288. var tessellation = options.tessellation || 24;
  23289. var subdivisions = options.subdivisions || 1;
  23290. var hasRings = options.hasRings;
  23291. var enclose = options.enclose;
  23292. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23293. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23294. var faceUV = options.faceUV || new Array(3);
  23295. var faceColors = options.faceColors;
  23296. // default face colors and UV if undefined
  23297. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23298. var ringNb = (hasRings) ? subdivisions : 1;
  23299. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23300. var f;
  23301. for (f = 0; f < surfaceNb; f++) {
  23302. if (faceColors && faceColors[f] === undefined) {
  23303. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23304. }
  23305. }
  23306. for (f = 0; f < surfaceNb; f++) {
  23307. if (faceUV && faceUV[f] === undefined) {
  23308. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23309. }
  23310. }
  23311. var indices = [];
  23312. var positions = [];
  23313. var normals = [];
  23314. var uvs = [];
  23315. var colors = [];
  23316. var angle_step = Math.PI * 2 * arc / tessellation;
  23317. var angle;
  23318. var h;
  23319. var radius;
  23320. var tan = (diameterBottom - diameterTop) / 2 / height;
  23321. var ringVertex = BABYLON.Vector3.Zero();
  23322. var ringNormal = BABYLON.Vector3.Zero();
  23323. var ringFirstVertex = BABYLON.Vector3.Zero();
  23324. var ringFirstNormal = BABYLON.Vector3.Zero();
  23325. var quadNormal = BABYLON.Vector3.Zero();
  23326. var Y = BABYLON.Axis.Y;
  23327. // positions, normals, uvs
  23328. var i;
  23329. var j;
  23330. var r;
  23331. var ringIdx = 1;
  23332. var s = 1; // surface index
  23333. var cs = 0;
  23334. var v = 0;
  23335. for (i = 0; i <= subdivisions; i++) {
  23336. h = i / subdivisions;
  23337. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23338. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23339. for (r = 0; r < ringIdx; r++) {
  23340. if (hasRings) {
  23341. s += r;
  23342. }
  23343. if (enclose) {
  23344. s += 2 * r;
  23345. }
  23346. for (j = 0; j <= tessellation; j++) {
  23347. angle = j * angle_step;
  23348. // position
  23349. ringVertex.x = Math.cos(-angle) * radius;
  23350. ringVertex.y = -height / 2 + h * height;
  23351. ringVertex.z = Math.sin(-angle) * radius;
  23352. // normal
  23353. if (diameterTop === 0 && i === subdivisions) {
  23354. // if no top cap, reuse former normals
  23355. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23356. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23357. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23358. }
  23359. else {
  23360. ringNormal.x = ringVertex.x;
  23361. ringNormal.z = ringVertex.z;
  23362. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23363. ringNormal.normalize();
  23364. }
  23365. // keep first ring vertex values for enclose
  23366. if (j === 0) {
  23367. ringFirstVertex.copyFrom(ringVertex);
  23368. ringFirstNormal.copyFrom(ringNormal);
  23369. }
  23370. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23371. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23372. if (hasRings) {
  23373. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23374. }
  23375. else {
  23376. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23377. }
  23378. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23379. if (faceColors) {
  23380. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23381. }
  23382. }
  23383. // if enclose, add four vertices and their dedicated normals
  23384. if (arc !== 1 && enclose) {
  23385. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23386. positions.push(0, ringVertex.y, 0);
  23387. positions.push(0, ringVertex.y, 0);
  23388. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23389. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23390. quadNormal.normalize();
  23391. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23392. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23393. quadNormal.normalize();
  23394. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23395. if (hasRings) {
  23396. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23397. }
  23398. else {
  23399. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23400. }
  23401. uvs.push(faceUV[s + 1].x, v);
  23402. uvs.push(faceUV[s + 1].z, v);
  23403. if (hasRings) {
  23404. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23405. }
  23406. else {
  23407. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23408. }
  23409. uvs.push(faceUV[s + 2].x, v);
  23410. uvs.push(faceUV[s + 2].z, v);
  23411. if (faceColors) {
  23412. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23413. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23414. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23415. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23416. }
  23417. }
  23418. if (cs !== s) {
  23419. cs = s;
  23420. }
  23421. }
  23422. }
  23423. // indices
  23424. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23425. var s;
  23426. i = 0;
  23427. for (s = 0; s < subdivisions; s++) {
  23428. for (j = 0; j < tessellation; j++) {
  23429. var i0 = i * (e + 1) + j;
  23430. var i1 = (i + 1) * (e + 1) + j;
  23431. var i2 = i * (e + 1) + (j + 1);
  23432. var i3 = (i + 1) * (e + 1) + (j + 1);
  23433. indices.push(i0, i1, i2);
  23434. indices.push(i3, i2, i1);
  23435. }
  23436. if (arc !== 1 && enclose) {
  23437. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23438. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23439. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23440. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23441. }
  23442. i = (hasRings) ? (i + 2) : (i + 1);
  23443. }
  23444. // Caps
  23445. var createCylinderCap = function (isTop) {
  23446. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23447. if (radius === 0) {
  23448. return;
  23449. }
  23450. // Cap positions, normals & uvs
  23451. var angle;
  23452. var circleVector;
  23453. var i;
  23454. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23455. var c;
  23456. if (faceColors) {
  23457. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23458. }
  23459. // cap center
  23460. var vbase = positions.length / 3;
  23461. var offset = isTop ? height / 2 : -height / 2;
  23462. var center = new BABYLON.Vector3(0, offset, 0);
  23463. positions.push(center.x, center.y, center.z);
  23464. normals.push(0, isTop ? 1 : -1, 0);
  23465. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23466. if (faceColors) {
  23467. colors.push(c.r, c.g, c.b, c.a);
  23468. }
  23469. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23470. for (i = 0; i <= tessellation; i++) {
  23471. angle = Math.PI * 2 * i * arc / tessellation;
  23472. var cos = Math.cos(-angle);
  23473. var sin = Math.sin(-angle);
  23474. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23475. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23476. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23477. normals.push(0, isTop ? 1 : -1, 0);
  23478. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23479. if (faceColors) {
  23480. colors.push(c.r, c.g, c.b, c.a);
  23481. }
  23482. }
  23483. // Cap indices
  23484. for (i = 0; i < tessellation; i++) {
  23485. if (!isTop) {
  23486. indices.push(vbase);
  23487. indices.push(vbase + (i + 1));
  23488. indices.push(vbase + (i + 2));
  23489. }
  23490. else {
  23491. indices.push(vbase);
  23492. indices.push(vbase + (i + 2));
  23493. indices.push(vbase + (i + 1));
  23494. }
  23495. }
  23496. };
  23497. // add caps to geometry
  23498. createCylinderCap(false);
  23499. createCylinderCap(true);
  23500. // Sides
  23501. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23502. var vertexData = new VertexData();
  23503. vertexData.indices = indices;
  23504. vertexData.positions = positions;
  23505. vertexData.normals = normals;
  23506. vertexData.uvs = uvs;
  23507. if (faceColors) {
  23508. vertexData.colors = colors;
  23509. }
  23510. return vertexData;
  23511. };
  23512. VertexData.CreateTorus = function (options) {
  23513. var indices = [];
  23514. var positions = [];
  23515. var normals = [];
  23516. var uvs = [];
  23517. var diameter = options.diameter || 1;
  23518. var thickness = options.thickness || 0.5;
  23519. var tessellation = options.tessellation || 16;
  23520. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23521. var stride = tessellation + 1;
  23522. for (var i = 0; i <= tessellation; i++) {
  23523. var u = i / tessellation;
  23524. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23525. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23526. for (var j = 0; j <= tessellation; j++) {
  23527. var v = 1 - j / tessellation;
  23528. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23529. var dx = Math.cos(innerAngle);
  23530. var dy = Math.sin(innerAngle);
  23531. // Create a vertex.
  23532. var normal = new BABYLON.Vector3(dx, dy, 0);
  23533. var position = normal.scale(thickness / 2);
  23534. var textureCoordinate = new BABYLON.Vector2(u, v);
  23535. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23536. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23537. positions.push(position.x, position.y, position.z);
  23538. normals.push(normal.x, normal.y, normal.z);
  23539. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23540. // And create indices for two triangles.
  23541. var nextI = (i + 1) % stride;
  23542. var nextJ = (j + 1) % stride;
  23543. indices.push(i * stride + j);
  23544. indices.push(i * stride + nextJ);
  23545. indices.push(nextI * stride + j);
  23546. indices.push(i * stride + nextJ);
  23547. indices.push(nextI * stride + nextJ);
  23548. indices.push(nextI * stride + j);
  23549. }
  23550. }
  23551. // Sides
  23552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23553. // Result
  23554. var vertexData = new VertexData();
  23555. vertexData.indices = indices;
  23556. vertexData.positions = positions;
  23557. vertexData.normals = normals;
  23558. vertexData.uvs = uvs;
  23559. return vertexData;
  23560. };
  23561. VertexData.CreateLines = function (options) {
  23562. var indices = [];
  23563. var positions = [];
  23564. var points = options.points;
  23565. for (var index = 0; index < points.length; index++) {
  23566. positions.push(points[index].x, points[index].y, points[index].z);
  23567. if (index > 0) {
  23568. indices.push(index - 1);
  23569. indices.push(index);
  23570. }
  23571. }
  23572. // Result
  23573. var vertexData = new VertexData();
  23574. vertexData.indices = indices;
  23575. vertexData.positions = positions;
  23576. return vertexData;
  23577. };
  23578. VertexData.CreateDashedLines = function (options) {
  23579. var dashSize = options.dashSize || 3;
  23580. var gapSize = options.gapSize || 1;
  23581. var dashNb = options.dashNb || 200;
  23582. var points = options.points;
  23583. var positions = new Array();
  23584. var indices = new Array();
  23585. var curvect = BABYLON.Vector3.Zero();
  23586. var lg = 0;
  23587. var nb = 0;
  23588. var shft = 0;
  23589. var dashshft = 0;
  23590. var curshft = 0;
  23591. var idx = 0;
  23592. var i = 0;
  23593. for (i = 0; i < points.length - 1; i++) {
  23594. points[i + 1].subtractToRef(points[i], curvect);
  23595. lg += curvect.length();
  23596. }
  23597. shft = lg / dashNb;
  23598. dashshft = dashSize * shft / (dashSize + gapSize);
  23599. for (i = 0; i < points.length - 1; i++) {
  23600. points[i + 1].subtractToRef(points[i], curvect);
  23601. nb = Math.floor(curvect.length() / shft);
  23602. curvect.normalize();
  23603. for (var j = 0; j < nb; j++) {
  23604. curshft = shft * j;
  23605. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23606. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23607. indices.push(idx, idx + 1);
  23608. idx += 2;
  23609. }
  23610. }
  23611. // Result
  23612. var vertexData = new VertexData();
  23613. vertexData.positions = positions;
  23614. vertexData.indices = indices;
  23615. return vertexData;
  23616. };
  23617. VertexData.CreateGround = function (options) {
  23618. var indices = [];
  23619. var positions = [];
  23620. var normals = [];
  23621. var uvs = [];
  23622. var row, col;
  23623. var width = options.width || 1;
  23624. var height = options.height || 1;
  23625. var subdivisions = options.subdivisions || 1;
  23626. for (row = 0; row <= subdivisions; row++) {
  23627. for (col = 0; col <= subdivisions; col++) {
  23628. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23629. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23630. positions.push(position.x, position.y, position.z);
  23631. normals.push(normal.x, normal.y, normal.z);
  23632. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23633. }
  23634. }
  23635. for (row = 0; row < subdivisions; row++) {
  23636. for (col = 0; col < subdivisions; col++) {
  23637. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23638. indices.push(col + 1 + row * (subdivisions + 1));
  23639. indices.push(col + row * (subdivisions + 1));
  23640. indices.push(col + (row + 1) * (subdivisions + 1));
  23641. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23642. indices.push(col + row * (subdivisions + 1));
  23643. }
  23644. }
  23645. // Result
  23646. var vertexData = new VertexData();
  23647. vertexData.indices = indices;
  23648. vertexData.positions = positions;
  23649. vertexData.normals = normals;
  23650. vertexData.uvs = uvs;
  23651. return vertexData;
  23652. };
  23653. VertexData.CreateTiledGround = function (options) {
  23654. var xmin = options.xmin;
  23655. var zmin = options.zmin;
  23656. var xmax = options.xmax;
  23657. var zmax = options.zmax;
  23658. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23659. var precision = options.precision || { w: 1, h: 1 };
  23660. var indices = [];
  23661. var positions = [];
  23662. var normals = [];
  23663. var uvs = [];
  23664. var row, col, tileRow, tileCol;
  23665. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23666. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23667. precision.w = (precision.w < 1) ? 1 : precision.w;
  23668. precision.h = (precision.h < 1) ? 1 : precision.h;
  23669. var tileSize = {
  23670. 'w': (xmax - xmin) / subdivisions.w,
  23671. 'h': (zmax - zmin) / subdivisions.h
  23672. };
  23673. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23674. // Indices
  23675. var base = positions.length / 3;
  23676. var rowLength = precision.w + 1;
  23677. for (row = 0; row < precision.h; row++) {
  23678. for (col = 0; col < precision.w; col++) {
  23679. var square = [
  23680. base + col + row * rowLength,
  23681. base + (col + 1) + row * rowLength,
  23682. base + (col + 1) + (row + 1) * rowLength,
  23683. base + col + (row + 1) * rowLength
  23684. ];
  23685. indices.push(square[1]);
  23686. indices.push(square[2]);
  23687. indices.push(square[3]);
  23688. indices.push(square[0]);
  23689. indices.push(square[1]);
  23690. indices.push(square[3]);
  23691. }
  23692. }
  23693. // Position, normals and uvs
  23694. var position = BABYLON.Vector3.Zero();
  23695. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23696. for (row = 0; row <= precision.h; row++) {
  23697. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23698. for (col = 0; col <= precision.w; col++) {
  23699. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23700. position.y = 0;
  23701. positions.push(position.x, position.y, position.z);
  23702. normals.push(normal.x, normal.y, normal.z);
  23703. uvs.push(col / precision.w, row / precision.h);
  23704. }
  23705. }
  23706. }
  23707. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23708. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23709. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23710. }
  23711. }
  23712. // Result
  23713. var vertexData = new VertexData();
  23714. vertexData.indices = indices;
  23715. vertexData.positions = positions;
  23716. vertexData.normals = normals;
  23717. vertexData.uvs = uvs;
  23718. return vertexData;
  23719. };
  23720. VertexData.CreateGroundFromHeightMap = function (options) {
  23721. var indices = [];
  23722. var positions = [];
  23723. var normals = [];
  23724. var uvs = [];
  23725. var row, col;
  23726. // Vertices
  23727. for (row = 0; row <= options.subdivisions; row++) {
  23728. for (col = 0; col <= options.subdivisions; col++) {
  23729. 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));
  23730. // Compute height
  23731. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23732. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23733. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23734. var r = options.buffer[pos] / 255.0;
  23735. var g = options.buffer[pos + 1] / 255.0;
  23736. var b = options.buffer[pos + 2] / 255.0;
  23737. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23738. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23739. // Add vertex
  23740. positions.push(position.x, position.y, position.z);
  23741. normals.push(0, 0, 0);
  23742. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23743. }
  23744. }
  23745. // Indices
  23746. for (row = 0; row < options.subdivisions; row++) {
  23747. for (col = 0; col < options.subdivisions; col++) {
  23748. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23749. indices.push(col + 1 + row * (options.subdivisions + 1));
  23750. indices.push(col + row * (options.subdivisions + 1));
  23751. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23752. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23753. indices.push(col + row * (options.subdivisions + 1));
  23754. }
  23755. }
  23756. // Normals
  23757. VertexData.ComputeNormals(positions, indices, normals);
  23758. // Result
  23759. var vertexData = new VertexData();
  23760. vertexData.indices = indices;
  23761. vertexData.positions = positions;
  23762. vertexData.normals = normals;
  23763. vertexData.uvs = uvs;
  23764. return vertexData;
  23765. };
  23766. VertexData.CreatePlane = function (options) {
  23767. var indices = [];
  23768. var positions = [];
  23769. var normals = [];
  23770. var uvs = [];
  23771. var width = options.width || options.size || 1;
  23772. var height = options.height || options.size || 1;
  23773. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23774. // Vertices
  23775. var halfWidth = width / 2.0;
  23776. var halfHeight = height / 2.0;
  23777. positions.push(-halfWidth, -halfHeight, 0);
  23778. normals.push(0, 0, -1.0);
  23779. uvs.push(0.0, 0.0);
  23780. positions.push(halfWidth, -halfHeight, 0);
  23781. normals.push(0, 0, -1.0);
  23782. uvs.push(1.0, 0.0);
  23783. positions.push(halfWidth, halfHeight, 0);
  23784. normals.push(0, 0, -1.0);
  23785. uvs.push(1.0, 1.0);
  23786. positions.push(-halfWidth, halfHeight, 0);
  23787. normals.push(0, 0, -1.0);
  23788. uvs.push(0.0, 1.0);
  23789. // Indices
  23790. indices.push(0);
  23791. indices.push(1);
  23792. indices.push(2);
  23793. indices.push(0);
  23794. indices.push(2);
  23795. indices.push(3);
  23796. // Sides
  23797. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23798. // Result
  23799. var vertexData = new VertexData();
  23800. vertexData.indices = indices;
  23801. vertexData.positions = positions;
  23802. vertexData.normals = normals;
  23803. vertexData.uvs = uvs;
  23804. return vertexData;
  23805. };
  23806. VertexData.CreateDisc = function (options) {
  23807. var positions = [];
  23808. var indices = [];
  23809. var normals = [];
  23810. var uvs = [];
  23811. var radius = options.radius || 0.5;
  23812. var tessellation = options.tessellation || 64;
  23813. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23815. // positions and uvs
  23816. positions.push(0, 0, 0); // disc center first
  23817. uvs.push(0.5, 0.5);
  23818. var theta = Math.PI * 2 * arc;
  23819. var step = theta / tessellation;
  23820. for (var a = 0; a < theta; a += step) {
  23821. var x = Math.cos(a);
  23822. var y = Math.sin(a);
  23823. var u = (x + 1) / 2;
  23824. var v = (1 - y) / 2;
  23825. positions.push(radius * x, radius * y, 0);
  23826. uvs.push(u, v);
  23827. }
  23828. if (arc === 1) {
  23829. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23830. uvs.push(uvs[2], uvs[3]);
  23831. }
  23832. //indices
  23833. var vertexNb = positions.length / 3;
  23834. for (var i = 1; i < vertexNb - 1; i++) {
  23835. indices.push(i + 1, 0, i);
  23836. }
  23837. // result
  23838. VertexData.ComputeNormals(positions, indices, normals);
  23839. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23840. var vertexData = new VertexData();
  23841. vertexData.indices = indices;
  23842. vertexData.positions = positions;
  23843. vertexData.normals = normals;
  23844. vertexData.uvs = uvs;
  23845. return vertexData;
  23846. };
  23847. VertexData.CreateIcoSphere = function (options) {
  23848. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23849. var radius = options.radius || 1;
  23850. var flat = (options.flat === undefined) ? true : options.flat;
  23851. var subdivisions = options.subdivisions || 4;
  23852. var radiusX = options.radiusX || radius;
  23853. var radiusY = options.radiusY || radius;
  23854. var radiusZ = options.radiusZ || radius;
  23855. var t = (1 + Math.sqrt(5)) / 2;
  23856. // 12 vertex x,y,z
  23857. var ico_vertices = [
  23858. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  23859. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  23860. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  23861. ];
  23862. // index of 3 vertex makes a face of icopshere
  23863. var ico_indices = [
  23864. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  23865. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  23866. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  23867. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  23868. ];
  23869. // vertex for uv have aliased position, not for UV
  23870. var vertices_unalias_id = [
  23871. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  23872. // vertex alias
  23873. 0,
  23874. 2,
  23875. 3,
  23876. 3,
  23877. 3,
  23878. 4,
  23879. 7,
  23880. 8,
  23881. 9,
  23882. 9,
  23883. 10,
  23884. 11 // 23: B + 12
  23885. ];
  23886. // uv as integer step (not pixels !)
  23887. var ico_vertexuv = [
  23888. 5, 1, 3, 1, 6, 4, 0, 0,
  23889. 5, 3, 4, 2, 2, 2, 4, 0,
  23890. 2, 0, 1, 1, 6, 0, 6, 2,
  23891. // vertex alias (for same vertex on different faces)
  23892. 0, 4,
  23893. 3, 3,
  23894. 4, 4,
  23895. 3, 1,
  23896. 4, 2,
  23897. 4, 4,
  23898. 0, 2,
  23899. 1, 1,
  23900. 2, 2,
  23901. 3, 3,
  23902. 1, 3,
  23903. 2, 4 // 23: B + 12
  23904. ];
  23905. // Vertices[0, 1, ...9, A, B] : position on UV plane
  23906. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  23907. // First island of uv mapping
  23908. // v = 4h 3+ 2
  23909. // v = 3h 9+ 4
  23910. // v = 2h 9+ 5 B
  23911. // v = 1h 9 1 0
  23912. // v = 0h 3 8 7 A
  23913. // u = 0 1 2 3 4 5 6 *a
  23914. // Second island of uv mapping
  23915. // v = 4h 0+ B+ 4+
  23916. // v = 3h A+ 2+
  23917. // v = 2h 7+ 6 3+
  23918. // v = 1h 8+ 3+
  23919. // v = 0h
  23920. // u = 0 1 2 3 4 5 6 *a
  23921. // Face layout on texture UV mapping
  23922. // ============
  23923. // \ 4 /\ 16 / ======
  23924. // \ / \ / /\ 11 /
  23925. // \/ 7 \/ / \ /
  23926. // ======= / 10 \/
  23927. // /\ 17 /\ =======
  23928. // / \ / \ \ 15 /\
  23929. // / 8 \/ 12 \ \ / \
  23930. // ============ \/ 6 \
  23931. // \ 18 /\ ============
  23932. // \ / \ \ 5 /\ 0 /
  23933. // \/ 13 \ \ / \ /
  23934. // ======= \/ 1 \/
  23935. // =============
  23936. // /\ 19 /\ 2 /\
  23937. // / \ / \ / \
  23938. // / 14 \/ 9 \/ 3 \
  23939. // ===================
  23940. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  23941. var ustep = 138 / 1024;
  23942. var vstep = 239 / 1024;
  23943. var uoffset = 60 / 1024;
  23944. var voffset = 26 / 1024;
  23945. // Second island should have margin, not to touch the first island
  23946. // avoid any borderline artefact in pixel rounding
  23947. var island_u_offset = -40 / 1024;
  23948. var island_v_offset = +20 / 1024;
  23949. // face is either island 0 or 1 :
  23950. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  23951. var island = [
  23952. 0, 0, 0, 0, 1,
  23953. 0, 0, 1, 1, 0,
  23954. 0, 0, 1, 1, 0,
  23955. 0, 1, 1, 1, 0 // 15 - 19
  23956. ];
  23957. var indices = [];
  23958. var positions = [];
  23959. var normals = [];
  23960. var uvs = [];
  23961. var current_indice = 0;
  23962. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  23963. var face_vertex_pos = new Array(3);
  23964. var face_vertex_uv = new Array(3);
  23965. var v012;
  23966. for (v012 = 0; v012 < 3; v012++) {
  23967. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  23968. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  23969. }
  23970. // create all with normals
  23971. for (var face = 0; face < 20; face++) {
  23972. // 3 vertex per face
  23973. for (v012 = 0; v012 < 3; v012++) {
  23974. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  23975. var v_id = ico_indices[3 * face + v012];
  23976. // vertex have 3D position (x,y,z)
  23977. 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]);
  23978. // Normalize to get normal, then scale to radius
  23979. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  23980. // uv Coordinates from vertex ID
  23981. 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);
  23982. }
  23983. // Subdivide the face (interpolate pos, norm, uv)
  23984. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  23985. // - norm is linear interpolation of vertex corner normal
  23986. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  23987. // - uv is linear interpolation
  23988. //
  23989. // Topology is as below for sub-divide by 2
  23990. // vertex shown as v0,v1,v2
  23991. // interp index is i1 to progress in range [v0,v1[
  23992. // interp index is i2 to progress in range [v0,v2[
  23993. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  23994. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  23995. //
  23996. //
  23997. // i2 v2
  23998. // ^ ^
  23999. // / / \
  24000. // / / \
  24001. // / / \
  24002. // / / (0,1) \
  24003. // / #---------\
  24004. // / / \ (0,0)'/ \
  24005. // / / \ / \
  24006. // / / \ / \
  24007. // / / (0,0) \ / (1,0) \
  24008. // / #---------#---------\
  24009. // v0 v1
  24010. //
  24011. // --------------------> i1
  24012. //
  24013. // interp of (i1,i2):
  24014. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24015. // along i1 : lerp(x0,x1, i1/(S-i2))
  24016. //
  24017. // centroid of triangle is needed to get help normal computation
  24018. // (c1,c2) are used for centroid location
  24019. var interp_vertex = function (i1, i2, c1, c2) {
  24020. // vertex is interpolated from
  24021. // - face_vertex_pos[0..2]
  24022. // - face_vertex_uv[0..2]
  24023. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24024. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24025. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24026. pos_interp.normalize();
  24027. var vertex_normal;
  24028. if (flat) {
  24029. // in flat mode, recalculate normal as face centroid normal
  24030. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24031. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24032. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24033. }
  24034. else {
  24035. // in smooth mode, recalculate normal from each single vertex position
  24036. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24037. }
  24038. // Vertex normal need correction due to X,Y,Z radius scaling
  24039. vertex_normal.x /= radiusX;
  24040. vertex_normal.y /= radiusY;
  24041. vertex_normal.z /= radiusZ;
  24042. vertex_normal.normalize();
  24043. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24044. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24045. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24046. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24047. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24048. uvs.push(uv_interp.x, uv_interp.y);
  24049. // push each vertex has member of a face
  24050. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24051. indices.push(current_indice);
  24052. current_indice++;
  24053. };
  24054. for (var i2 = 0; i2 < subdivisions; i2++) {
  24055. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24056. // face : (i1,i2) for /\ :
  24057. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24058. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24059. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24060. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24061. if (i1 + i2 + 1 < subdivisions) {
  24062. // face : (i1,i2)' for \/ :
  24063. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24064. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24065. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24066. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24067. }
  24068. }
  24069. }
  24070. }
  24071. // Sides
  24072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24073. // Result
  24074. var vertexData = new VertexData();
  24075. vertexData.indices = indices;
  24076. vertexData.positions = positions;
  24077. vertexData.normals = normals;
  24078. vertexData.uvs = uvs;
  24079. return vertexData;
  24080. };
  24081. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24082. VertexData.CreatePolyhedron = function (options) {
  24083. // provided polyhedron types :
  24084. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24085. // 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)
  24086. var polyhedra = [];
  24087. 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]] };
  24088. 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]] };
  24089. polyhedra[2] = {
  24090. 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]],
  24091. 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]]
  24092. };
  24093. polyhedra[3] = {
  24094. 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]],
  24095. 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]]
  24096. };
  24097. polyhedra[4] = {
  24098. 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]],
  24099. 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]]
  24100. };
  24101. 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]] };
  24102. 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]] };
  24103. 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]] };
  24104. 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]] };
  24105. 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]] };
  24106. 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]] };
  24107. 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]] };
  24108. 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]] };
  24109. 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]] };
  24110. polyhedra[14] = {
  24111. 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]],
  24112. 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]]
  24113. };
  24114. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24115. var size = options.size;
  24116. var sizeX = options.sizeX || size || 1;
  24117. var sizeY = options.sizeY || size || 1;
  24118. var sizeZ = options.sizeZ || size || 1;
  24119. var data = options.custom || polyhedra[type];
  24120. var nbfaces = data.face.length;
  24121. var faceUV = options.faceUV || new Array(nbfaces);
  24122. var faceColors = options.faceColors;
  24123. var flat = (options.flat === undefined) ? true : options.flat;
  24124. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24125. var positions = [];
  24126. var indices = [];
  24127. var normals = [];
  24128. var uvs = [];
  24129. var colors = [];
  24130. var index = 0;
  24131. var faceIdx = 0; // face cursor in the array "indexes"
  24132. var indexes = [];
  24133. var i = 0;
  24134. var f = 0;
  24135. var u, v, ang, x, y, tmp;
  24136. // default face colors and UV if undefined
  24137. if (flat) {
  24138. for (f = 0; f < nbfaces; f++) {
  24139. if (faceColors && faceColors[f] === undefined) {
  24140. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24141. }
  24142. if (faceUV && faceUV[f] === undefined) {
  24143. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24144. }
  24145. }
  24146. }
  24147. if (!flat) {
  24148. for (i = 0; i < data.vertex.length; i++) {
  24149. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24150. uvs.push(0, 0);
  24151. }
  24152. for (f = 0; f < nbfaces; f++) {
  24153. for (i = 0; i < data.face[f].length - 2; i++) {
  24154. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24155. }
  24156. }
  24157. }
  24158. else {
  24159. for (f = 0; f < nbfaces; f++) {
  24160. var fl = data.face[f].length; // number of vertices of the current face
  24161. ang = 2 * Math.PI / fl;
  24162. x = 0.5 * Math.tan(ang / 2);
  24163. y = 0.5;
  24164. // positions, uvs, colors
  24165. for (i = 0; i < fl; i++) {
  24166. // positions
  24167. 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);
  24168. indexes.push(index);
  24169. index++;
  24170. // uvs
  24171. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24172. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24173. uvs.push(u, v);
  24174. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24175. y = x * Math.sin(ang) + y * Math.cos(ang);
  24176. x = tmp;
  24177. // colors
  24178. if (faceColors) {
  24179. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24180. }
  24181. }
  24182. // indices from indexes
  24183. for (i = 0; i < fl - 2; i++) {
  24184. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24185. }
  24186. faceIdx += fl;
  24187. }
  24188. }
  24189. VertexData.ComputeNormals(positions, indices, normals);
  24190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24191. var vertexData = new VertexData();
  24192. vertexData.positions = positions;
  24193. vertexData.indices = indices;
  24194. vertexData.normals = normals;
  24195. vertexData.uvs = uvs;
  24196. if (faceColors && flat) {
  24197. vertexData.colors = colors;
  24198. }
  24199. return vertexData;
  24200. };
  24201. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24202. VertexData.CreateTorusKnot = function (options) {
  24203. var indices = [];
  24204. var positions = [];
  24205. var normals = [];
  24206. var uvs = [];
  24207. var radius = options.radius || 2;
  24208. var tube = options.tube || 0.5;
  24209. var radialSegments = options.radialSegments || 32;
  24210. var tubularSegments = options.tubularSegments || 32;
  24211. var p = options.p || 2;
  24212. var q = options.q || 3;
  24213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24214. // Helper
  24215. var getPos = function (angle) {
  24216. var cu = Math.cos(angle);
  24217. var su = Math.sin(angle);
  24218. var quOverP = q / p * angle;
  24219. var cs = Math.cos(quOverP);
  24220. var tx = radius * (2 + cs) * 0.5 * cu;
  24221. var ty = radius * (2 + cs) * su * 0.5;
  24222. var tz = radius * Math.sin(quOverP) * 0.5;
  24223. return new BABYLON.Vector3(tx, ty, tz);
  24224. };
  24225. // Vertices
  24226. var i;
  24227. var j;
  24228. for (i = 0; i <= radialSegments; i++) {
  24229. var modI = i % radialSegments;
  24230. var u = modI / radialSegments * 2 * p * Math.PI;
  24231. var p1 = getPos(u);
  24232. var p2 = getPos(u + 0.01);
  24233. var tang = p2.subtract(p1);
  24234. var n = p2.add(p1);
  24235. var bitan = BABYLON.Vector3.Cross(tang, n);
  24236. n = BABYLON.Vector3.Cross(bitan, tang);
  24237. bitan.normalize();
  24238. n.normalize();
  24239. for (j = 0; j < tubularSegments; j++) {
  24240. var modJ = j % tubularSegments;
  24241. var v = modJ / tubularSegments * 2 * Math.PI;
  24242. var cx = -tube * Math.cos(v);
  24243. var cy = tube * Math.sin(v);
  24244. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24245. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24246. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24247. uvs.push(i / radialSegments);
  24248. uvs.push(j / tubularSegments);
  24249. }
  24250. }
  24251. for (i = 0; i < radialSegments; i++) {
  24252. for (j = 0; j < tubularSegments; j++) {
  24253. var jNext = (j + 1) % tubularSegments;
  24254. var a = i * tubularSegments + j;
  24255. var b = (i + 1) * tubularSegments + j;
  24256. var c = (i + 1) * tubularSegments + jNext;
  24257. var d = i * tubularSegments + jNext;
  24258. indices.push(d);
  24259. indices.push(b);
  24260. indices.push(a);
  24261. indices.push(d);
  24262. indices.push(c);
  24263. indices.push(b);
  24264. }
  24265. }
  24266. // Normals
  24267. VertexData.ComputeNormals(positions, indices, normals);
  24268. // Sides
  24269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24270. // Result
  24271. var vertexData = new VertexData();
  24272. vertexData.indices = indices;
  24273. vertexData.positions = positions;
  24274. vertexData.normals = normals;
  24275. vertexData.uvs = uvs;
  24276. return vertexData;
  24277. };
  24278. // Tools
  24279. /**
  24280. * @param {any} - positions (number[] or Float32Array)
  24281. * @param {any} - indices (number[] or Uint16Array)
  24282. * @param {any} - normals (number[] or Float32Array)
  24283. */
  24284. VertexData.ComputeNormals = function (positions, indices, normals) {
  24285. var index = 0;
  24286. var p1p2x = 0.0;
  24287. var p1p2y = 0.0;
  24288. var p1p2z = 0.0;
  24289. var p3p2x = 0.0;
  24290. var p3p2y = 0.0;
  24291. var p3p2z = 0.0;
  24292. var faceNormalx = 0.0;
  24293. var faceNormaly = 0.0;
  24294. var faceNormalz = 0.0;
  24295. var length = 0.0;
  24296. var i1 = 0;
  24297. var i2 = 0;
  24298. var i3 = 0;
  24299. for (index = 0; index < positions.length; index++) {
  24300. normals[index] = 0.0;
  24301. }
  24302. // indice triplet = 1 face
  24303. var nbFaces = indices.length / 3;
  24304. for (index = 0; index < nbFaces; index++) {
  24305. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24306. i2 = indices[index * 3 + 1];
  24307. i3 = indices[index * 3 + 2];
  24308. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24309. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24310. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24311. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24312. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24313. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24314. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24315. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24316. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24317. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24318. length = (length === 0) ? 1.0 : length;
  24319. faceNormalx /= length; // normalize this normal
  24320. faceNormaly /= length;
  24321. faceNormalz /= length;
  24322. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24323. normals[i1 * 3 + 1] += faceNormaly;
  24324. normals[i1 * 3 + 2] += faceNormalz;
  24325. normals[i2 * 3] += faceNormalx;
  24326. normals[i2 * 3 + 1] += faceNormaly;
  24327. normals[i2 * 3 + 2] += faceNormalz;
  24328. normals[i3 * 3] += faceNormalx;
  24329. normals[i3 * 3 + 1] += faceNormaly;
  24330. normals[i3 * 3 + 2] += faceNormalz;
  24331. }
  24332. // last normalization of each normal
  24333. for (index = 0; index < normals.length / 3; index++) {
  24334. faceNormalx = normals[index * 3];
  24335. faceNormaly = normals[index * 3 + 1];
  24336. faceNormalz = normals[index * 3 + 2];
  24337. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24338. length = (length === 0) ? 1.0 : length;
  24339. faceNormalx /= length;
  24340. faceNormaly /= length;
  24341. faceNormalz /= length;
  24342. normals[index * 3] = faceNormalx;
  24343. normals[index * 3 + 1] = faceNormaly;
  24344. normals[index * 3 + 2] = faceNormalz;
  24345. }
  24346. };
  24347. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24348. var li = indices.length;
  24349. var ln = normals.length;
  24350. var i;
  24351. var n;
  24352. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24353. switch (sideOrientation) {
  24354. case BABYLON.Mesh.FRONTSIDE:
  24355. // nothing changed
  24356. break;
  24357. case BABYLON.Mesh.BACKSIDE:
  24358. var tmp;
  24359. // indices
  24360. for (i = 0; i < li; i += 3) {
  24361. tmp = indices[i];
  24362. indices[i] = indices[i + 2];
  24363. indices[i + 2] = tmp;
  24364. }
  24365. // normals
  24366. for (n = 0; n < ln; n++) {
  24367. normals[n] = -normals[n];
  24368. }
  24369. break;
  24370. case BABYLON.Mesh.DOUBLESIDE:
  24371. // positions
  24372. var lp = positions.length;
  24373. var l = lp / 3;
  24374. for (var p = 0; p < lp; p++) {
  24375. positions[lp + p] = positions[p];
  24376. }
  24377. // indices
  24378. for (i = 0; i < li; i += 3) {
  24379. indices[i + li] = indices[i + 2] + l;
  24380. indices[i + 1 + li] = indices[i + 1] + l;
  24381. indices[i + 2 + li] = indices[i] + l;
  24382. }
  24383. // normals
  24384. for (n = 0; n < ln; n++) {
  24385. normals[ln + n] = -normals[n];
  24386. }
  24387. // uvs
  24388. var lu = uvs.length;
  24389. for (var u = 0; u < lu; u++) {
  24390. uvs[u + lu] = uvs[u];
  24391. }
  24392. break;
  24393. }
  24394. };
  24395. return VertexData;
  24396. })();
  24397. BABYLON.VertexData = VertexData;
  24398. })(BABYLON || (BABYLON = {}));
  24399. var BABYLON;
  24400. (function (BABYLON) {
  24401. var Tags = (function () {
  24402. function Tags() {
  24403. }
  24404. Tags.EnableFor = function (obj) {
  24405. obj._tags = obj._tags || {};
  24406. obj.hasTags = function () {
  24407. return Tags.HasTags(obj);
  24408. };
  24409. obj.addTags = function (tagsString) {
  24410. return Tags.AddTagsTo(obj, tagsString);
  24411. };
  24412. obj.removeTags = function (tagsString) {
  24413. return Tags.RemoveTagsFrom(obj, tagsString);
  24414. };
  24415. obj.matchesTagsQuery = function (tagsQuery) {
  24416. return Tags.MatchesQuery(obj, tagsQuery);
  24417. };
  24418. };
  24419. Tags.DisableFor = function (obj) {
  24420. delete obj._tags;
  24421. delete obj.hasTags;
  24422. delete obj.addTags;
  24423. delete obj.removeTags;
  24424. delete obj.matchesTagsQuery;
  24425. };
  24426. Tags.HasTags = function (obj) {
  24427. if (!obj._tags) {
  24428. return false;
  24429. }
  24430. return !BABYLON.Tools.IsEmpty(obj._tags);
  24431. };
  24432. Tags.GetTags = function (obj) {
  24433. if (!obj._tags) {
  24434. return null;
  24435. }
  24436. return obj._tags;
  24437. };
  24438. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24439. // a tag cannot start with '||', '&&', and '!'
  24440. // it cannot contain whitespaces
  24441. Tags.AddTagsTo = function (obj, tagsString) {
  24442. if (!tagsString) {
  24443. return;
  24444. }
  24445. if (typeof tagsString !== "string") {
  24446. return;
  24447. }
  24448. var tags = tagsString.split(" ");
  24449. for (var t in tags) {
  24450. Tags._AddTagTo(obj, tags[t]);
  24451. }
  24452. };
  24453. Tags._AddTagTo = function (obj, tag) {
  24454. tag = tag.trim();
  24455. if (tag === "" || tag === "true" || tag === "false") {
  24456. return;
  24457. }
  24458. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24459. return;
  24460. }
  24461. Tags.EnableFor(obj);
  24462. obj._tags[tag] = true;
  24463. };
  24464. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24465. if (!Tags.HasTags(obj)) {
  24466. return;
  24467. }
  24468. var tags = tagsString.split(" ");
  24469. for (var t in tags) {
  24470. Tags._RemoveTagFrom(obj, tags[t]);
  24471. }
  24472. };
  24473. Tags._RemoveTagFrom = function (obj, tag) {
  24474. delete obj._tags[tag];
  24475. };
  24476. Tags.MatchesQuery = function (obj, tagsQuery) {
  24477. if (tagsQuery === undefined) {
  24478. return true;
  24479. }
  24480. if (tagsQuery === "") {
  24481. return Tags.HasTags(obj);
  24482. }
  24483. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24484. };
  24485. return Tags;
  24486. })();
  24487. BABYLON.Tags = Tags;
  24488. })(BABYLON || (BABYLON = {}));
  24489. var BABYLON;
  24490. (function (BABYLON) {
  24491. var Internals;
  24492. (function (Internals) {
  24493. var AndOrNotEvaluator = (function () {
  24494. function AndOrNotEvaluator() {
  24495. }
  24496. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24497. if (!query.match(/\([^\(\)]*\)/g)) {
  24498. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24499. }
  24500. else {
  24501. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24502. // remove parenthesis
  24503. r = r.slice(1, r.length - 1);
  24504. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24505. });
  24506. }
  24507. if (query === "true") {
  24508. return true;
  24509. }
  24510. if (query === "false") {
  24511. return false;
  24512. }
  24513. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24514. };
  24515. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24516. evaluateCallback = evaluateCallback || (function (r) {
  24517. return r === "true" ? true : false;
  24518. });
  24519. var result;
  24520. var or = parenthesisContent.split("||");
  24521. for (var i in or) {
  24522. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24523. var and = ori.split("&&");
  24524. if (and.length > 1) {
  24525. for (var j = 0; j < and.length; ++j) {
  24526. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24527. if (andj !== "true" && andj !== "false") {
  24528. if (andj[0] === "!") {
  24529. result = !evaluateCallback(andj.substring(1));
  24530. }
  24531. else {
  24532. result = evaluateCallback(andj);
  24533. }
  24534. }
  24535. else {
  24536. result = andj === "true" ? true : false;
  24537. }
  24538. if (!result) {
  24539. ori = "false";
  24540. break;
  24541. }
  24542. }
  24543. }
  24544. if (result || ori === "true") {
  24545. result = true;
  24546. break;
  24547. }
  24548. // result equals false (or undefined)
  24549. if (ori !== "true" && ori !== "false") {
  24550. if (ori[0] === "!") {
  24551. result = !evaluateCallback(ori.substring(1));
  24552. }
  24553. else {
  24554. result = evaluateCallback(ori);
  24555. }
  24556. }
  24557. else {
  24558. result = ori === "true" ? true : false;
  24559. }
  24560. }
  24561. // the whole parenthesis scope is replaced by 'true' or 'false'
  24562. return result ? "true" : "false";
  24563. };
  24564. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24565. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24566. // remove whitespaces
  24567. r = r.replace(/[\s]/g, function () { return ""; });
  24568. return r.length % 2 ? "!" : "";
  24569. });
  24570. booleanString = booleanString.trim();
  24571. if (booleanString === "!true") {
  24572. booleanString = "false";
  24573. }
  24574. else if (booleanString === "!false") {
  24575. booleanString = "true";
  24576. }
  24577. return booleanString;
  24578. };
  24579. return AndOrNotEvaluator;
  24580. })();
  24581. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24582. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24583. })(BABYLON || (BABYLON = {}));
  24584. var BABYLON;
  24585. (function (BABYLON) {
  24586. var PostProcessRenderPass = (function () {
  24587. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24588. this._enabled = true;
  24589. this._refCount = 0;
  24590. this._name = name;
  24591. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24592. this.setRenderList(renderList);
  24593. this._renderTexture.onBeforeRender = beforeRender;
  24594. this._renderTexture.onAfterRender = afterRender;
  24595. this._scene = scene;
  24596. this._renderList = renderList;
  24597. }
  24598. // private
  24599. PostProcessRenderPass.prototype._incRefCount = function () {
  24600. if (this._refCount === 0) {
  24601. this._scene.customRenderTargets.push(this._renderTexture);
  24602. }
  24603. return ++this._refCount;
  24604. };
  24605. PostProcessRenderPass.prototype._decRefCount = function () {
  24606. this._refCount--;
  24607. if (this._refCount <= 0) {
  24608. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24609. }
  24610. return this._refCount;
  24611. };
  24612. PostProcessRenderPass.prototype._update = function () {
  24613. this.setRenderList(this._renderList);
  24614. };
  24615. // public
  24616. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24617. this._renderTexture.renderList = renderList;
  24618. };
  24619. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24620. return this._renderTexture;
  24621. };
  24622. return PostProcessRenderPass;
  24623. })();
  24624. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24625. })(BABYLON || (BABYLON = {}));
  24626. var BABYLON;
  24627. (function (BABYLON) {
  24628. var PostProcessRenderEffect = (function () {
  24629. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24630. this._engine = engine;
  24631. this._name = name;
  24632. this._singleInstance = singleInstance || true;
  24633. this._getPostProcess = getPostProcess;
  24634. this._cameras = [];
  24635. this._indicesForCamera = [];
  24636. this._postProcesses = {};
  24637. this._renderPasses = {};
  24638. this._renderEffectAsPasses = {};
  24639. }
  24640. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24641. get: function () {
  24642. for (var index in this._postProcesses) {
  24643. if (!this._postProcesses[index].isSupported) {
  24644. return false;
  24645. }
  24646. }
  24647. return true;
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. PostProcessRenderEffect.prototype._update = function () {
  24653. for (var renderPassName in this._renderPasses) {
  24654. this._renderPasses[renderPassName]._update();
  24655. }
  24656. };
  24657. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24658. this._renderPasses[renderPass._name] = renderPass;
  24659. this._linkParameters();
  24660. };
  24661. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24662. delete this._renderPasses[renderPass._name];
  24663. this._linkParameters();
  24664. };
  24665. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24666. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24667. this._linkParameters();
  24668. };
  24669. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24670. for (var renderPassName in this._renderPasses) {
  24671. if (renderPassName === passName) {
  24672. return this._renderPasses[passName];
  24673. }
  24674. }
  24675. };
  24676. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24677. this._renderPasses = {};
  24678. this._linkParameters();
  24679. };
  24680. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24681. var cameraKey;
  24682. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24683. for (var i = 0; i < _cam.length; i++) {
  24684. var camera = _cam[i];
  24685. var cameraName = camera.name;
  24686. if (this._singleInstance) {
  24687. cameraKey = 0;
  24688. }
  24689. else {
  24690. cameraKey = cameraName;
  24691. }
  24692. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24693. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24694. if (!this._indicesForCamera[cameraName]) {
  24695. this._indicesForCamera[cameraName] = [];
  24696. }
  24697. this._indicesForCamera[cameraName].push(index);
  24698. if (this._cameras.indexOf(camera) === -1) {
  24699. this._cameras[cameraName] = camera;
  24700. }
  24701. for (var passName in this._renderPasses) {
  24702. this._renderPasses[passName]._incRefCount();
  24703. }
  24704. }
  24705. this._linkParameters();
  24706. };
  24707. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24708. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24709. for (var i = 0; i < _cam.length; i++) {
  24710. var camera = _cam[i];
  24711. var cameraName = camera.name;
  24712. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24713. var index = this._cameras.indexOf(cameraName);
  24714. this._indicesForCamera.splice(index, 1);
  24715. this._cameras.splice(index, 1);
  24716. for (var passName in this._renderPasses) {
  24717. this._renderPasses[passName]._decRefCount();
  24718. }
  24719. }
  24720. };
  24721. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24722. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24723. for (var i = 0; i < _cam.length; i++) {
  24724. var camera = _cam[i];
  24725. var cameraName = camera.name;
  24726. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24727. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24728. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24729. }
  24730. }
  24731. for (var passName in this._renderPasses) {
  24732. this._renderPasses[passName]._incRefCount();
  24733. }
  24734. }
  24735. };
  24736. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24737. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24738. for (var i = 0; i < _cam.length; i++) {
  24739. var camera = _cam[i];
  24740. var cameraName = camera.Name;
  24741. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24742. for (var passName in this._renderPasses) {
  24743. this._renderPasses[passName]._decRefCount();
  24744. }
  24745. }
  24746. };
  24747. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24748. if (this._singleInstance) {
  24749. return this._postProcesses[0];
  24750. }
  24751. else {
  24752. return this._postProcesses[camera.name];
  24753. }
  24754. };
  24755. PostProcessRenderEffect.prototype._linkParameters = function () {
  24756. var _this = this;
  24757. for (var index in this._postProcesses) {
  24758. if (this.applyParameters) {
  24759. this.applyParameters(this._postProcesses[index]);
  24760. }
  24761. this._postProcesses[index].onBeforeRender = function (effect) {
  24762. _this._linkTextures(effect);
  24763. };
  24764. }
  24765. };
  24766. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24767. for (var renderPassName in this._renderPasses) {
  24768. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24769. }
  24770. for (var renderEffectName in this._renderEffectAsPasses) {
  24771. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24772. }
  24773. };
  24774. return PostProcessRenderEffect;
  24775. })();
  24776. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24777. })(BABYLON || (BABYLON = {}));
  24778. var BABYLON;
  24779. (function (BABYLON) {
  24780. var PostProcessRenderPipeline = (function () {
  24781. function PostProcessRenderPipeline(engine, name) {
  24782. this._engine = engine;
  24783. this._name = name;
  24784. this._renderEffects = {};
  24785. this._renderEffectsForIsolatedPass = {};
  24786. this._cameras = [];
  24787. }
  24788. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24789. get: function () {
  24790. for (var renderEffectName in this._renderEffects) {
  24791. if (!this._renderEffects[renderEffectName].isSupported) {
  24792. return false;
  24793. }
  24794. }
  24795. return true;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24801. this._renderEffects[renderEffect._name] = renderEffect;
  24802. };
  24803. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24804. var renderEffects = this._renderEffects[renderEffectName];
  24805. if (!renderEffects) {
  24806. return;
  24807. }
  24808. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24809. };
  24810. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24811. var renderEffects = this._renderEffects[renderEffectName];
  24812. if (!renderEffects) {
  24813. return;
  24814. }
  24815. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24816. };
  24817. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24818. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24819. var indicesToDelete = [];
  24820. var i;
  24821. for (i = 0; i < _cam.length; i++) {
  24822. var camera = _cam[i];
  24823. var cameraName = camera.name;
  24824. if (this._cameras.indexOf(camera) === -1) {
  24825. this._cameras[cameraName] = camera;
  24826. }
  24827. else if (unique) {
  24828. indicesToDelete.push(i);
  24829. }
  24830. }
  24831. for (i = 0; i < indicesToDelete.length; i++) {
  24832. cameras.splice(indicesToDelete[i], 1);
  24833. }
  24834. for (var renderEffectName in this._renderEffects) {
  24835. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24836. }
  24837. };
  24838. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24839. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24840. for (var renderEffectName in this._renderEffects) {
  24841. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24842. }
  24843. for (var i = 0; i < _cam.length; i++) {
  24844. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24845. }
  24846. };
  24847. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24848. var _this = this;
  24849. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24850. var pass = null;
  24851. var renderEffectName;
  24852. for (renderEffectName in this._renderEffects) {
  24853. pass = this._renderEffects[renderEffectName].getPass(passName);
  24854. if (pass != null) {
  24855. break;
  24856. }
  24857. }
  24858. if (pass === null) {
  24859. return;
  24860. }
  24861. for (renderEffectName in this._renderEffects) {
  24862. this._renderEffects[renderEffectName]._disable(_cam);
  24863. }
  24864. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24865. for (var i = 0; i < _cam.length; i++) {
  24866. var camera = _cam[i];
  24867. var cameraName = camera.name;
  24868. 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); });
  24869. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24870. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24871. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24872. }
  24873. };
  24874. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24875. var _this = this;
  24876. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24877. for (var i = 0; i < _cam.length; i++) {
  24878. var camera = _cam[i];
  24879. var cameraName = camera.name;
  24880. 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); });
  24881. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24882. }
  24883. for (var renderEffectName in this._renderEffects) {
  24884. this._renderEffects[renderEffectName]._enable(_cam);
  24885. }
  24886. };
  24887. PostProcessRenderPipeline.prototype._update = function () {
  24888. for (var renderEffectName in this._renderEffects) {
  24889. this._renderEffects[renderEffectName]._update();
  24890. }
  24891. for (var i = 0; i < this._cameras.length; i++) {
  24892. var cameraName = this._cameras[i].name;
  24893. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24894. this._renderEffectsForIsolatedPass[cameraName]._update();
  24895. }
  24896. }
  24897. };
  24898. PostProcessRenderPipeline.prototype.dispose = function () {
  24899. // Must be implemented by children
  24900. };
  24901. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24902. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24903. return PostProcessRenderPipeline;
  24904. })();
  24905. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24906. })(BABYLON || (BABYLON = {}));
  24907. var BABYLON;
  24908. (function (BABYLON) {
  24909. var PostProcessRenderPipelineManager = (function () {
  24910. function PostProcessRenderPipelineManager() {
  24911. this._renderPipelines = {};
  24912. }
  24913. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24914. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24915. };
  24916. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24917. var renderPipeline = this._renderPipelines[renderPipelineName];
  24918. if (!renderPipeline) {
  24919. return;
  24920. }
  24921. renderPipeline._attachCameras(cameras, unique);
  24922. };
  24923. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24924. var renderPipeline = this._renderPipelines[renderPipelineName];
  24925. if (!renderPipeline) {
  24926. return;
  24927. }
  24928. renderPipeline._detachCameras(cameras);
  24929. };
  24930. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24931. var renderPipeline = this._renderPipelines[renderPipelineName];
  24932. if (!renderPipeline) {
  24933. return;
  24934. }
  24935. renderPipeline._enableEffect(renderEffectName, cameras);
  24936. };
  24937. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24938. var renderPipeline = this._renderPipelines[renderPipelineName];
  24939. if (!renderPipeline) {
  24940. return;
  24941. }
  24942. renderPipeline._disableEffect(renderEffectName, cameras);
  24943. };
  24944. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24945. var renderPipeline = this._renderPipelines[renderPipelineName];
  24946. if (!renderPipeline) {
  24947. return;
  24948. }
  24949. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24950. };
  24951. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24952. var renderPipeline = this._renderPipelines[renderPipelineName];
  24953. if (!renderPipeline) {
  24954. return;
  24955. }
  24956. renderPipeline._disableDisplayOnlyPass(cameras);
  24957. };
  24958. PostProcessRenderPipelineManager.prototype.update = function () {
  24959. for (var renderPipelineName in this._renderPipelines) {
  24960. var pipeline = this._renderPipelines[renderPipelineName];
  24961. if (!pipeline.isSupported) {
  24962. pipeline.dispose();
  24963. delete this._renderPipelines[renderPipelineName];
  24964. }
  24965. else {
  24966. pipeline._update();
  24967. }
  24968. }
  24969. };
  24970. return PostProcessRenderPipelineManager;
  24971. })();
  24972. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24973. })(BABYLON || (BABYLON = {}));
  24974. var BABYLON;
  24975. (function (BABYLON) {
  24976. var BoundingBoxRenderer = (function () {
  24977. function BoundingBoxRenderer(scene) {
  24978. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24979. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24980. this.showBackLines = true;
  24981. this.renderList = new BABYLON.SmartArray(32);
  24982. this._scene = scene;
  24983. }
  24984. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24985. if (this._colorShader) {
  24986. return;
  24987. }
  24988. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24989. attributes: ["position"],
  24990. uniforms: ["worldViewProjection", "color"]
  24991. });
  24992. var engine = this._scene.getEngine();
  24993. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24994. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24995. 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]);
  24996. };
  24997. BoundingBoxRenderer.prototype.reset = function () {
  24998. this.renderList.reset();
  24999. };
  25000. BoundingBoxRenderer.prototype.render = function () {
  25001. if (this.renderList.length === 0) {
  25002. return;
  25003. }
  25004. this._prepareRessources();
  25005. if (!this._colorShader.isReady()) {
  25006. return;
  25007. }
  25008. var engine = this._scene.getEngine();
  25009. engine.setDepthWrite(false);
  25010. this._colorShader._preBind();
  25011. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25012. var boundingBox = this.renderList.data[boundingBoxIndex];
  25013. var min = boundingBox.minimum;
  25014. var max = boundingBox.maximum;
  25015. var diff = max.subtract(min);
  25016. var median = min.add(diff.scale(0.5));
  25017. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25018. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25019. .multiply(boundingBox.getWorldMatrix());
  25020. // VBOs
  25021. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25022. if (this.showBackLines) {
  25023. // Back
  25024. engine.setDepthFunctionToGreaterOrEqual();
  25025. this._scene.resetCachedMaterial();
  25026. this._colorShader.setColor4("color", this.backColor.toColor4());
  25027. this._colorShader.bind(worldMatrix);
  25028. // Draw order
  25029. engine.draw(false, 0, 24);
  25030. }
  25031. // Front
  25032. engine.setDepthFunctionToLess();
  25033. this._scene.resetCachedMaterial();
  25034. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25035. this._colorShader.bind(worldMatrix);
  25036. // Draw order
  25037. engine.draw(false, 0, 24);
  25038. }
  25039. this._colorShader.unbind();
  25040. engine.setDepthFunctionToLessOrEqual();
  25041. engine.setDepthWrite(true);
  25042. };
  25043. BoundingBoxRenderer.prototype.dispose = function () {
  25044. if (!this._colorShader) {
  25045. return;
  25046. }
  25047. this._colorShader.dispose();
  25048. this._vb.dispose();
  25049. this._scene.getEngine()._releaseBuffer(this._ib);
  25050. };
  25051. return BoundingBoxRenderer;
  25052. })();
  25053. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25054. })(BABYLON || (BABYLON = {}));
  25055. var BABYLON;
  25056. (function (BABYLON) {
  25057. var Condition = (function () {
  25058. function Condition(actionManager) {
  25059. this._actionManager = actionManager;
  25060. }
  25061. Condition.prototype.isValid = function () {
  25062. return true;
  25063. };
  25064. Condition.prototype._getProperty = function (propertyPath) {
  25065. return this._actionManager._getProperty(propertyPath);
  25066. };
  25067. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25068. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25069. };
  25070. return Condition;
  25071. })();
  25072. BABYLON.Condition = Condition;
  25073. var ValueCondition = (function (_super) {
  25074. __extends(ValueCondition, _super);
  25075. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25076. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25077. _super.call(this, actionManager);
  25078. this.propertyPath = propertyPath;
  25079. this.value = value;
  25080. this.operator = operator;
  25081. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25082. this._property = this._getProperty(this.propertyPath);
  25083. }
  25084. Object.defineProperty(ValueCondition, "IsEqual", {
  25085. get: function () {
  25086. return ValueCondition._IsEqual;
  25087. },
  25088. enumerable: true,
  25089. configurable: true
  25090. });
  25091. Object.defineProperty(ValueCondition, "IsDifferent", {
  25092. get: function () {
  25093. return ValueCondition._IsDifferent;
  25094. },
  25095. enumerable: true,
  25096. configurable: true
  25097. });
  25098. Object.defineProperty(ValueCondition, "IsGreater", {
  25099. get: function () {
  25100. return ValueCondition._IsGreater;
  25101. },
  25102. enumerable: true,
  25103. configurable: true
  25104. });
  25105. Object.defineProperty(ValueCondition, "IsLesser", {
  25106. get: function () {
  25107. return ValueCondition._IsLesser;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. // Methods
  25113. ValueCondition.prototype.isValid = function () {
  25114. switch (this.operator) {
  25115. case ValueCondition.IsGreater:
  25116. return this._target[this._property] > this.value;
  25117. case ValueCondition.IsLesser:
  25118. return this._target[this._property] < this.value;
  25119. case ValueCondition.IsEqual:
  25120. case ValueCondition.IsDifferent:
  25121. var check;
  25122. if (this.value.equals) {
  25123. check = this.value.equals(this._target[this._property]);
  25124. }
  25125. else {
  25126. check = this.value === this._target[this._property];
  25127. }
  25128. return this.operator === ValueCondition.IsEqual ? check : !check;
  25129. }
  25130. return false;
  25131. };
  25132. // Statics
  25133. ValueCondition._IsEqual = 0;
  25134. ValueCondition._IsDifferent = 1;
  25135. ValueCondition._IsGreater = 2;
  25136. ValueCondition._IsLesser = 3;
  25137. return ValueCondition;
  25138. })(Condition);
  25139. BABYLON.ValueCondition = ValueCondition;
  25140. var PredicateCondition = (function (_super) {
  25141. __extends(PredicateCondition, _super);
  25142. function PredicateCondition(actionManager, predicate) {
  25143. _super.call(this, actionManager);
  25144. this.predicate = predicate;
  25145. }
  25146. PredicateCondition.prototype.isValid = function () {
  25147. return this.predicate();
  25148. };
  25149. return PredicateCondition;
  25150. })(Condition);
  25151. BABYLON.PredicateCondition = PredicateCondition;
  25152. var StateCondition = (function (_super) {
  25153. __extends(StateCondition, _super);
  25154. function StateCondition(actionManager, target, value) {
  25155. _super.call(this, actionManager);
  25156. this.value = value;
  25157. this._target = target;
  25158. }
  25159. // Methods
  25160. StateCondition.prototype.isValid = function () {
  25161. return this._target.state === this.value;
  25162. };
  25163. return StateCondition;
  25164. })(Condition);
  25165. BABYLON.StateCondition = StateCondition;
  25166. })(BABYLON || (BABYLON = {}));
  25167. var BABYLON;
  25168. (function (BABYLON) {
  25169. var Action = (function () {
  25170. function Action(triggerOptions, condition) {
  25171. this.triggerOptions = triggerOptions;
  25172. if (triggerOptions.parameter) {
  25173. this.trigger = triggerOptions.trigger;
  25174. this._triggerParameter = triggerOptions.parameter;
  25175. }
  25176. else {
  25177. this.trigger = triggerOptions;
  25178. }
  25179. this._nextActiveAction = this;
  25180. this._condition = condition;
  25181. }
  25182. // Methods
  25183. Action.prototype._prepare = function () {
  25184. };
  25185. Action.prototype.getTriggerParameter = function () {
  25186. return this._triggerParameter;
  25187. };
  25188. Action.prototype._executeCurrent = function (evt) {
  25189. if (this._nextActiveAction._condition) {
  25190. var condition = this._nextActiveAction._condition;
  25191. var currentRenderId = this._actionManager.getScene().getRenderId();
  25192. // We cache the current evaluation for the current frame
  25193. if (condition._evaluationId === currentRenderId) {
  25194. if (!condition._currentResult) {
  25195. return;
  25196. }
  25197. }
  25198. else {
  25199. condition._evaluationId = currentRenderId;
  25200. if (!condition.isValid()) {
  25201. condition._currentResult = false;
  25202. return;
  25203. }
  25204. condition._currentResult = true;
  25205. }
  25206. }
  25207. this._nextActiveAction.execute(evt);
  25208. if (this._nextActiveAction._child) {
  25209. if (!this._nextActiveAction._child._actionManager) {
  25210. this._nextActiveAction._child._actionManager = this._actionManager;
  25211. }
  25212. this._nextActiveAction = this._nextActiveAction._child;
  25213. }
  25214. else {
  25215. this._nextActiveAction = this;
  25216. }
  25217. };
  25218. Action.prototype.execute = function (evt) {
  25219. };
  25220. Action.prototype.then = function (action) {
  25221. this._child = action;
  25222. action._actionManager = this._actionManager;
  25223. action._prepare();
  25224. return action;
  25225. };
  25226. Action.prototype._getProperty = function (propertyPath) {
  25227. return this._actionManager._getProperty(propertyPath);
  25228. };
  25229. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25230. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25231. };
  25232. return Action;
  25233. })();
  25234. BABYLON.Action = Action;
  25235. })(BABYLON || (BABYLON = {}));
  25236. var BABYLON;
  25237. (function (BABYLON) {
  25238. /**
  25239. * ActionEvent is the event beint sent when an action is triggered.
  25240. */
  25241. var ActionEvent = (function () {
  25242. /**
  25243. * @constructor
  25244. * @param source The mesh or sprite that triggered the action.
  25245. * @param pointerX The X mouse cursor position at the time of the event
  25246. * @param pointerY The Y mouse cursor position at the time of the event
  25247. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25248. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25249. */
  25250. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25251. this.source = source;
  25252. this.pointerX = pointerX;
  25253. this.pointerY = pointerY;
  25254. this.meshUnderPointer = meshUnderPointer;
  25255. this.sourceEvent = sourceEvent;
  25256. this.additionalData = additionalData;
  25257. }
  25258. /**
  25259. * Helper function to auto-create an ActionEvent from a source mesh.
  25260. * @param source The source mesh that triggered the event
  25261. * @param evt {Event} The original (browser) event
  25262. */
  25263. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25264. var scene = source.getScene();
  25265. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25266. };
  25267. /**
  25268. * Helper function to auto-create an ActionEvent from a source mesh.
  25269. * @param source The source sprite that triggered the event
  25270. * @param scene Scene associated with the sprite
  25271. * @param evt {Event} The original (browser) event
  25272. */
  25273. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25274. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25275. };
  25276. /**
  25277. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25278. * @param scene the scene where the event occurred
  25279. * @param evt {Event} The original (browser) event
  25280. */
  25281. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25282. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25283. };
  25284. return ActionEvent;
  25285. })();
  25286. BABYLON.ActionEvent = ActionEvent;
  25287. /**
  25288. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25289. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25290. */
  25291. var ActionManager = (function () {
  25292. function ActionManager(scene) {
  25293. // Members
  25294. this.actions = new Array();
  25295. this._scene = scene;
  25296. scene._actionManagers.push(this);
  25297. }
  25298. Object.defineProperty(ActionManager, "NothingTrigger", {
  25299. get: function () {
  25300. return ActionManager._NothingTrigger;
  25301. },
  25302. enumerable: true,
  25303. configurable: true
  25304. });
  25305. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25306. get: function () {
  25307. return ActionManager._OnPickTrigger;
  25308. },
  25309. enumerable: true,
  25310. configurable: true
  25311. });
  25312. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25313. get: function () {
  25314. return ActionManager._OnLeftPickTrigger;
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25320. get: function () {
  25321. return ActionManager._OnRightPickTrigger;
  25322. },
  25323. enumerable: true,
  25324. configurable: true
  25325. });
  25326. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25327. get: function () {
  25328. return ActionManager._OnCenterPickTrigger;
  25329. },
  25330. enumerable: true,
  25331. configurable: true
  25332. });
  25333. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25334. get: function () {
  25335. return ActionManager._OnPointerOverTrigger;
  25336. },
  25337. enumerable: true,
  25338. configurable: true
  25339. });
  25340. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25341. get: function () {
  25342. return ActionManager._OnPointerOutTrigger;
  25343. },
  25344. enumerable: true,
  25345. configurable: true
  25346. });
  25347. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25348. get: function () {
  25349. return ActionManager._OnEveryFrameTrigger;
  25350. },
  25351. enumerable: true,
  25352. configurable: true
  25353. });
  25354. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25355. get: function () {
  25356. return ActionManager._OnIntersectionEnterTrigger;
  25357. },
  25358. enumerable: true,
  25359. configurable: true
  25360. });
  25361. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25362. get: function () {
  25363. return ActionManager._OnIntersectionExitTrigger;
  25364. },
  25365. enumerable: true,
  25366. configurable: true
  25367. });
  25368. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25369. get: function () {
  25370. return ActionManager._OnKeyDownTrigger;
  25371. },
  25372. enumerable: true,
  25373. configurable: true
  25374. });
  25375. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25376. get: function () {
  25377. return ActionManager._OnKeyUpTrigger;
  25378. },
  25379. enumerable: true,
  25380. configurable: true
  25381. });
  25382. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25383. get: function () {
  25384. return ActionManager._OnPickUpTrigger;
  25385. },
  25386. enumerable: true,
  25387. configurable: true
  25388. });
  25389. // Methods
  25390. ActionManager.prototype.dispose = function () {
  25391. var index = this._scene._actionManagers.indexOf(this);
  25392. if (index > -1) {
  25393. this._scene._actionManagers.splice(index, 1);
  25394. }
  25395. };
  25396. ActionManager.prototype.getScene = function () {
  25397. return this._scene;
  25398. };
  25399. /**
  25400. * Does this action manager handles actions of any of the given triggers
  25401. * @param {number[]} triggers - the triggers to be tested
  25402. * @return {boolean} whether one (or more) of the triggers is handeled
  25403. */
  25404. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25405. for (var index = 0; index < this.actions.length; index++) {
  25406. var action = this.actions[index];
  25407. if (triggers.indexOf(action.trigger) > -1) {
  25408. return true;
  25409. }
  25410. }
  25411. return false;
  25412. };
  25413. /**
  25414. * Does this action manager handles actions of a given trigger
  25415. * @param {number} trigger - the trigger to be tested
  25416. * @return {boolean} whether the trigger is handeled
  25417. */
  25418. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25419. for (var index = 0; index < this.actions.length; index++) {
  25420. var action = this.actions[index];
  25421. if (action.trigger === trigger) {
  25422. return true;
  25423. }
  25424. }
  25425. return false;
  25426. };
  25427. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25428. /**
  25429. * Does this action manager has pointer triggers
  25430. * @return {boolean} whether or not it has pointer triggers
  25431. */
  25432. get: function () {
  25433. for (var index = 0; index < this.actions.length; index++) {
  25434. var action = this.actions[index];
  25435. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25436. return true;
  25437. }
  25438. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25439. return true;
  25440. }
  25441. }
  25442. return false;
  25443. },
  25444. enumerable: true,
  25445. configurable: true
  25446. });
  25447. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25448. /**
  25449. * Does this action manager has pick triggers
  25450. * @return {boolean} whether or not it has pick triggers
  25451. */
  25452. get: function () {
  25453. for (var index = 0; index < this.actions.length; index++) {
  25454. var action = this.actions[index];
  25455. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25456. return true;
  25457. }
  25458. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25459. return true;
  25460. }
  25461. }
  25462. return false;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. /**
  25468. * Registers an action to this action manager
  25469. * @param {BABYLON.Action} action - the action to be registered
  25470. * @return {BABYLON.Action} the action amended (prepared) after registration
  25471. */
  25472. ActionManager.prototype.registerAction = function (action) {
  25473. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25474. if (this.getScene().actionManager !== this) {
  25475. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25476. return null;
  25477. }
  25478. }
  25479. this.actions.push(action);
  25480. action._actionManager = this;
  25481. action._prepare();
  25482. return action;
  25483. };
  25484. /**
  25485. * Process a specific trigger
  25486. * @param {number} trigger - the trigger to process
  25487. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25488. */
  25489. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25490. for (var index = 0; index < this.actions.length; index++) {
  25491. var action = this.actions[index];
  25492. if (action.trigger === trigger) {
  25493. if (trigger === ActionManager.OnKeyUpTrigger
  25494. || trigger === ActionManager.OnKeyDownTrigger) {
  25495. var parameter = action.getTriggerParameter();
  25496. if (parameter) {
  25497. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25498. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25499. if (actualkey !== parameter.toLowerCase()) {
  25500. continue;
  25501. }
  25502. }
  25503. }
  25504. action._executeCurrent(evt);
  25505. }
  25506. }
  25507. };
  25508. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25509. var properties = propertyPath.split(".");
  25510. for (var index = 0; index < properties.length - 1; index++) {
  25511. target = target[properties[index]];
  25512. }
  25513. return target;
  25514. };
  25515. ActionManager.prototype._getProperty = function (propertyPath) {
  25516. var properties = propertyPath.split(".");
  25517. return properties[properties.length - 1];
  25518. };
  25519. // Statics
  25520. ActionManager._NothingTrigger = 0;
  25521. ActionManager._OnPickTrigger = 1;
  25522. ActionManager._OnLeftPickTrigger = 2;
  25523. ActionManager._OnRightPickTrigger = 3;
  25524. ActionManager._OnCenterPickTrigger = 4;
  25525. ActionManager._OnPointerOverTrigger = 5;
  25526. ActionManager._OnPointerOutTrigger = 6;
  25527. ActionManager._OnEveryFrameTrigger = 7;
  25528. ActionManager._OnIntersectionEnterTrigger = 8;
  25529. ActionManager._OnIntersectionExitTrigger = 9;
  25530. ActionManager._OnKeyDownTrigger = 10;
  25531. ActionManager._OnKeyUpTrigger = 11;
  25532. ActionManager._OnPickUpTrigger = 12;
  25533. return ActionManager;
  25534. })();
  25535. BABYLON.ActionManager = ActionManager;
  25536. })(BABYLON || (BABYLON = {}));
  25537. var BABYLON;
  25538. (function (BABYLON) {
  25539. var InterpolateValueAction = (function (_super) {
  25540. __extends(InterpolateValueAction, _super);
  25541. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25542. if (duration === void 0) { duration = 1000; }
  25543. _super.call(this, triggerOptions, condition);
  25544. this.propertyPath = propertyPath;
  25545. this.value = value;
  25546. this.duration = duration;
  25547. this.stopOtherAnimations = stopOtherAnimations;
  25548. this.onInterpolationDone = onInterpolationDone;
  25549. this._target = target;
  25550. }
  25551. InterpolateValueAction.prototype._prepare = function () {
  25552. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25553. this._property = this._getProperty(this.propertyPath);
  25554. };
  25555. InterpolateValueAction.prototype.execute = function () {
  25556. var scene = this._actionManager.getScene();
  25557. var keys = [
  25558. {
  25559. frame: 0,
  25560. value: this._target[this._property]
  25561. }, {
  25562. frame: 100,
  25563. value: this.value
  25564. }
  25565. ];
  25566. var dataType;
  25567. if (typeof this.value === "number") {
  25568. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25569. }
  25570. else if (this.value instanceof BABYLON.Color3) {
  25571. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25572. }
  25573. else if (this.value instanceof BABYLON.Vector3) {
  25574. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25575. }
  25576. else if (this.value instanceof BABYLON.Matrix) {
  25577. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25578. }
  25579. else if (this.value instanceof BABYLON.Quaternion) {
  25580. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25581. }
  25582. else {
  25583. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25584. return;
  25585. }
  25586. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25587. animation.setKeys(keys);
  25588. if (this.stopOtherAnimations) {
  25589. scene.stopAnimation(this._target);
  25590. }
  25591. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25592. };
  25593. return InterpolateValueAction;
  25594. })(BABYLON.Action);
  25595. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25596. })(BABYLON || (BABYLON = {}));
  25597. var BABYLON;
  25598. (function (BABYLON) {
  25599. var SwitchBooleanAction = (function (_super) {
  25600. __extends(SwitchBooleanAction, _super);
  25601. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25602. _super.call(this, triggerOptions, condition);
  25603. this.propertyPath = propertyPath;
  25604. this._target = target;
  25605. }
  25606. SwitchBooleanAction.prototype._prepare = function () {
  25607. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25608. this._property = this._getProperty(this.propertyPath);
  25609. };
  25610. SwitchBooleanAction.prototype.execute = function () {
  25611. this._target[this._property] = !this._target[this._property];
  25612. };
  25613. return SwitchBooleanAction;
  25614. })(BABYLON.Action);
  25615. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25616. var SetStateAction = (function (_super) {
  25617. __extends(SetStateAction, _super);
  25618. function SetStateAction(triggerOptions, target, value, condition) {
  25619. _super.call(this, triggerOptions, condition);
  25620. this.value = value;
  25621. this._target = target;
  25622. }
  25623. SetStateAction.prototype.execute = function () {
  25624. this._target.state = this.value;
  25625. };
  25626. return SetStateAction;
  25627. })(BABYLON.Action);
  25628. BABYLON.SetStateAction = SetStateAction;
  25629. var SetValueAction = (function (_super) {
  25630. __extends(SetValueAction, _super);
  25631. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25632. _super.call(this, triggerOptions, condition);
  25633. this.propertyPath = propertyPath;
  25634. this.value = value;
  25635. this._target = target;
  25636. }
  25637. SetValueAction.prototype._prepare = function () {
  25638. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25639. this._property = this._getProperty(this.propertyPath);
  25640. };
  25641. SetValueAction.prototype.execute = function () {
  25642. this._target[this._property] = this.value;
  25643. };
  25644. return SetValueAction;
  25645. })(BABYLON.Action);
  25646. BABYLON.SetValueAction = SetValueAction;
  25647. var IncrementValueAction = (function (_super) {
  25648. __extends(IncrementValueAction, _super);
  25649. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25650. _super.call(this, triggerOptions, condition);
  25651. this.propertyPath = propertyPath;
  25652. this.value = value;
  25653. this._target = target;
  25654. }
  25655. IncrementValueAction.prototype._prepare = function () {
  25656. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25657. this._property = this._getProperty(this.propertyPath);
  25658. if (typeof this._target[this._property] !== "number") {
  25659. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25660. }
  25661. };
  25662. IncrementValueAction.prototype.execute = function () {
  25663. this._target[this._property] += this.value;
  25664. };
  25665. return IncrementValueAction;
  25666. })(BABYLON.Action);
  25667. BABYLON.IncrementValueAction = IncrementValueAction;
  25668. var PlayAnimationAction = (function (_super) {
  25669. __extends(PlayAnimationAction, _super);
  25670. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25671. _super.call(this, triggerOptions, condition);
  25672. this.from = from;
  25673. this.to = to;
  25674. this.loop = loop;
  25675. this._target = target;
  25676. }
  25677. PlayAnimationAction.prototype._prepare = function () {
  25678. };
  25679. PlayAnimationAction.prototype.execute = function () {
  25680. var scene = this._actionManager.getScene();
  25681. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25682. };
  25683. return PlayAnimationAction;
  25684. })(BABYLON.Action);
  25685. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25686. var StopAnimationAction = (function (_super) {
  25687. __extends(StopAnimationAction, _super);
  25688. function StopAnimationAction(triggerOptions, target, condition) {
  25689. _super.call(this, triggerOptions, condition);
  25690. this._target = target;
  25691. }
  25692. StopAnimationAction.prototype._prepare = function () {
  25693. };
  25694. StopAnimationAction.prototype.execute = function () {
  25695. var scene = this._actionManager.getScene();
  25696. scene.stopAnimation(this._target);
  25697. };
  25698. return StopAnimationAction;
  25699. })(BABYLON.Action);
  25700. BABYLON.StopAnimationAction = StopAnimationAction;
  25701. var DoNothingAction = (function (_super) {
  25702. __extends(DoNothingAction, _super);
  25703. function DoNothingAction(triggerOptions, condition) {
  25704. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25705. _super.call(this, triggerOptions, condition);
  25706. }
  25707. DoNothingAction.prototype.execute = function () {
  25708. };
  25709. return DoNothingAction;
  25710. })(BABYLON.Action);
  25711. BABYLON.DoNothingAction = DoNothingAction;
  25712. var CombineAction = (function (_super) {
  25713. __extends(CombineAction, _super);
  25714. function CombineAction(triggerOptions, children, condition) {
  25715. _super.call(this, triggerOptions, condition);
  25716. this.children = children;
  25717. }
  25718. CombineAction.prototype._prepare = function () {
  25719. for (var index = 0; index < this.children.length; index++) {
  25720. this.children[index]._actionManager = this._actionManager;
  25721. this.children[index]._prepare();
  25722. }
  25723. };
  25724. CombineAction.prototype.execute = function (evt) {
  25725. for (var index = 0; index < this.children.length; index++) {
  25726. this.children[index].execute(evt);
  25727. }
  25728. };
  25729. return CombineAction;
  25730. })(BABYLON.Action);
  25731. BABYLON.CombineAction = CombineAction;
  25732. var ExecuteCodeAction = (function (_super) {
  25733. __extends(ExecuteCodeAction, _super);
  25734. function ExecuteCodeAction(triggerOptions, func, condition) {
  25735. _super.call(this, triggerOptions, condition);
  25736. this.func = func;
  25737. }
  25738. ExecuteCodeAction.prototype.execute = function (evt) {
  25739. this.func(evt);
  25740. };
  25741. return ExecuteCodeAction;
  25742. })(BABYLON.Action);
  25743. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25744. var SetParentAction = (function (_super) {
  25745. __extends(SetParentAction, _super);
  25746. function SetParentAction(triggerOptions, target, parent, condition) {
  25747. _super.call(this, triggerOptions, condition);
  25748. this._target = target;
  25749. this._parent = parent;
  25750. }
  25751. SetParentAction.prototype._prepare = function () {
  25752. };
  25753. SetParentAction.prototype.execute = function () {
  25754. if (this._target.parent === this._parent) {
  25755. return;
  25756. }
  25757. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25758. invertParentWorldMatrix.invert();
  25759. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25760. this._target.parent = this._parent;
  25761. };
  25762. return SetParentAction;
  25763. })(BABYLON.Action);
  25764. BABYLON.SetParentAction = SetParentAction;
  25765. var PlaySoundAction = (function (_super) {
  25766. __extends(PlaySoundAction, _super);
  25767. function PlaySoundAction(triggerOptions, sound, condition) {
  25768. _super.call(this, triggerOptions, condition);
  25769. this._sound = sound;
  25770. }
  25771. PlaySoundAction.prototype._prepare = function () {
  25772. };
  25773. PlaySoundAction.prototype.execute = function () {
  25774. if (this._sound !== undefined)
  25775. this._sound.play();
  25776. };
  25777. return PlaySoundAction;
  25778. })(BABYLON.Action);
  25779. BABYLON.PlaySoundAction = PlaySoundAction;
  25780. var StopSoundAction = (function (_super) {
  25781. __extends(StopSoundAction, _super);
  25782. function StopSoundAction(triggerOptions, sound, condition) {
  25783. _super.call(this, triggerOptions, condition);
  25784. this._sound = sound;
  25785. }
  25786. StopSoundAction.prototype._prepare = function () {
  25787. };
  25788. StopSoundAction.prototype.execute = function () {
  25789. if (this._sound !== undefined)
  25790. this._sound.stop();
  25791. };
  25792. return StopSoundAction;
  25793. })(BABYLON.Action);
  25794. BABYLON.StopSoundAction = StopSoundAction;
  25795. })(BABYLON || (BABYLON = {}));
  25796. var BABYLON;
  25797. (function (BABYLON) {
  25798. var Geometry = (function () {
  25799. function Geometry(id, scene, vertexData, updatable, mesh) {
  25800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25801. this._totalVertices = 0;
  25802. this._isDisposed = false;
  25803. this.id = id;
  25804. this._engine = scene.getEngine();
  25805. this._meshes = [];
  25806. this._scene = scene;
  25807. //Init vertex buffer cache
  25808. this._vertexBuffers = {};
  25809. this._indices = [];
  25810. // vertexData
  25811. if (vertexData) {
  25812. this.setAllVerticesData(vertexData, updatable);
  25813. }
  25814. else {
  25815. this._totalVertices = 0;
  25816. this._indices = [];
  25817. }
  25818. // applyToMesh
  25819. if (mesh) {
  25820. this.applyToMesh(mesh);
  25821. mesh.computeWorldMatrix(true);
  25822. }
  25823. }
  25824. Object.defineProperty(Geometry.prototype, "extend", {
  25825. get: function () {
  25826. return this._extend;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Geometry.prototype.getScene = function () {
  25832. return this._scene;
  25833. };
  25834. Geometry.prototype.getEngine = function () {
  25835. return this._engine;
  25836. };
  25837. Geometry.prototype.isReady = function () {
  25838. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25839. };
  25840. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25841. vertexData.applyToGeometry(this, updatable);
  25842. this.notifyUpdate();
  25843. };
  25844. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25845. if (this._vertexBuffers[kind]) {
  25846. this._vertexBuffers[kind].dispose();
  25847. }
  25848. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25849. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25850. stride = this._vertexBuffers[kind].getStrideSize();
  25851. this._totalVertices = data.length / stride;
  25852. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25853. var meshes = this._meshes;
  25854. var numOfMeshes = meshes.length;
  25855. for (var index = 0; index < numOfMeshes; index++) {
  25856. var mesh = meshes[index];
  25857. mesh._resetPointsArrayCache();
  25858. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25859. mesh._createGlobalSubMesh();
  25860. mesh.computeWorldMatrix(true);
  25861. }
  25862. }
  25863. this.notifyUpdate(kind);
  25864. };
  25865. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25866. var vertexBuffer = this.getVertexBuffer(kind);
  25867. if (!vertexBuffer) {
  25868. return;
  25869. }
  25870. vertexBuffer.updateDirectly(data, offset);
  25871. this.notifyUpdate(kind);
  25872. };
  25873. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25874. var vertexBuffer = this.getVertexBuffer(kind);
  25875. if (!vertexBuffer) {
  25876. return;
  25877. }
  25878. vertexBuffer.update(data);
  25879. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25880. var stride = vertexBuffer.getStrideSize();
  25881. this._totalVertices = data.length / stride;
  25882. if (updateExtends) {
  25883. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25884. }
  25885. var meshes = this._meshes;
  25886. var numOfMeshes = meshes.length;
  25887. for (var index = 0; index < numOfMeshes; index++) {
  25888. var mesh = meshes[index];
  25889. mesh._resetPointsArrayCache();
  25890. if (updateExtends) {
  25891. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25892. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25893. var subMesh = mesh.subMeshes[subIndex];
  25894. subMesh.refreshBoundingInfo();
  25895. }
  25896. }
  25897. }
  25898. }
  25899. this.notifyUpdate(kind);
  25900. };
  25901. Geometry.prototype.getTotalVertices = function () {
  25902. if (!this.isReady()) {
  25903. return 0;
  25904. }
  25905. return this._totalVertices;
  25906. };
  25907. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25908. var vertexBuffer = this.getVertexBuffer(kind);
  25909. if (!vertexBuffer) {
  25910. return null;
  25911. }
  25912. var orig = vertexBuffer.getData();
  25913. if (!copyWhenShared || this._meshes.length === 1) {
  25914. return orig;
  25915. }
  25916. else {
  25917. var len = orig.length;
  25918. var copy = [];
  25919. for (var i = 0; i < len; i++) {
  25920. copy.push(orig[i]);
  25921. }
  25922. return copy;
  25923. }
  25924. };
  25925. Geometry.prototype.getVertexBuffer = function (kind) {
  25926. if (!this.isReady()) {
  25927. return null;
  25928. }
  25929. return this._vertexBuffers[kind];
  25930. };
  25931. Geometry.prototype.getVertexBuffers = function () {
  25932. if (!this.isReady()) {
  25933. return null;
  25934. }
  25935. return this._vertexBuffers;
  25936. };
  25937. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25938. if (!this._vertexBuffers) {
  25939. if (this._delayInfo) {
  25940. return this._delayInfo.indexOf(kind) !== -1;
  25941. }
  25942. return false;
  25943. }
  25944. return this._vertexBuffers[kind] !== undefined;
  25945. };
  25946. Geometry.prototype.getVerticesDataKinds = function () {
  25947. var result = [];
  25948. var kind;
  25949. if (!this._vertexBuffers && this._delayInfo) {
  25950. for (kind in this._delayInfo) {
  25951. result.push(kind);
  25952. }
  25953. }
  25954. else {
  25955. for (kind in this._vertexBuffers) {
  25956. result.push(kind);
  25957. }
  25958. }
  25959. return result;
  25960. };
  25961. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25962. if (this._indexBuffer) {
  25963. this._engine._releaseBuffer(this._indexBuffer);
  25964. }
  25965. this._indices = indices;
  25966. if (this._meshes.length !== 0 && this._indices) {
  25967. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25968. }
  25969. if (totalVertices !== undefined) {
  25970. this._totalVertices = totalVertices;
  25971. }
  25972. var meshes = this._meshes;
  25973. var numOfMeshes = meshes.length;
  25974. for (var index = 0; index < numOfMeshes; index++) {
  25975. meshes[index]._createGlobalSubMesh();
  25976. }
  25977. this.notifyUpdate();
  25978. };
  25979. Geometry.prototype.getTotalIndices = function () {
  25980. if (!this.isReady()) {
  25981. return 0;
  25982. }
  25983. return this._indices.length;
  25984. };
  25985. Geometry.prototype.getIndices = function (copyWhenShared) {
  25986. if (!this.isReady()) {
  25987. return null;
  25988. }
  25989. var orig = this._indices;
  25990. if (!copyWhenShared || this._meshes.length === 1) {
  25991. return orig;
  25992. }
  25993. else {
  25994. var len = orig.length;
  25995. var copy = [];
  25996. for (var i = 0; i < len; i++) {
  25997. copy.push(orig[i]);
  25998. }
  25999. return copy;
  26000. }
  26001. };
  26002. Geometry.prototype.getIndexBuffer = function () {
  26003. if (!this.isReady()) {
  26004. return null;
  26005. }
  26006. return this._indexBuffer;
  26007. };
  26008. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26009. var meshes = this._meshes;
  26010. var index = meshes.indexOf(mesh);
  26011. if (index === -1) {
  26012. return;
  26013. }
  26014. for (var kind in this._vertexBuffers) {
  26015. this._vertexBuffers[kind].dispose();
  26016. }
  26017. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26018. this._indexBuffer = null;
  26019. }
  26020. meshes.splice(index, 1);
  26021. mesh._geometry = null;
  26022. if (meshes.length === 0 && shouldDispose) {
  26023. this.dispose();
  26024. }
  26025. };
  26026. Geometry.prototype.applyToMesh = function (mesh) {
  26027. if (mesh._geometry === this) {
  26028. return;
  26029. }
  26030. var previousGeometry = mesh._geometry;
  26031. if (previousGeometry) {
  26032. previousGeometry.releaseForMesh(mesh);
  26033. }
  26034. var meshes = this._meshes;
  26035. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26036. mesh._geometry = this;
  26037. this._scene.pushGeometry(this);
  26038. meshes.push(mesh);
  26039. if (this.isReady()) {
  26040. this._applyToMesh(mesh);
  26041. }
  26042. else {
  26043. mesh._boundingInfo = this._boundingInfo;
  26044. }
  26045. };
  26046. Geometry.prototype._applyToMesh = function (mesh) {
  26047. var numOfMeshes = this._meshes.length;
  26048. // vertexBuffers
  26049. for (var kind in this._vertexBuffers) {
  26050. if (numOfMeshes === 1) {
  26051. this._vertexBuffers[kind].create();
  26052. }
  26053. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26054. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26055. mesh._resetPointsArrayCache();
  26056. if (!this._extend) {
  26057. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26058. }
  26059. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26060. mesh._createGlobalSubMesh();
  26061. //bounding info was just created again, world matrix should be applied again.
  26062. mesh._updateBoundingInfo();
  26063. }
  26064. }
  26065. // indexBuffer
  26066. if (numOfMeshes === 1 && this._indices) {
  26067. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26068. }
  26069. if (this._indexBuffer) {
  26070. this._indexBuffer.references = numOfMeshes;
  26071. }
  26072. };
  26073. Geometry.prototype.notifyUpdate = function (kind) {
  26074. if (this.onGeometryUpdated) {
  26075. this.onGeometryUpdated(this, kind);
  26076. }
  26077. };
  26078. Geometry.prototype.load = function (scene, onLoaded) {
  26079. var _this = this;
  26080. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26081. return;
  26082. }
  26083. if (this.isReady()) {
  26084. if (onLoaded) {
  26085. onLoaded();
  26086. }
  26087. return;
  26088. }
  26089. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26090. scene._addPendingData(this);
  26091. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26092. _this._delayLoadingFunction(JSON.parse(data), _this);
  26093. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26094. _this._delayInfo = [];
  26095. scene._removePendingData(_this);
  26096. var meshes = _this._meshes;
  26097. var numOfMeshes = meshes.length;
  26098. for (var index = 0; index < numOfMeshes; index++) {
  26099. _this._applyToMesh(meshes[index]);
  26100. }
  26101. if (onLoaded) {
  26102. onLoaded();
  26103. }
  26104. }, function () { }, scene.database);
  26105. };
  26106. Geometry.prototype.isDisposed = function () {
  26107. return this._isDisposed;
  26108. };
  26109. Geometry.prototype.dispose = function () {
  26110. var meshes = this._meshes;
  26111. var numOfMeshes = meshes.length;
  26112. var index;
  26113. for (index = 0; index < numOfMeshes; index++) {
  26114. this.releaseForMesh(meshes[index]);
  26115. }
  26116. this._meshes = [];
  26117. for (var kind in this._vertexBuffers) {
  26118. this._vertexBuffers[kind].dispose();
  26119. }
  26120. this._vertexBuffers = [];
  26121. this._totalVertices = 0;
  26122. if (this._indexBuffer) {
  26123. this._engine._releaseBuffer(this._indexBuffer);
  26124. }
  26125. this._indexBuffer = null;
  26126. this._indices = [];
  26127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26128. this.delayLoadingFile = null;
  26129. this._delayLoadingFunction = null;
  26130. this._delayInfo = [];
  26131. this._boundingInfo = null;
  26132. this._scene.removeGeometry(this);
  26133. this._isDisposed = true;
  26134. };
  26135. Geometry.prototype.copy = function (id) {
  26136. var vertexData = new BABYLON.VertexData();
  26137. vertexData.indices = [];
  26138. var indices = this.getIndices();
  26139. for (var index = 0; index < indices.length; index++) {
  26140. vertexData.indices.push(indices[index]);
  26141. }
  26142. var updatable = false;
  26143. var stopChecking = false;
  26144. var kind;
  26145. for (kind in this._vertexBuffers) {
  26146. // using slice() to make a copy of the array and not just reference it
  26147. var data = this.getVerticesData(kind);
  26148. if (data instanceof Float32Array) {
  26149. vertexData.set(new Float32Array(data), kind);
  26150. }
  26151. else {
  26152. vertexData.set(data.slice(0), kind);
  26153. }
  26154. if (!stopChecking) {
  26155. updatable = this.getVertexBuffer(kind).isUpdatable();
  26156. stopChecking = !updatable;
  26157. }
  26158. }
  26159. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26160. geometry.delayLoadState = this.delayLoadState;
  26161. geometry.delayLoadingFile = this.delayLoadingFile;
  26162. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26163. for (kind in this._delayInfo) {
  26164. geometry._delayInfo = geometry._delayInfo || [];
  26165. geometry._delayInfo.push(kind);
  26166. }
  26167. // Bounding info
  26168. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26169. return geometry;
  26170. };
  26171. // Statics
  26172. Geometry.ExtractFromMesh = function (mesh, id) {
  26173. var geometry = mesh._geometry;
  26174. if (!geometry) {
  26175. return null;
  26176. }
  26177. return geometry.copy(id);
  26178. };
  26179. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26180. // be aware Math.random() could cause collisions
  26181. Geometry.RandomId = function () {
  26182. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26183. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26184. return v.toString(16);
  26185. });
  26186. };
  26187. return Geometry;
  26188. })();
  26189. BABYLON.Geometry = Geometry;
  26190. /////// Primitives //////////////////////////////////////////////
  26191. var Geometry;
  26192. (function (Geometry) {
  26193. var Primitives;
  26194. (function (Primitives) {
  26195. /// Abstract class
  26196. var _Primitive = (function (_super) {
  26197. __extends(_Primitive, _super);
  26198. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26199. this._beingRegenerated = true;
  26200. this._canBeRegenerated = canBeRegenerated;
  26201. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26202. this._beingRegenerated = false;
  26203. }
  26204. _Primitive.prototype.canBeRegenerated = function () {
  26205. return this._canBeRegenerated;
  26206. };
  26207. _Primitive.prototype.regenerate = function () {
  26208. if (!this._canBeRegenerated) {
  26209. return;
  26210. }
  26211. this._beingRegenerated = true;
  26212. this.setAllVerticesData(this._regenerateVertexData(), false);
  26213. this._beingRegenerated = false;
  26214. };
  26215. _Primitive.prototype.asNewGeometry = function (id) {
  26216. return _super.prototype.copy.call(this, id);
  26217. };
  26218. // overrides
  26219. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26220. if (!this._beingRegenerated) {
  26221. return;
  26222. }
  26223. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26224. };
  26225. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26226. if (!this._beingRegenerated) {
  26227. return;
  26228. }
  26229. _super.prototype.setVerticesData.call(this, kind, data, false);
  26230. };
  26231. // to override
  26232. // protected
  26233. _Primitive.prototype._regenerateVertexData = function () {
  26234. throw new Error("Abstract method");
  26235. };
  26236. _Primitive.prototype.copy = function (id) {
  26237. throw new Error("Must be overriden in sub-classes.");
  26238. };
  26239. return _Primitive;
  26240. })(Geometry);
  26241. Primitives._Primitive = _Primitive;
  26242. var Ribbon = (function (_super) {
  26243. __extends(Ribbon, _super);
  26244. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26245. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26246. this.pathArray = pathArray;
  26247. this.closeArray = closeArray;
  26248. this.closePath = closePath;
  26249. this.offset = offset;
  26250. this.side = side;
  26251. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26252. }
  26253. Ribbon.prototype._regenerateVertexData = function () {
  26254. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26255. };
  26256. Ribbon.prototype.copy = function (id) {
  26257. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26258. };
  26259. return Ribbon;
  26260. })(_Primitive);
  26261. Primitives.Ribbon = Ribbon;
  26262. var Box = (function (_super) {
  26263. __extends(Box, _super);
  26264. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26266. this.size = size;
  26267. this.side = side;
  26268. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26269. }
  26270. Box.prototype._regenerateVertexData = function () {
  26271. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26272. };
  26273. Box.prototype.copy = function (id) {
  26274. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26275. };
  26276. return Box;
  26277. })(_Primitive);
  26278. Primitives.Box = Box;
  26279. var Sphere = (function (_super) {
  26280. __extends(Sphere, _super);
  26281. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26282. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26283. this.segments = segments;
  26284. this.diameter = diameter;
  26285. this.side = side;
  26286. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26287. }
  26288. Sphere.prototype._regenerateVertexData = function () {
  26289. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26290. };
  26291. Sphere.prototype.copy = function (id) {
  26292. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26293. };
  26294. return Sphere;
  26295. })(_Primitive);
  26296. Primitives.Sphere = Sphere;
  26297. var Disc = (function (_super) {
  26298. __extends(Disc, _super);
  26299. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26300. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26301. this.radius = radius;
  26302. this.tessellation = tessellation;
  26303. this.side = side;
  26304. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26305. }
  26306. Disc.prototype._regenerateVertexData = function () {
  26307. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26308. };
  26309. Disc.prototype.copy = function (id) {
  26310. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26311. };
  26312. return Disc;
  26313. })(_Primitive);
  26314. Primitives.Disc = Disc;
  26315. var Cylinder = (function (_super) {
  26316. __extends(Cylinder, _super);
  26317. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26318. if (subdivisions === void 0) { subdivisions = 1; }
  26319. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26320. this.height = height;
  26321. this.diameterTop = diameterTop;
  26322. this.diameterBottom = diameterBottom;
  26323. this.tessellation = tessellation;
  26324. this.subdivisions = subdivisions;
  26325. this.side = side;
  26326. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26327. }
  26328. Cylinder.prototype._regenerateVertexData = function () {
  26329. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26330. };
  26331. Cylinder.prototype.copy = function (id) {
  26332. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26333. };
  26334. return Cylinder;
  26335. })(_Primitive);
  26336. Primitives.Cylinder = Cylinder;
  26337. var Torus = (function (_super) {
  26338. __extends(Torus, _super);
  26339. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26341. this.diameter = diameter;
  26342. this.thickness = thickness;
  26343. this.tessellation = tessellation;
  26344. this.side = side;
  26345. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26346. }
  26347. Torus.prototype._regenerateVertexData = function () {
  26348. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26349. };
  26350. Torus.prototype.copy = function (id) {
  26351. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26352. };
  26353. return Torus;
  26354. })(_Primitive);
  26355. Primitives.Torus = Torus;
  26356. var Ground = (function (_super) {
  26357. __extends(Ground, _super);
  26358. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26359. this.width = width;
  26360. this.height = height;
  26361. this.subdivisions = subdivisions;
  26362. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26363. }
  26364. Ground.prototype._regenerateVertexData = function () {
  26365. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26366. };
  26367. Ground.prototype.copy = function (id) {
  26368. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26369. };
  26370. return Ground;
  26371. })(_Primitive);
  26372. Primitives.Ground = Ground;
  26373. var TiledGround = (function (_super) {
  26374. __extends(TiledGround, _super);
  26375. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26376. this.xmin = xmin;
  26377. this.zmin = zmin;
  26378. this.xmax = xmax;
  26379. this.zmax = zmax;
  26380. this.subdivisions = subdivisions;
  26381. this.precision = precision;
  26382. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26383. }
  26384. TiledGround.prototype._regenerateVertexData = function () {
  26385. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26386. };
  26387. TiledGround.prototype.copy = function (id) {
  26388. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26389. };
  26390. return TiledGround;
  26391. })(_Primitive);
  26392. Primitives.TiledGround = TiledGround;
  26393. var Plane = (function (_super) {
  26394. __extends(Plane, _super);
  26395. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26396. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26397. this.size = size;
  26398. this.side = side;
  26399. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26400. }
  26401. Plane.prototype._regenerateVertexData = function () {
  26402. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26403. };
  26404. Plane.prototype.copy = function (id) {
  26405. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26406. };
  26407. return Plane;
  26408. })(_Primitive);
  26409. Primitives.Plane = Plane;
  26410. var TorusKnot = (function (_super) {
  26411. __extends(TorusKnot, _super);
  26412. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26413. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26414. this.radius = radius;
  26415. this.tube = tube;
  26416. this.radialSegments = radialSegments;
  26417. this.tubularSegments = tubularSegments;
  26418. this.p = p;
  26419. this.q = q;
  26420. this.side = side;
  26421. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26422. }
  26423. TorusKnot.prototype._regenerateVertexData = function () {
  26424. 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 });
  26425. };
  26426. TorusKnot.prototype.copy = function (id) {
  26427. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26428. };
  26429. return TorusKnot;
  26430. })(_Primitive);
  26431. Primitives.TorusKnot = TorusKnot;
  26432. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26433. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26434. })(BABYLON || (BABYLON = {}));
  26435. var BABYLON;
  26436. (function (BABYLON) {
  26437. var GroundMesh = (function (_super) {
  26438. __extends(GroundMesh, _super);
  26439. function GroundMesh(name, scene) {
  26440. _super.call(this, name, scene);
  26441. this.generateOctree = false;
  26442. this._worldInverse = new BABYLON.Matrix();
  26443. }
  26444. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26445. get: function () {
  26446. return this._subdivisions;
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26452. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26453. this._subdivisions = chunksCount;
  26454. this.subdivide(this._subdivisions);
  26455. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26456. };
  26457. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26458. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26459. this.getWorldMatrix().invertToRef(this._worldInverse);
  26460. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26461. var pickInfo = this.intersects(ray);
  26462. if (pickInfo.hit) {
  26463. return pickInfo.pickedPoint.y;
  26464. }
  26465. return 0;
  26466. };
  26467. return GroundMesh;
  26468. })(BABYLON.Mesh);
  26469. BABYLON.GroundMesh = GroundMesh;
  26470. })(BABYLON || (BABYLON = {}));
  26471. var BABYLON;
  26472. (function (BABYLON) {
  26473. var LinesMesh = (function (_super) {
  26474. __extends(LinesMesh, _super);
  26475. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26476. if (parent === void 0) { parent = null; }
  26477. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26478. this.color = new BABYLON.Color3(1, 1, 1);
  26479. this.alpha = 1;
  26480. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26481. attributes: ["position"],
  26482. uniforms: ["worldViewProjection", "color"],
  26483. needAlphaBlending: true
  26484. });
  26485. }
  26486. Object.defineProperty(LinesMesh.prototype, "material", {
  26487. get: function () {
  26488. return this._colorShader;
  26489. },
  26490. enumerable: true,
  26491. configurable: true
  26492. });
  26493. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26494. get: function () {
  26495. return false;
  26496. },
  26497. enumerable: true,
  26498. configurable: true
  26499. });
  26500. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26501. get: function () {
  26502. return false;
  26503. },
  26504. enumerable: true,
  26505. configurable: true
  26506. });
  26507. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26508. var engine = this.getScene().getEngine();
  26509. var indexToBind = this._geometry.getIndexBuffer();
  26510. // VBOs
  26511. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26512. // Color
  26513. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26514. };
  26515. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26516. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26517. return;
  26518. }
  26519. var engine = this.getScene().getEngine();
  26520. // Draw order
  26521. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26522. };
  26523. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26524. return null;
  26525. };
  26526. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26527. this._colorShader.dispose();
  26528. _super.prototype.dispose.call(this, doNotRecurse);
  26529. };
  26530. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26531. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26532. };
  26533. return LinesMesh;
  26534. })(BABYLON.Mesh);
  26535. BABYLON.LinesMesh = LinesMesh;
  26536. })(BABYLON || (BABYLON = {}));
  26537. var BABYLON;
  26538. (function (BABYLON) {
  26539. var DebugLayer = (function () {
  26540. function DebugLayer(scene) {
  26541. var _this = this;
  26542. this._transformationMatrix = BABYLON.Matrix.Identity();
  26543. this._enabled = false;
  26544. this._labelsEnabled = false;
  26545. this._displayStatistics = true;
  26546. this._displayTree = false;
  26547. this._displayLogs = false;
  26548. this._identityMatrix = BABYLON.Matrix.Identity();
  26549. this.axisRatio = 0.02;
  26550. this.accentColor = "orange";
  26551. this._scene = scene;
  26552. this._syncPositions = function () {
  26553. var engine = _this._scene.getEngine();
  26554. var canvasRect = engine.getRenderingCanvasClientRect();
  26555. if (_this._showUI) {
  26556. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26557. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26558. _this._statsDiv.style.width = "400px";
  26559. _this._statsDiv.style.height = "auto";
  26560. _this._statsSubsetDiv.style.maxHeight = "240px";
  26561. _this._optionsDiv.style.left = "0px";
  26562. _this._optionsDiv.style.top = "10px";
  26563. _this._optionsDiv.style.width = "200px";
  26564. _this._optionsDiv.style.height = "auto";
  26565. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26566. _this._logDiv.style.left = "0px";
  26567. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26568. _this._logDiv.style.width = "600px";
  26569. _this._logDiv.style.height = "160px";
  26570. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26571. _this._treeDiv.style.top = "10px";
  26572. _this._treeDiv.style.width = "300px";
  26573. _this._treeDiv.style.height = "auto";
  26574. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26575. }
  26576. _this._globalDiv.style.left = canvasRect.left + "px";
  26577. _this._globalDiv.style.top = canvasRect.top + "px";
  26578. _this._drawingCanvas.style.left = "0px";
  26579. _this._drawingCanvas.style.top = "0px";
  26580. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26581. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26582. var devicePixelRatio = window.devicePixelRatio || 1;
  26583. var context = _this._drawingContext;
  26584. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26585. context.mozBackingStorePixelRatio ||
  26586. context.msBackingStorePixelRatio ||
  26587. context.oBackingStorePixelRatio ||
  26588. context.backingStorePixelRatio || 1;
  26589. _this._ratio = devicePixelRatio / backingStoreRatio;
  26590. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26591. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26592. };
  26593. this._onCanvasClick = function (evt) {
  26594. _this._clickPosition = {
  26595. x: evt.clientX * _this._ratio,
  26596. y: evt.clientY * _this._ratio
  26597. };
  26598. };
  26599. this._syncUI = function () {
  26600. if (_this._showUI) {
  26601. if (_this._displayStatistics) {
  26602. _this._displayStats();
  26603. _this._statsDiv.style.display = "";
  26604. }
  26605. else {
  26606. _this._statsDiv.style.display = "none";
  26607. }
  26608. if (_this._displayLogs) {
  26609. _this._logDiv.style.display = "";
  26610. }
  26611. else {
  26612. _this._logDiv.style.display = "none";
  26613. }
  26614. if (_this._displayTree) {
  26615. _this._treeDiv.style.display = "";
  26616. if (_this._needToRefreshMeshesTree) {
  26617. _this._needToRefreshMeshesTree = false;
  26618. _this._refreshMeshesTreeContent();
  26619. }
  26620. }
  26621. else {
  26622. _this._treeDiv.style.display = "none";
  26623. }
  26624. }
  26625. };
  26626. this._syncData = function () {
  26627. if (_this._labelsEnabled || !_this._showUI) {
  26628. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26629. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26630. var engine = _this._scene.getEngine();
  26631. var viewport = _this._camera.viewport;
  26632. var globalViewport = viewport.toGlobal(engine);
  26633. // Meshes
  26634. var meshes = _this._camera.getActiveMeshes();
  26635. var index;
  26636. var projectedPosition;
  26637. for (index = 0; index < meshes.length; index++) {
  26638. var mesh = meshes.data[index];
  26639. var position = mesh.getBoundingInfo().boundingSphere.center;
  26640. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26641. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26642. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26643. }
  26644. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26645. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26646. }
  26647. }
  26648. // Cameras
  26649. var cameras = _this._scene.cameras;
  26650. for (index = 0; index < cameras.length; index++) {
  26651. var camera = cameras[index];
  26652. if (camera === _this._camera) {
  26653. continue;
  26654. }
  26655. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26656. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26657. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26658. _this._camera.detachControl(engine.getRenderingCanvas());
  26659. _this._camera = camera;
  26660. _this._camera.attachControl(engine.getRenderingCanvas());
  26661. }, function () { return "purple"; });
  26662. }
  26663. }
  26664. // Lights
  26665. var lights = _this._scene.lights;
  26666. for (index = 0; index < lights.length; index++) {
  26667. var light = lights[index];
  26668. if (light.position) {
  26669. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26670. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26671. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26672. light.setEnabled(!light.isEnabled());
  26673. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26674. }
  26675. }
  26676. }
  26677. }
  26678. _this._clickPosition = undefined;
  26679. };
  26680. }
  26681. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26682. while (this._treeSubsetDiv.hasChildNodes()) {
  26683. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26684. }
  26685. // Add meshes
  26686. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26687. sortedArray.sort(function (a, b) {
  26688. if (a.name === b.name) {
  26689. return 0;
  26690. }
  26691. return (a.name > b.name) ? 1 : -1;
  26692. });
  26693. for (var index = 0; index < sortedArray.length; index++) {
  26694. var mesh = sortedArray[index];
  26695. if (!mesh.isEnabled()) {
  26696. continue;
  26697. }
  26698. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26699. m.isVisible = element.checked;
  26700. }, mesh);
  26701. }
  26702. };
  26703. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26704. this._drawingContext.beginPath();
  26705. this._drawingContext.moveTo(zero.x, zero.y);
  26706. this._drawingContext.lineTo(unit.x, unit.y);
  26707. this._drawingContext.strokeStyle = color;
  26708. this._drawingContext.lineWidth = 4;
  26709. this._drawingContext.stroke();
  26710. this._drawingContext.font = "normal 14px Segoe UI";
  26711. this._drawingContext.fillStyle = color;
  26712. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26713. };
  26714. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26715. var position = mesh.getBoundingInfo().boundingSphere.center;
  26716. var worldMatrix = mesh.getWorldMatrix();
  26717. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26718. var unit = (unprojectedVector.subtract(position)).length();
  26719. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26720. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26721. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26722. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26723. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26724. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26725. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26726. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26727. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26728. };
  26729. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26730. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26731. this._drawingContext.font = "normal 12px Segoe UI";
  26732. var textMetrics = this._drawingContext.measureText(text);
  26733. var centerX = projectedPosition.x - textMetrics.width / 2;
  26734. var centerY = projectedPosition.y;
  26735. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26736. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26737. onClick();
  26738. }
  26739. this._drawingContext.beginPath();
  26740. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26741. this._drawingContext.fillStyle = getFillStyle();
  26742. this._drawingContext.globalAlpha = 0.5;
  26743. this._drawingContext.fill();
  26744. this._drawingContext.globalAlpha = 1.0;
  26745. this._drawingContext.strokeStyle = '#FFFFFF';
  26746. this._drawingContext.lineWidth = 1;
  26747. this._drawingContext.stroke();
  26748. this._drawingContext.fillStyle = "#FFFFFF";
  26749. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26750. this._drawingContext.beginPath();
  26751. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26752. this._drawingContext.fill();
  26753. }
  26754. };
  26755. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26756. if (!this._clickPosition) {
  26757. return false;
  26758. }
  26759. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26760. return false;
  26761. }
  26762. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26763. return false;
  26764. }
  26765. return true;
  26766. };
  26767. DebugLayer.prototype.isVisible = function () {
  26768. return this._enabled;
  26769. };
  26770. DebugLayer.prototype.hide = function () {
  26771. if (!this._enabled) {
  26772. return;
  26773. }
  26774. this._enabled = false;
  26775. var engine = this._scene.getEngine();
  26776. this._scene.unregisterBeforeRender(this._syncData);
  26777. this._scene.unregisterAfterRender(this._syncUI);
  26778. this._rootElement.removeChild(this._globalDiv);
  26779. this._scene.forceShowBoundingBoxes = false;
  26780. this._scene.forceWireframe = false;
  26781. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26782. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26783. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26784. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26785. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26786. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26787. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26788. BABYLON.StandardMaterial.LightmapEnabled = true;
  26789. this._scene.shadowsEnabled = true;
  26790. this._scene.particlesEnabled = true;
  26791. this._scene.postProcessesEnabled = true;
  26792. this._scene.collisionsEnabled = true;
  26793. this._scene.lightsEnabled = true;
  26794. this._scene.texturesEnabled = true;
  26795. this._scene.lensFlaresEnabled = true;
  26796. this._scene.proceduralTexturesEnabled = true;
  26797. this._scene.renderTargetsEnabled = true;
  26798. this._scene.probesEnabled = true;
  26799. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26800. };
  26801. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26802. if (showUI === void 0) { showUI = true; }
  26803. if (camera === void 0) { camera = null; }
  26804. if (rootElement === void 0) { rootElement = null; }
  26805. if (this._enabled) {
  26806. return;
  26807. }
  26808. this._enabled = true;
  26809. if (camera) {
  26810. this._camera = camera;
  26811. }
  26812. else {
  26813. this._camera = this._scene.activeCamera;
  26814. }
  26815. this._showUI = showUI;
  26816. var engine = this._scene.getEngine();
  26817. this._globalDiv = document.createElement("div");
  26818. this._rootElement = rootElement || document.body;
  26819. this._rootElement.appendChild(this._globalDiv);
  26820. this._generateDOMelements();
  26821. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26822. this._syncPositions();
  26823. this._scene.registerBeforeRender(this._syncData);
  26824. this._scene.registerAfterRender(this._syncUI);
  26825. };
  26826. DebugLayer.prototype._clearLabels = function () {
  26827. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26828. for (var index = 0; index < this._scene.meshes.length; index++) {
  26829. var mesh = this._scene.meshes[index];
  26830. mesh.renderOverlay = false;
  26831. }
  26832. };
  26833. DebugLayer.prototype._generateheader = function (root, text) {
  26834. var header = document.createElement("div");
  26835. header.innerHTML = text + "&nbsp;";
  26836. header.style.textAlign = "right";
  26837. header.style.width = "100%";
  26838. header.style.color = "white";
  26839. header.style.backgroundColor = "Black";
  26840. header.style.padding = "5px 5px 4px 0px";
  26841. header.style.marginLeft = "-5px";
  26842. header.style.fontWeight = "bold";
  26843. root.appendChild(header);
  26844. };
  26845. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26846. var label = document.createElement("label");
  26847. label.innerHTML = title;
  26848. label.style.color = color;
  26849. root.appendChild(label);
  26850. root.appendChild(document.createElement("br"));
  26851. };
  26852. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26853. if (tag === void 0) { tag = null; }
  26854. var label = document.createElement("label");
  26855. var boundingBoxesCheckbox = document.createElement("input");
  26856. boundingBoxesCheckbox.type = "checkbox";
  26857. boundingBoxesCheckbox.checked = initialState;
  26858. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26859. task(evt.target, tag);
  26860. });
  26861. label.appendChild(boundingBoxesCheckbox);
  26862. var container = document.createElement("span");
  26863. var leftPart = document.createElement("span");
  26864. var rightPart = document.createElement("span");
  26865. rightPart.style.cssFloat = "right";
  26866. leftPart.innerHTML = leftTitle;
  26867. rightPart.innerHTML = rightTitle;
  26868. rightPart.style.fontSize = "12px";
  26869. rightPart.style.maxWidth = "200px";
  26870. container.appendChild(leftPart);
  26871. container.appendChild(rightPart);
  26872. label.appendChild(container);
  26873. root.appendChild(label);
  26874. root.appendChild(document.createElement("br"));
  26875. };
  26876. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26877. if (tag === void 0) { tag = null; }
  26878. var label = document.createElement("label");
  26879. var checkBox = document.createElement("input");
  26880. checkBox.type = "checkbox";
  26881. checkBox.checked = initialState;
  26882. checkBox.addEventListener("change", function (evt) {
  26883. task(evt.target, tag);
  26884. });
  26885. label.appendChild(checkBox);
  26886. label.appendChild(document.createTextNode(title));
  26887. root.appendChild(label);
  26888. root.appendChild(document.createElement("br"));
  26889. };
  26890. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26891. if (tag === void 0) { tag = null; }
  26892. var button = document.createElement("button");
  26893. button.innerHTML = title;
  26894. button.style.height = "24px";
  26895. button.style.width = "150px";
  26896. button.style.marginBottom = "5px";
  26897. button.style.color = "#444444";
  26898. button.style.border = "1px solid white";
  26899. button.className = "debugLayerButton";
  26900. button.addEventListener("click", function (evt) {
  26901. task(evt.target, tag);
  26902. });
  26903. root.appendChild(button);
  26904. root.appendChild(document.createElement("br"));
  26905. };
  26906. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26907. if (tag === void 0) { tag = null; }
  26908. var label = document.createElement("label");
  26909. var boundingBoxesRadio = document.createElement("input");
  26910. boundingBoxesRadio.type = "radio";
  26911. boundingBoxesRadio.name = name;
  26912. boundingBoxesRadio.checked = initialState;
  26913. boundingBoxesRadio.addEventListener("change", function (evt) {
  26914. task(evt.target, tag);
  26915. });
  26916. label.appendChild(boundingBoxesRadio);
  26917. label.appendChild(document.createTextNode(title));
  26918. root.appendChild(label);
  26919. root.appendChild(document.createElement("br"));
  26920. };
  26921. DebugLayer.prototype._generateDOMelements = function () {
  26922. var _this = this;
  26923. this._globalDiv.id = "DebugLayer";
  26924. this._globalDiv.style.position = "absolute";
  26925. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26926. this._globalDiv.style.fontSize = "14px";
  26927. this._globalDiv.style.color = "white";
  26928. // Drawing canvas
  26929. this._drawingCanvas = document.createElement("canvas");
  26930. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26931. this._drawingCanvas.style.position = "absolute";
  26932. this._drawingCanvas.style.pointerEvents = "none";
  26933. this._drawingCanvas.style.backgroundColor = "transparent";
  26934. this._drawingContext = this._drawingCanvas.getContext("2d");
  26935. this._globalDiv.appendChild(this._drawingCanvas);
  26936. if (this._showUI) {
  26937. var background = "rgba(128, 128, 128, 0.4)";
  26938. var border = "rgb(180, 180, 180) solid 1px";
  26939. // Stats
  26940. this._statsDiv = document.createElement("div");
  26941. this._statsDiv.id = "DebugLayerStats";
  26942. this._statsDiv.style.border = border;
  26943. this._statsDiv.style.position = "absolute";
  26944. this._statsDiv.style.background = background;
  26945. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26946. this._generateheader(this._statsDiv, "STATISTICS");
  26947. this._statsSubsetDiv = document.createElement("div");
  26948. this._statsSubsetDiv.style.paddingTop = "5px";
  26949. this._statsSubsetDiv.style.paddingBottom = "5px";
  26950. this._statsSubsetDiv.style.overflowY = "auto";
  26951. this._statsDiv.appendChild(this._statsSubsetDiv);
  26952. // Tree
  26953. this._treeDiv = document.createElement("div");
  26954. this._treeDiv.id = "DebugLayerTree";
  26955. this._treeDiv.style.border = border;
  26956. this._treeDiv.style.position = "absolute";
  26957. this._treeDiv.style.background = background;
  26958. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26959. this._treeDiv.style.display = "none";
  26960. this._generateheader(this._treeDiv, "MESHES TREE");
  26961. this._treeSubsetDiv = document.createElement("div");
  26962. this._treeSubsetDiv.style.paddingTop = "5px";
  26963. this._treeSubsetDiv.style.paddingRight = "5px";
  26964. this._treeSubsetDiv.style.overflowY = "auto";
  26965. this._treeSubsetDiv.style.maxHeight = "300px";
  26966. this._treeDiv.appendChild(this._treeSubsetDiv);
  26967. this._needToRefreshMeshesTree = true;
  26968. // Logs
  26969. this._logDiv = document.createElement("div");
  26970. this._logDiv.style.border = border;
  26971. this._logDiv.id = "DebugLayerLogs";
  26972. this._logDiv.style.position = "absolute";
  26973. this._logDiv.style.background = background;
  26974. this._logDiv.style.padding = "0px 0px 0px 5px";
  26975. this._logDiv.style.display = "none";
  26976. this._generateheader(this._logDiv, "LOGS");
  26977. this._logSubsetDiv = document.createElement("div");
  26978. this._logSubsetDiv.style.height = "127px";
  26979. this._logSubsetDiv.style.paddingTop = "5px";
  26980. this._logSubsetDiv.style.overflowY = "auto";
  26981. this._logSubsetDiv.style.fontSize = "12px";
  26982. this._logSubsetDiv.style.fontFamily = "consolas";
  26983. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26984. this._logDiv.appendChild(this._logSubsetDiv);
  26985. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26986. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26987. };
  26988. // Options
  26989. this._optionsDiv = document.createElement("div");
  26990. this._optionsDiv.id = "DebugLayerOptions";
  26991. this._optionsDiv.style.border = border;
  26992. this._optionsDiv.style.position = "absolute";
  26993. this._optionsDiv.style.background = background;
  26994. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26995. this._optionsDiv.style.overflowY = "auto";
  26996. this._generateheader(this._optionsDiv, "OPTIONS");
  26997. this._optionsSubsetDiv = document.createElement("div");
  26998. this._optionsSubsetDiv.style.paddingTop = "5px";
  26999. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27000. this._optionsSubsetDiv.style.overflowY = "auto";
  27001. this._optionsSubsetDiv.style.maxHeight = "200px";
  27002. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27003. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27004. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27005. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27006. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27007. _this._displayTree = element.checked;
  27008. _this._needToRefreshMeshesTree = true;
  27009. });
  27010. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27011. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27012. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27013. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27014. _this._labelsEnabled = element.checked;
  27015. if (!_this._labelsEnabled) {
  27016. _this._clearLabels();
  27017. }
  27018. });
  27019. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27020. if (element.checked) {
  27021. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27022. }
  27023. else {
  27024. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27025. }
  27026. });
  27027. ;
  27028. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27029. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27030. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27031. if (element.checked) {
  27032. _this._scene.forceWireframe = false;
  27033. _this._scene.forcePointsCloud = false;
  27034. }
  27035. });
  27036. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27037. if (element.checked) {
  27038. _this._scene.forceWireframe = true;
  27039. _this._scene.forcePointsCloud = false;
  27040. }
  27041. });
  27042. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27043. if (element.checked) {
  27044. _this._scene.forceWireframe = false;
  27045. _this._scene.forcePointsCloud = true;
  27046. }
  27047. });
  27048. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27049. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27050. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27051. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27052. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27053. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27054. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27055. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27056. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27057. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27058. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27059. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27060. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27061. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27062. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27063. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27064. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27065. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27066. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27067. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27068. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27069. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27070. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27071. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27072. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27073. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27074. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27075. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27076. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27077. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27078. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27079. if (element.checked) {
  27080. _this._scene.headphone = true;
  27081. }
  27082. });
  27083. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27084. if (element.checked) {
  27085. _this._scene.headphone = false;
  27086. }
  27087. });
  27088. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27089. _this._scene.audioEnabled = !element.checked;
  27090. });
  27091. }
  27092. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27093. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27094. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27095. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27096. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  27097. if (_this._camera) {
  27098. console.log(_this._camera);
  27099. }
  27100. else {
  27101. console.warn("No camera defined, or debug layer created before camera creation!");
  27102. }
  27103. });
  27104. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27105. this._globalDiv.appendChild(this._statsDiv);
  27106. this._globalDiv.appendChild(this._logDiv);
  27107. this._globalDiv.appendChild(this._optionsDiv);
  27108. this._globalDiv.appendChild(this._treeDiv);
  27109. }
  27110. };
  27111. DebugLayer.prototype._displayStats = function () {
  27112. var scene = this._scene;
  27113. var engine = scene.getEngine();
  27114. var glInfo = engine.getGlInfo();
  27115. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27116. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27117. + "<b>Count</b><br>"
  27118. + "Total meshes: " + scene.meshes.length + "<br>"
  27119. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27120. + "Total materials: " + scene.materials.length + "<br>"
  27121. + "Total textures: " + scene.textures.length + "<br>"
  27122. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27123. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27124. + "Active bones: " + scene.getActiveBones() + "<br>"
  27125. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27126. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27127. + "<b>Duration</b><br>"
  27128. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27129. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27130. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27131. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27132. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27133. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27134. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27135. + "</div>"
  27136. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27137. + "<b>Extensions</b><br>"
  27138. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27139. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27140. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27141. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27142. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27143. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  27144. + "<b>Caps.</b><br>"
  27145. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27146. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27147. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27148. + "</div><br>"
  27149. + "<b>Info</b><br>"
  27150. + glInfo.version + "<br>"
  27151. + glInfo.renderer + "<br>";
  27152. if (this.customStatsFunction) {
  27153. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27154. }
  27155. };
  27156. return DebugLayer;
  27157. })();
  27158. BABYLON.DebugLayer = DebugLayer;
  27159. })(BABYLON || (BABYLON = {}));
  27160. var BABYLON;
  27161. (function (BABYLON) {
  27162. var DefaultLoadingScreen = (function () {
  27163. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27164. var _this = this;
  27165. if (_loadingText === void 0) { _loadingText = ""; }
  27166. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27167. this._renderingCanvas = _renderingCanvas;
  27168. this._loadingText = _loadingText;
  27169. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27170. // Resize
  27171. this._resizeLoadingUI = function () {
  27172. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27173. _this._loadingDiv.style.position = "absolute";
  27174. _this._loadingDiv.style.left = canvasRect.left + "px";
  27175. _this._loadingDiv.style.top = canvasRect.top + "px";
  27176. _this._loadingDiv.style.width = canvasRect.width + "px";
  27177. _this._loadingDiv.style.height = canvasRect.height + "px";
  27178. };
  27179. }
  27180. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27181. var _this = this;
  27182. this._loadingDiv = document.createElement("div");
  27183. this._loadingDiv.id = "babylonjsLoadingDiv";
  27184. this._loadingDiv.style.opacity = "0";
  27185. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27186. // Loading text
  27187. this._loadingTextDiv = document.createElement("div");
  27188. this._loadingTextDiv.style.position = "absolute";
  27189. this._loadingTextDiv.style.left = "0";
  27190. this._loadingTextDiv.style.top = "50%";
  27191. this._loadingTextDiv.style.marginTop = "80px";
  27192. this._loadingTextDiv.style.width = "100%";
  27193. this._loadingTextDiv.style.height = "20px";
  27194. this._loadingTextDiv.style.fontFamily = "Arial";
  27195. this._loadingTextDiv.style.fontSize = "14px";
  27196. this._loadingTextDiv.style.color = "white";
  27197. this._loadingTextDiv.style.textAlign = "center";
  27198. this._loadingTextDiv.innerHTML = "Loading";
  27199. this._loadingDiv.appendChild(this._loadingTextDiv);
  27200. //set the predefined text
  27201. this._loadingTextDiv.innerHTML = this._loadingText;
  27202. // Loading img
  27203. var imgBack = new Image();
  27204. 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==";
  27205. imgBack.style.position = "absolute";
  27206. imgBack.style.left = "50%";
  27207. imgBack.style.top = "50%";
  27208. imgBack.style.marginLeft = "-50px";
  27209. imgBack.style.marginTop = "-50px";
  27210. imgBack.style.transition = "transform 1.0s ease";
  27211. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27212. var deg = 360;
  27213. var onTransitionEnd = function () {
  27214. deg += 360;
  27215. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27216. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27217. };
  27218. imgBack.addEventListener("transitionend", onTransitionEnd);
  27219. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27220. this._loadingDiv.appendChild(imgBack);
  27221. // front image
  27222. var imgFront = new Image();
  27223. 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=";
  27224. imgFront.style.position = "absolute";
  27225. imgFront.style.left = "50%";
  27226. imgFront.style.top = "50%";
  27227. imgFront.style.marginLeft = "-50px";
  27228. imgFront.style.marginTop = "-50px";
  27229. this._loadingDiv.appendChild(imgFront);
  27230. this._resizeLoadingUI();
  27231. window.addEventListener("resize", this._resizeLoadingUI);
  27232. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27233. document.body.appendChild(this._loadingDiv);
  27234. setTimeout(function () {
  27235. _this._loadingDiv.style.opacity = "1";
  27236. imgBack.style.transform = "rotateZ(360deg)";
  27237. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27238. }, 0);
  27239. };
  27240. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27241. var _this = this;
  27242. if (!this._loadingDiv) {
  27243. return;
  27244. }
  27245. var onTransitionEnd = function () {
  27246. if (!_this._loadingDiv) {
  27247. return;
  27248. }
  27249. document.body.removeChild(_this._loadingDiv);
  27250. window.removeEventListener("resize", _this._resizeLoadingUI);
  27251. _this._loadingDiv = null;
  27252. };
  27253. this._loadingDiv.style.opacity = "0";
  27254. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27255. };
  27256. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27257. set: function (text) {
  27258. this._loadingText = text;
  27259. if (this._loadingTextDiv) {
  27260. this._loadingTextDiv.innerHTML = this._loadingText;
  27261. }
  27262. },
  27263. enumerable: true,
  27264. configurable: true
  27265. });
  27266. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27267. get: function () {
  27268. return this._loadingDivBackgroundColor;
  27269. },
  27270. set: function (color) {
  27271. this._loadingDivBackgroundColor = color;
  27272. if (!this._loadingDiv) {
  27273. return;
  27274. }
  27275. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. return DefaultLoadingScreen;
  27281. })();
  27282. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27283. })(BABYLON || (BABYLON = {}));
  27284. var BABYLON;
  27285. (function (BABYLON) {
  27286. var SIMDVector3 = (function () {
  27287. function SIMDVector3() {
  27288. }
  27289. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27290. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27291. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27292. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27293. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27294. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27295. 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));
  27296. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27297. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27298. };
  27299. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27300. var v0 = SIMD.float32x4.splat(x);
  27301. var v1 = SIMD.float32x4.splat(y);
  27302. var v2 = SIMD.float32x4.splat(z);
  27303. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27304. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27305. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27306. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27307. 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));
  27308. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27309. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27310. };
  27311. return SIMDVector3;
  27312. })();
  27313. BABYLON.SIMDVector3 = SIMDVector3;
  27314. var SIMDMatrix = (function () {
  27315. function SIMDMatrix() {
  27316. }
  27317. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27318. if (offset === void 0) { offset = 0; }
  27319. var tm = this.m;
  27320. var om = other.m;
  27321. var om0 = SIMD.float32x4.load(om, 0);
  27322. var om1 = SIMD.float32x4.load(om, 4);
  27323. var om2 = SIMD.float32x4.load(om, 8);
  27324. var om3 = SIMD.float32x4.load(om, 12);
  27325. var tm0 = SIMD.float32x4.load(tm, 0);
  27326. 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)))));
  27327. var tm1 = SIMD.float32x4.load(tm, 4);
  27328. 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)))));
  27329. var tm2 = SIMD.float32x4.load(tm, 8);
  27330. 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)))));
  27331. var tm3 = SIMD.float32x4.load(tm, 12);
  27332. 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)))));
  27333. };
  27334. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27335. var src = this.m;
  27336. var dest = other.m;
  27337. var row0, row1, row2, row3;
  27338. var tmp1;
  27339. var minor0, minor1, minor2, minor3;
  27340. var det;
  27341. // Load the 4 rows
  27342. var src0 = SIMD.float32x4.load(src, 0);
  27343. var src1 = SIMD.float32x4.load(src, 4);
  27344. var src2 = SIMD.float32x4.load(src, 8);
  27345. var src3 = SIMD.float32x4.load(src, 12);
  27346. // Transpose the source matrix. Sort of. Not a true transpose operation
  27347. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27348. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27349. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27350. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27351. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27352. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27353. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27354. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27355. // This is a true transposition, but it will lead to an incorrect result
  27356. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27357. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27358. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27359. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27360. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27361. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27362. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27363. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27364. // ----
  27365. tmp1 = SIMD.float32x4.mul(row2, row3);
  27366. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27367. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27368. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27369. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27370. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27371. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27372. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27373. // ----
  27374. tmp1 = SIMD.float32x4.mul(row1, row2);
  27375. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27376. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27377. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27378. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27379. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27380. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27381. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27382. // ----
  27383. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27384. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27385. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27386. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27387. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27388. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27389. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27390. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27391. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27392. // ----
  27393. tmp1 = SIMD.float32x4.mul(row0, row1);
  27394. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27395. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27396. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27397. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27398. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27399. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27400. // ----
  27401. tmp1 = SIMD.float32x4.mul(row0, row3);
  27402. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27403. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27404. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27405. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27406. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27407. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27408. // ----
  27409. tmp1 = SIMD.float32x4.mul(row0, row2);
  27410. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27411. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27412. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27413. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27414. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27415. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27416. // Compute determinant
  27417. det = SIMD.float32x4.mul(row0, minor0);
  27418. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27419. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27420. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27421. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27422. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27423. // These shuffles aren't necessary if the faulty transposition is done
  27424. // up at the top of this function.
  27425. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27426. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27427. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27428. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27429. // Compute final values by multiplying with 1/det
  27430. minor0 = SIMD.float32x4.mul(det, minor0);
  27431. minor1 = SIMD.float32x4.mul(det, minor1);
  27432. minor2 = SIMD.float32x4.mul(det, minor2);
  27433. minor3 = SIMD.float32x4.mul(det, minor3);
  27434. SIMD.float32x4.store(dest, 0, minor0);
  27435. SIMD.float32x4.store(dest, 4, minor1);
  27436. SIMD.float32x4.store(dest, 8, minor2);
  27437. SIMD.float32x4.store(dest, 12, minor3);
  27438. return this;
  27439. };
  27440. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27441. var out = result.m;
  27442. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27443. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27444. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27445. // cc.kmVec3Subtract(f, pCenter, pEye);
  27446. var f = SIMD.float32x4.sub(center, eye);
  27447. // cc.kmVec3Normalize(f, f);
  27448. var tmp = SIMD.float32x4.mul(f, f);
  27449. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27450. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27451. // cc.kmVec3Assign(up, pUp);
  27452. // cc.kmVec3Normalize(up, up);
  27453. tmp = SIMD.float32x4.mul(up, up);
  27454. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27455. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27456. // cc.kmVec3Cross(s, f, up);
  27457. 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)));
  27458. // cc.kmVec3Normalize(s, s);
  27459. tmp = SIMD.float32x4.mul(s, s);
  27460. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27461. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27462. // cc.kmVec3Cross(u, s, f);
  27463. 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)));
  27464. // cc.kmVec3Normalize(s, s);
  27465. tmp = SIMD.float32x4.mul(s, s);
  27466. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27467. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27468. var zero = SIMD.float32x4.splat(0.0);
  27469. s = SIMD.float32x4.neg(s);
  27470. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27471. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27472. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27473. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27474. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27475. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27476. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27477. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27478. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27479. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27480. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27481. var b3 = SIMD.float32x4.neg(eye);
  27482. b3 = SIMD.float32x4.withW(b3, 1.0);
  27483. 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)))));
  27484. 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)))));
  27485. 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)))));
  27486. 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)))));
  27487. };
  27488. return SIMDMatrix;
  27489. })();
  27490. BABYLON.SIMDMatrix = SIMDMatrix;
  27491. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27492. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27493. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27494. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27495. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27496. var SIMDHelper = (function () {
  27497. function SIMDHelper() {
  27498. }
  27499. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27500. get: function () {
  27501. return SIMDHelper._isEnabled;
  27502. },
  27503. enumerable: true,
  27504. configurable: true
  27505. });
  27506. SIMDHelper.DisableSIMD = function () {
  27507. // Replace functions
  27508. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27509. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27510. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27511. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27513. SIMDHelper._isEnabled = false;
  27514. };
  27515. SIMDHelper.EnableSIMD = function () {
  27516. if (window.SIMD === undefined) {
  27517. return;
  27518. }
  27519. // Replace functions
  27520. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27521. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27522. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27523. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27524. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27525. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27526. get: function () { return this._data[0]; },
  27527. set: function (value) {
  27528. if (!this._data) {
  27529. this._data = new Float32Array(3);
  27530. }
  27531. this._data[0] = value;
  27532. }
  27533. });
  27534. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27535. get: function () { return this._data[1]; },
  27536. set: function (value) {
  27537. this._data[1] = value;
  27538. }
  27539. });
  27540. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27541. get: function () { return this._data[2]; },
  27542. set: function (value) {
  27543. this._data[2] = value;
  27544. }
  27545. });
  27546. SIMDHelper._isEnabled = true;
  27547. };
  27548. SIMDHelper._isEnabled = false;
  27549. return SIMDHelper;
  27550. })();
  27551. BABYLON.SIMDHelper = SIMDHelper;
  27552. })(BABYLON || (BABYLON = {}));
  27553. var BABYLON;
  27554. (function (BABYLON) {
  27555. var ShaderMaterial = (function (_super) {
  27556. __extends(ShaderMaterial, _super);
  27557. function ShaderMaterial(name, scene, shaderPath, options) {
  27558. _super.call(this, name, scene);
  27559. this._textures = new Array();
  27560. this._floats = new Array();
  27561. this._floatsArrays = {};
  27562. this._colors3 = new Array();
  27563. this._colors4 = new Array();
  27564. this._vectors2 = new Array();
  27565. this._vectors3 = new Array();
  27566. this._vectors4 = new Array();
  27567. this._matrices = new Array();
  27568. this._matrices3x3 = new Array();
  27569. this._matrices2x2 = new Array();
  27570. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27571. this._shaderPath = shaderPath;
  27572. options.needAlphaBlending = options.needAlphaBlending || false;
  27573. options.needAlphaTesting = options.needAlphaTesting || false;
  27574. options.attributes = options.attributes || ["position", "normal", "uv"];
  27575. options.uniforms = options.uniforms || ["worldViewProjection"];
  27576. options.samplers = options.samplers || [];
  27577. options.defines = options.defines || [];
  27578. this._options = options;
  27579. }
  27580. ShaderMaterial.prototype.needAlphaBlending = function () {
  27581. return this._options.needAlphaBlending;
  27582. };
  27583. ShaderMaterial.prototype.needAlphaTesting = function () {
  27584. return this._options.needAlphaTesting;
  27585. };
  27586. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27587. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27588. this._options.uniforms.push(uniformName);
  27589. }
  27590. };
  27591. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27592. if (this._options.samplers.indexOf(name) === -1) {
  27593. this._options.samplers.push(name);
  27594. }
  27595. this._textures[name] = texture;
  27596. return this;
  27597. };
  27598. ShaderMaterial.prototype.setFloat = function (name, value) {
  27599. this._checkUniform(name);
  27600. this._floats[name] = value;
  27601. return this;
  27602. };
  27603. ShaderMaterial.prototype.setFloats = function (name, value) {
  27604. this._checkUniform(name);
  27605. this._floatsArrays[name] = value;
  27606. return this;
  27607. };
  27608. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27609. this._checkUniform(name);
  27610. this._colors3[name] = value;
  27611. return this;
  27612. };
  27613. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27614. this._checkUniform(name);
  27615. this._colors4[name] = value;
  27616. return this;
  27617. };
  27618. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27619. this._checkUniform(name);
  27620. this._vectors2[name] = value;
  27621. return this;
  27622. };
  27623. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27624. this._checkUniform(name);
  27625. this._vectors3[name] = value;
  27626. return this;
  27627. };
  27628. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27629. this._checkUniform(name);
  27630. this._vectors4[name] = value;
  27631. return this;
  27632. };
  27633. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27634. this._checkUniform(name);
  27635. this._matrices[name] = value;
  27636. return this;
  27637. };
  27638. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27639. this._checkUniform(name);
  27640. this._matrices3x3[name] = value;
  27641. return this;
  27642. };
  27643. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27644. this._checkUniform(name);
  27645. this._matrices2x2[name] = value;
  27646. return this;
  27647. };
  27648. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27649. var scene = this.getScene();
  27650. var engine = scene.getEngine();
  27651. if (!this.checkReadyOnEveryCall) {
  27652. if (this._renderId === scene.getRenderId()) {
  27653. return true;
  27654. }
  27655. }
  27656. // Instances
  27657. var defines = [];
  27658. var fallbacks = new BABYLON.EffectFallbacks();
  27659. if (useInstances) {
  27660. defines.push("#define INSTANCES");
  27661. }
  27662. for (var index = 0; index < this._options.defines.length; index++) {
  27663. defines.push(this._options.defines[index]);
  27664. }
  27665. // Bones
  27666. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27667. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  27668. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27669. fallbacks.addCPUSkinningFallback(0, mesh);
  27670. }
  27671. // Alpha test
  27672. if (engine.getAlphaTesting()) {
  27673. defines.push("#define ALPHATEST");
  27674. }
  27675. var previousEffect = this._effect;
  27676. var join = defines.join("\n");
  27677. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27678. if (!this._effect.isReady()) {
  27679. return false;
  27680. }
  27681. if (previousEffect !== this._effect) {
  27682. scene.resetCachedMaterial();
  27683. }
  27684. this._renderId = scene.getRenderId();
  27685. return true;
  27686. };
  27687. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27688. var scene = this.getScene();
  27689. if (this._options.uniforms.indexOf("world") !== -1) {
  27690. this._effect.setMatrix("world", world);
  27691. }
  27692. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27693. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27694. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27695. }
  27696. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27697. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27698. }
  27699. };
  27700. ShaderMaterial.prototype.bind = function (world, mesh) {
  27701. // Std values
  27702. this.bindOnlyWorldMatrix(world);
  27703. if (this.getScene().getCachedMaterial() !== this) {
  27704. if (this._options.uniforms.indexOf("view") !== -1) {
  27705. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27706. }
  27707. if (this._options.uniforms.indexOf("projection") !== -1) {
  27708. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27709. }
  27710. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27711. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27712. }
  27713. // Bones
  27714. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27715. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27716. }
  27717. // Texture
  27718. for (var name in this._textures) {
  27719. this._effect.setTexture(name, this._textures[name]);
  27720. }
  27721. // Float
  27722. for (name in this._floats) {
  27723. this._effect.setFloat(name, this._floats[name]);
  27724. }
  27725. // Float s
  27726. for (name in this._floatsArrays) {
  27727. this._effect.setArray(name, this._floatsArrays[name]);
  27728. }
  27729. // Color3
  27730. for (name in this._colors3) {
  27731. this._effect.setColor3(name, this._colors3[name]);
  27732. }
  27733. // Color4
  27734. for (name in this._colors4) {
  27735. var color = this._colors4[name];
  27736. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27737. }
  27738. // Vector2
  27739. for (name in this._vectors2) {
  27740. this._effect.setVector2(name, this._vectors2[name]);
  27741. }
  27742. // Vector3
  27743. for (name in this._vectors3) {
  27744. this._effect.setVector3(name, this._vectors3[name]);
  27745. }
  27746. // Vector4
  27747. for (name in this._vectors4) {
  27748. this._effect.setVector4(name, this._vectors4[name]);
  27749. }
  27750. // Matrix
  27751. for (name in this._matrices) {
  27752. this._effect.setMatrix(name, this._matrices[name]);
  27753. }
  27754. // Matrix 3x3
  27755. for (name in this._matrices3x3) {
  27756. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27757. }
  27758. // Matrix 2x2
  27759. for (name in this._matrices2x2) {
  27760. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27761. }
  27762. }
  27763. _super.prototype.bind.call(this, world, mesh);
  27764. };
  27765. ShaderMaterial.prototype.clone = function (name) {
  27766. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27767. return newShaderMaterial;
  27768. };
  27769. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27770. for (var name in this._textures) {
  27771. this._textures[name].dispose();
  27772. }
  27773. this._textures = [];
  27774. _super.prototype.dispose.call(this, forceDisposeEffect);
  27775. };
  27776. return ShaderMaterial;
  27777. })(BABYLON.Material);
  27778. BABYLON.ShaderMaterial = ShaderMaterial;
  27779. })(BABYLON || (BABYLON = {}));
  27780. var BABYLON;
  27781. (function (BABYLON) {
  27782. var Internals;
  27783. (function (Internals) {
  27784. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27785. // All values and structures referenced from:
  27786. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27787. var DDS_MAGIC = 0x20534444;
  27788. 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;
  27789. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27790. 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;
  27791. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27792. function FourCCToInt32(value) {
  27793. return value.charCodeAt(0) +
  27794. (value.charCodeAt(1) << 8) +
  27795. (value.charCodeAt(2) << 16) +
  27796. (value.charCodeAt(3) << 24);
  27797. }
  27798. function Int32ToFourCC(value) {
  27799. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27800. }
  27801. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27802. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27803. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27804. var headerLengthInt = 31; // The header length in 32 bit ints
  27805. // Offsets into the header array
  27806. var off_magic = 0;
  27807. var off_size = 1;
  27808. var off_flags = 2;
  27809. var off_height = 3;
  27810. var off_width = 4;
  27811. var off_mipmapCount = 7;
  27812. var off_pfFlags = 20;
  27813. var off_pfFourCC = 21;
  27814. var off_RGBbpp = 22;
  27815. var off_RMask = 23;
  27816. var off_GMask = 24;
  27817. var off_BMask = 25;
  27818. var off_AMask = 26;
  27819. var off_caps1 = 27;
  27820. var off_caps2 = 28;
  27821. ;
  27822. var DDSTools = (function () {
  27823. function DDSTools() {
  27824. }
  27825. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27826. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27827. var mipmapCount = 1;
  27828. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27829. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27830. }
  27831. return {
  27832. width: header[off_width],
  27833. height: header[off_height],
  27834. mipmapCount: mipmapCount,
  27835. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27836. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27837. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27838. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27839. };
  27840. };
  27841. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27842. var byteArray = new Uint8Array(dataLength);
  27843. var srcData = new Uint8Array(arrayBuffer);
  27844. var index = 0;
  27845. for (var y = height - 1; y >= 0; y--) {
  27846. for (var x = 0; x < width; x++) {
  27847. var srcPos = dataOffset + (x + y * width) * 4;
  27848. byteArray[index + 2] = srcData[srcPos];
  27849. byteArray[index + 1] = srcData[srcPos + 1];
  27850. byteArray[index] = srcData[srcPos + 2];
  27851. byteArray[index + 3] = srcData[srcPos + 3];
  27852. index += 4;
  27853. }
  27854. }
  27855. return byteArray;
  27856. };
  27857. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27858. var byteArray = new Uint8Array(dataLength);
  27859. var srcData = new Uint8Array(arrayBuffer);
  27860. var index = 0;
  27861. for (var y = height - 1; y >= 0; y--) {
  27862. for (var x = 0; x < width; x++) {
  27863. var srcPos = dataOffset + (x + y * width) * 3;
  27864. byteArray[index + 2] = srcData[srcPos];
  27865. byteArray[index + 1] = srcData[srcPos + 1];
  27866. byteArray[index] = srcData[srcPos + 2];
  27867. index += 3;
  27868. }
  27869. }
  27870. return byteArray;
  27871. };
  27872. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27873. var byteArray = new Uint8Array(dataLength);
  27874. var srcData = new Uint8Array(arrayBuffer);
  27875. var index = 0;
  27876. for (var y = height - 1; y >= 0; y--) {
  27877. for (var x = 0; x < width; x++) {
  27878. var srcPos = dataOffset + (x + y * width);
  27879. byteArray[index] = srcData[srcPos];
  27880. index++;
  27881. }
  27882. }
  27883. return byteArray;
  27884. };
  27885. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27886. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27887. if (header[off_magic] != DDS_MAGIC) {
  27888. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27889. return;
  27890. }
  27891. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27892. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27893. return;
  27894. }
  27895. if (info.isFourCC) {
  27896. fourCC = header[off_pfFourCC];
  27897. switch (fourCC) {
  27898. case FOURCC_DXT1:
  27899. blockBytes = 8;
  27900. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27901. break;
  27902. case FOURCC_DXT3:
  27903. blockBytes = 16;
  27904. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27905. break;
  27906. case FOURCC_DXT5:
  27907. blockBytes = 16;
  27908. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27909. break;
  27910. default:
  27911. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27912. return;
  27913. }
  27914. }
  27915. mipmapCount = 1;
  27916. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27917. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27918. }
  27919. var bpp = header[off_RGBbpp];
  27920. for (var face = 0; face < faces; face++) {
  27921. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27922. width = header[off_width];
  27923. height = header[off_height];
  27924. dataOffset = header[off_size] + 4;
  27925. for (i = 0; i < mipmapCount; ++i) {
  27926. if (info.isRGB) {
  27927. if (bpp === 24) {
  27928. dataLength = width * height * 3;
  27929. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27930. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27931. }
  27932. else {
  27933. dataLength = width * height * 4;
  27934. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27935. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27936. }
  27937. }
  27938. else if (info.isLuminance) {
  27939. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27940. var unpaddedRowSize = width;
  27941. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27942. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27943. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27944. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27945. }
  27946. else {
  27947. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27948. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27949. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27950. }
  27951. dataOffset += dataLength;
  27952. width *= 0.5;
  27953. height *= 0.5;
  27954. width = Math.max(1.0, width);
  27955. height = Math.max(1.0, height);
  27956. }
  27957. }
  27958. };
  27959. return DDSTools;
  27960. })();
  27961. Internals.DDSTools = DDSTools;
  27962. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27963. })(BABYLON || (BABYLON = {}));
  27964. var BABYLON;
  27965. (function (BABYLON) {
  27966. var CannonJSPlugin = (function () {
  27967. function CannonJSPlugin() {
  27968. this._registeredMeshes = [];
  27969. this._physicsMaterials = [];
  27970. this.name = "cannon";
  27971. this.updateBodyPosition = function (mesh) {
  27972. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27973. var registeredMesh = this._registeredMeshes[index];
  27974. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27975. var body = registeredMesh.body;
  27976. var center = mesh.getBoundingInfo().boundingBox.center;
  27977. body.position.set(center.x, center.y, center.z);
  27978. body.quaternion.copy(mesh.rotationQuaternion);
  27979. if (registeredMesh.deltaRotation) {
  27980. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27981. body.quaternion = body.quaternion.mult(tmpQ);
  27982. }
  27983. if (registeredMesh.heightmap) {
  27984. //calculate the correct body position:
  27985. var rotationQuaternion = mesh.rotationQuaternion;
  27986. mesh.rotationQuaternion = new BABYLON.Quaternion();
  27987. mesh.computeWorldMatrix(true);
  27988. //get original center with no rotation
  27989. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  27990. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  27991. //rotation is back
  27992. mesh.rotationQuaternion = rotationQuaternion;
  27993. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  27994. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  27995. mesh.setPivotMatrix(p);
  27996. mesh.computeWorldMatrix(true);
  27997. //calculate the translation
  27998. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  27999. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28000. //add it inverted to the delta
  28001. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28002. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28003. mesh.setPivotMatrix(oldPivot);
  28004. mesh.computeWorldMatrix(true);
  28005. }
  28006. return;
  28007. }
  28008. }
  28009. };
  28010. }
  28011. CannonJSPlugin.prototype.initialize = function (iterations) {
  28012. if (iterations === void 0) { iterations = 10; }
  28013. this._world = new CANNON.World();
  28014. this._world.broadphase = new CANNON.NaiveBroadphase();
  28015. this._world.solver.iterations = iterations;
  28016. };
  28017. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28018. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28019. };
  28020. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28021. var _this = this;
  28022. this._world.step(delta);
  28023. this._registeredMeshes.forEach(function (registeredMesh) {
  28024. // Body position
  28025. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28026. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28027. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28028. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28029. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28030. if (registeredMesh.deltaRotation) {
  28031. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28032. }
  28033. //is the physics collision callback is set?
  28034. if (registeredMesh.mesh.onPhysicsCollide) {
  28035. if (!registeredMesh.collisionFunction) {
  28036. registeredMesh.collisionFunction = function (e) {
  28037. //find the mesh that collided with the registered mesh
  28038. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28039. if (_this._registeredMeshes[idx].body == e.body) {
  28040. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28041. }
  28042. }
  28043. };
  28044. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28045. }
  28046. }
  28047. else {
  28048. //unregister, in case the function was removed for some reason
  28049. if (registeredMesh.collisionFunction) {
  28050. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28051. }
  28052. }
  28053. });
  28054. };
  28055. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28056. this._gravity = gravity;
  28057. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28058. };
  28059. CannonJSPlugin.prototype.getGravity = function () {
  28060. return this._gravity;
  28061. };
  28062. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28063. this.unregisterMesh(mesh);
  28064. if (!mesh.rotationQuaternion) {
  28065. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28066. }
  28067. mesh.computeWorldMatrix(true);
  28068. var shape = this._createShape(mesh, impostor);
  28069. return this._createRigidBodyFromShape(shape, mesh, options);
  28070. };
  28071. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28072. //get the correct bounding box
  28073. var oldQuaternion = mesh.rotationQuaternion;
  28074. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28075. mesh.computeWorldMatrix(true);
  28076. var returnValue;
  28077. switch (impostor) {
  28078. case BABYLON.PhysicsEngine.SphereImpostor:
  28079. var bbox = mesh.getBoundingInfo().boundingBox;
  28080. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28081. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28082. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28083. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28084. break;
  28085. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28086. case BABYLON.PhysicsEngine.CylinderImpostor:
  28087. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28088. case BABYLON.PhysicsEngine.BoxImpostor:
  28089. bbox = mesh.getBoundingInfo().boundingBox;
  28090. var min = bbox.minimumWorld;
  28091. var max = bbox.maximumWorld;
  28092. var box = max.subtract(min).scale(0.5);
  28093. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28094. break;
  28095. case BABYLON.PhysicsEngine.PlaneImpostor:
  28096. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28097. returnValue = new CANNON.Plane();
  28098. break;
  28099. case BABYLON.PhysicsEngine.MeshImpostor:
  28100. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28101. var rawFaces = mesh.getIndices();
  28102. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28103. break;
  28104. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28105. returnValue = this._createHeightmap(mesh);
  28106. break;
  28107. }
  28108. mesh.rotationQuaternion = oldQuaternion;
  28109. return returnValue;
  28110. };
  28111. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28112. var verts = [], faces = [];
  28113. mesh.computeWorldMatrix(true);
  28114. //reuse this variable
  28115. var transformed = BABYLON.Vector3.Zero();
  28116. // Get vertices
  28117. for (var i = 0; i < rawVerts.length; i += 3) {
  28118. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28119. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28120. }
  28121. // Get faces
  28122. for (var j = 0; j < rawFaces.length; j += 3) {
  28123. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28124. }
  28125. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28126. return shape;
  28127. };
  28128. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28129. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28130. var matrix = [];
  28131. //For now pointDepth will not be used and will be automatically calculated.
  28132. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28133. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28134. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28135. var elementSize = dim * 2 / arraySize;
  28136. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28137. for (var i = 0; i < pos.length; i = i + 3) {
  28138. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28139. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28140. var y = pos[i + 1] + minY;
  28141. if (!matrix[x]) {
  28142. matrix[x] = [];
  28143. }
  28144. if (!matrix[x][z]) {
  28145. matrix[x][z] = y;
  28146. }
  28147. matrix[x][z] = Math.max(y, matrix[x][z]);
  28148. }
  28149. for (var x = 0; x <= arraySize; ++x) {
  28150. if (!matrix[x]) {
  28151. var loc = 1;
  28152. while (!matrix[(x + loc) % arraySize]) {
  28153. loc++;
  28154. }
  28155. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28156. }
  28157. for (var z = 0; z <= arraySize; ++z) {
  28158. if (!matrix[x][z]) {
  28159. var loc = 1;
  28160. var newValue;
  28161. while (newValue === undefined) {
  28162. newValue = matrix[x][(z + loc++) % arraySize];
  28163. }
  28164. matrix[x][z] = newValue;
  28165. }
  28166. }
  28167. }
  28168. var shape = new CANNON.Heightfield(matrix, {
  28169. elementSize: elementSize
  28170. });
  28171. //For future reference, needed for body transformation
  28172. shape.minY = minY;
  28173. return shape;
  28174. };
  28175. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28176. var index;
  28177. var mat;
  28178. for (index = 0; index < this._physicsMaterials.length; index++) {
  28179. mat = this._physicsMaterials[index];
  28180. if (mat.friction === friction && mat.restitution === restitution) {
  28181. return mat;
  28182. }
  28183. }
  28184. var currentMat = new CANNON.Material("mat");
  28185. this._physicsMaterials.push(currentMat);
  28186. for (index = 0; index < this._physicsMaterials.length; index++) {
  28187. mat = this._physicsMaterials[index];
  28188. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28189. this._world.addContactMaterial(contactMaterial);
  28190. }
  28191. return currentMat;
  28192. };
  28193. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28194. if (!mesh.rotationQuaternion) {
  28195. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28196. }
  28197. // The delta between the mesh position and the mesh bounding box center
  28198. var bbox = mesh.getBoundingInfo().boundingBox;
  28199. var deltaPosition = mesh.position.subtract(bbox.center);
  28200. var deltaRotation;
  28201. var material = this._addMaterial(options.friction, options.restitution);
  28202. var body = new CANNON.Body({
  28203. mass: options.mass,
  28204. material: material,
  28205. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28206. });
  28207. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28208. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28209. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28210. //-90 DEG in X, precalculated
  28211. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28212. body.quaternion = body.quaternion.mult(tmpQ);
  28213. //Invert! (Precalculated, 90 deg in X)
  28214. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28215. }
  28216. //If it is a heightfield, if should be centered.
  28217. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28218. //calculate the correct body position:
  28219. var rotationQuaternion = mesh.rotationQuaternion;
  28220. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28221. mesh.computeWorldMatrix(true);
  28222. //get original center with no rotation
  28223. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28224. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28225. //rotation is back
  28226. mesh.rotationQuaternion = rotationQuaternion;
  28227. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28228. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28229. mesh.setPivotMatrix(p);
  28230. mesh.computeWorldMatrix(true);
  28231. //calculate the translation
  28232. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28233. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28234. //add it inverted to the delta
  28235. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28236. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28237. mesh.setPivotMatrix(oldPivot);
  28238. mesh.computeWorldMatrix(true);
  28239. }
  28240. //add the shape
  28241. body.addShape(shape);
  28242. this._world.add(body);
  28243. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28244. return body;
  28245. };
  28246. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28247. var initialMesh = parts[0].mesh;
  28248. this.unregisterMesh(initialMesh);
  28249. initialMesh.computeWorldMatrix(true);
  28250. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28251. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28252. for (var index = 1; index < parts.length; index++) {
  28253. var mesh = parts[index].mesh;
  28254. mesh.computeWorldMatrix(true);
  28255. var shape = this._createShape(mesh, parts[index].impostor);
  28256. var localPosition = mesh.position;
  28257. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28258. }
  28259. return body;
  28260. };
  28261. CannonJSPlugin.prototype._unbindBody = function (body) {
  28262. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28263. var registeredMesh = this._registeredMeshes[index];
  28264. if (registeredMesh.body === body) {
  28265. this._world.remove(registeredMesh.body);
  28266. registeredMesh.body = null;
  28267. registeredMesh.delta = null;
  28268. registeredMesh.deltaRotation = null;
  28269. }
  28270. }
  28271. };
  28272. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28273. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28274. var registeredMesh = this._registeredMeshes[index];
  28275. if (registeredMesh.mesh === mesh) {
  28276. // Remove body
  28277. if (registeredMesh.body) {
  28278. this._unbindBody(registeredMesh.body);
  28279. }
  28280. this._registeredMeshes.splice(index, 1);
  28281. return;
  28282. }
  28283. }
  28284. };
  28285. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28286. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28287. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28288. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28289. var registeredMesh = this._registeredMeshes[index];
  28290. if (registeredMesh.mesh === mesh) {
  28291. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28292. return;
  28293. }
  28294. }
  28295. };
  28296. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28297. var body1 = null, body2 = null;
  28298. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28299. var registeredMesh = this._registeredMeshes[index];
  28300. if (registeredMesh.mesh === mesh1) {
  28301. body1 = registeredMesh.body;
  28302. }
  28303. else if (registeredMesh.mesh === mesh2) {
  28304. body2 = registeredMesh.body;
  28305. }
  28306. }
  28307. if (!body1 || !body2) {
  28308. return false;
  28309. }
  28310. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  28311. this._world.addConstraint(constraint);
  28312. return true;
  28313. };
  28314. CannonJSPlugin.prototype.dispose = function () {
  28315. while (this._registeredMeshes.length) {
  28316. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28317. }
  28318. };
  28319. CannonJSPlugin.prototype.isSupported = function () {
  28320. return window.CANNON !== undefined;
  28321. };
  28322. CannonJSPlugin.prototype.getWorldObject = function () {
  28323. return this._world;
  28324. };
  28325. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28326. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28327. var registeredMesh = this._registeredMeshes[index];
  28328. if (registeredMesh.mesh === mesh) {
  28329. return registeredMesh.body;
  28330. }
  28331. }
  28332. return null;
  28333. };
  28334. return CannonJSPlugin;
  28335. })();
  28336. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28337. })(BABYLON || (BABYLON = {}));
  28338. var BABYLON;
  28339. (function (BABYLON) {
  28340. var OimoJSPlugin = (function () {
  28341. function OimoJSPlugin() {
  28342. this._registeredMeshes = [];
  28343. this.name = "oimo";
  28344. /**
  28345. * Update the body position according to the mesh position
  28346. * @param mesh
  28347. */
  28348. this.updateBodyPosition = function (mesh) {
  28349. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28350. var registeredMesh = this._registeredMeshes[index];
  28351. var body = registeredMesh.body.body;
  28352. var updated = false;
  28353. var newPosition;
  28354. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28355. mesh.computeWorldMatrix(true);
  28356. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28357. updated = true;
  28358. }
  28359. else if (registeredMesh.mesh.parent === mesh) {
  28360. mesh.computeWorldMatrix(true);
  28361. registeredMesh.mesh.computeWorldMatrix(true);
  28362. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28363. updated = true;
  28364. }
  28365. if (updated) {
  28366. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28367. body.setQuaternion(mesh.rotationQuaternion);
  28368. body.sleeping = false;
  28369. //force Oimo to update the body's position
  28370. body.updatePosition(1);
  28371. }
  28372. }
  28373. };
  28374. }
  28375. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28376. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28377. };
  28378. OimoJSPlugin.prototype.initialize = function (iterations) {
  28379. this._world = new OIMO.World(null, null, iterations);
  28380. this._world.clear();
  28381. };
  28382. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28383. this._gravity = this._world.gravity = gravity;
  28384. };
  28385. OimoJSPlugin.prototype.getGravity = function () {
  28386. return this._gravity;
  28387. };
  28388. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28389. this.unregisterMesh(mesh);
  28390. if (!mesh.rotationQuaternion) {
  28391. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28392. }
  28393. mesh.computeWorldMatrix(true);
  28394. var bbox = mesh.getBoundingInfo().boundingBox;
  28395. // The delta between the mesh position and the mesh bounding box center
  28396. var deltaPosition = mesh.position.subtract(bbox.center);
  28397. //calculate rotation to fit Oimo's needs (Euler...)
  28398. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28399. //get the correct bounding box
  28400. var oldQuaternion = mesh.rotationQuaternion;
  28401. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28402. mesh.computeWorldMatrix(true);
  28403. var bodyConfig = {
  28404. name: mesh.uniqueId,
  28405. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28406. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28407. move: options.mass != 0,
  28408. config: [options.mass, options.friction, options.restitution],
  28409. world: this._world
  28410. };
  28411. // register mesh
  28412. switch (impostor) {
  28413. case BABYLON.PhysicsEngine.SphereImpostor:
  28414. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28415. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28416. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28417. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28418. bodyConfig.type = 'sphere';
  28419. bodyConfig.size = [size];
  28420. break;
  28421. case BABYLON.PhysicsEngine.PlaneImpostor:
  28422. //Oimo "fakes" a cylinder as a box, so why don't we!
  28423. case BABYLON.PhysicsEngine.CylinderImpostor:
  28424. case BABYLON.PhysicsEngine.BoxImpostor:
  28425. var min = bbox.minimumWorld;
  28426. var max = bbox.maximumWorld;
  28427. var box = max.subtract(min);
  28428. var sizeX = this._checkWithEpsilon(box.x);
  28429. var sizeY = this._checkWithEpsilon(box.y);
  28430. var sizeZ = this._checkWithEpsilon(box.z);
  28431. bodyConfig.type = 'box';
  28432. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28433. break;
  28434. }
  28435. var body = new OIMO.Body(bodyConfig);
  28436. //We have to access the rigid body's properties to set the quaternion.
  28437. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28438. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28439. //TEST
  28440. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28441. //update the internal rotation matrix
  28442. //body.body.syncShapes();
  28443. this._registeredMeshes.push({
  28444. mesh: mesh,
  28445. body: body,
  28446. delta: deltaPosition
  28447. });
  28448. //for the sake of consistency.
  28449. mesh.rotationQuaternion = oldQuaternion;
  28450. return body;
  28451. };
  28452. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28453. var types = [], sizes = [], positions = [], rotations = [];
  28454. var initialMesh = parts[0].mesh;
  28455. for (var index = 0; index < parts.length; index++) {
  28456. var part = parts[index];
  28457. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28458. types.push(bodyParameters.type);
  28459. sizes.push.apply(sizes, bodyParameters.size);
  28460. positions.push.apply(positions, bodyParameters.pos);
  28461. rotations.push.apply(rotations, bodyParameters.rot);
  28462. }
  28463. var body = new OIMO.Body({
  28464. name: initialMesh.uniqueId,
  28465. type: types,
  28466. size: sizes,
  28467. pos: positions,
  28468. rot: rotations,
  28469. move: options.mass != 0,
  28470. config: [options.mass, options.friction, options.restitution],
  28471. world: this._world
  28472. });
  28473. //Reset the body's rotation to be of the initial mesh's.
  28474. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28475. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28476. this._registeredMeshes.push({
  28477. mesh: initialMesh,
  28478. body: body
  28479. });
  28480. return body;
  28481. };
  28482. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28483. var mesh = part.mesh;
  28484. if (!mesh.rotationQuaternion) {
  28485. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28486. }
  28487. // We need the bounding box/sphere info to compute the physics body
  28488. mesh.computeWorldMatrix(true);
  28489. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28490. var bodyParameters = {
  28491. name: mesh.uniqueId,
  28492. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28493. //A bug in Oimo (Body class) prevents us from using rot directly.
  28494. rot: [0, 0, 0],
  28495. //For future reference, if the bug will ever be fixed.
  28496. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28497. };
  28498. var oldQuaternion = mesh.rotationQuaternion;
  28499. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28500. mesh.computeWorldMatrix(true);
  28501. switch (part.impostor) {
  28502. case BABYLON.PhysicsEngine.SphereImpostor:
  28503. var bbox = mesh.getBoundingInfo().boundingBox;
  28504. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28505. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28506. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28507. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28508. bodyParameters.type = 'sphere';
  28509. bodyParameters.size = [size, size, size];
  28510. break;
  28511. case BABYLON.PhysicsEngine.PlaneImpostor:
  28512. case BABYLON.PhysicsEngine.CylinderImpostor:
  28513. case BABYLON.PhysicsEngine.BoxImpostor:
  28514. bbox = mesh.getBoundingInfo().boundingBox;
  28515. var min = bbox.minimumWorld;
  28516. var max = bbox.maximumWorld;
  28517. var box = max.subtract(min);
  28518. var sizeX = this._checkWithEpsilon(box.x);
  28519. var sizeY = this._checkWithEpsilon(box.y);
  28520. var sizeZ = this._checkWithEpsilon(box.z);
  28521. bodyParameters.type = 'box';
  28522. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28523. break;
  28524. }
  28525. mesh.rotationQuaternion = oldQuaternion;
  28526. return bodyParameters;
  28527. };
  28528. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28529. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28530. var registeredMesh = this._registeredMeshes[index];
  28531. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28532. if (registeredMesh.body) {
  28533. this._world.removeRigidBody(registeredMesh.body.body);
  28534. this._unbindBody(registeredMesh.body);
  28535. }
  28536. this._registeredMeshes.splice(index, 1);
  28537. return;
  28538. }
  28539. }
  28540. };
  28541. OimoJSPlugin.prototype._unbindBody = function (body) {
  28542. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28543. var registeredMesh = this._registeredMeshes[index];
  28544. if (registeredMesh.body === body) {
  28545. registeredMesh.body = null;
  28546. }
  28547. }
  28548. };
  28549. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28550. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28551. var registeredMesh = this._registeredMeshes[index];
  28552. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28553. // Get object mass to have a behaviour similar to cannon.js
  28554. var mass = registeredMesh.body.body.massInfo.mass;
  28555. // The force is scaled with the mass of object
  28556. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28557. return;
  28558. }
  28559. }
  28560. };
  28561. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28562. var body1 = null, body2 = null;
  28563. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28564. var registeredMesh = this._registeredMeshes[index];
  28565. if (registeredMesh.mesh === mesh1) {
  28566. body1 = registeredMesh.body.body;
  28567. }
  28568. else if (registeredMesh.mesh === mesh2) {
  28569. body2 = registeredMesh.body.body;
  28570. }
  28571. }
  28572. if (!body1 || !body2) {
  28573. return false;
  28574. }
  28575. if (!options) {
  28576. options = {};
  28577. }
  28578. new OIMO.Link({
  28579. type: options.type,
  28580. body1: body1,
  28581. body2: body2,
  28582. min: options.min,
  28583. max: options.max,
  28584. axe1: options.axe1,
  28585. axe2: options.axe2,
  28586. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28587. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28588. collision: options.collision,
  28589. spring: options.spring,
  28590. world: this._world
  28591. });
  28592. return true;
  28593. };
  28594. OimoJSPlugin.prototype.dispose = function () {
  28595. this._world.clear();
  28596. while (this._registeredMeshes.length) {
  28597. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28598. }
  28599. };
  28600. OimoJSPlugin.prototype.isSupported = function () {
  28601. return OIMO !== undefined;
  28602. };
  28603. OimoJSPlugin.prototype.getWorldObject = function () {
  28604. return this._world;
  28605. };
  28606. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28607. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28608. var registeredMesh = this._registeredMeshes[index];
  28609. if (registeredMesh.mesh === mesh) {
  28610. return registeredMesh.body;
  28611. }
  28612. }
  28613. return null;
  28614. };
  28615. OimoJSPlugin.prototype._getLastShape = function (body) {
  28616. var lastShape = body.shapes;
  28617. while (lastShape.next) {
  28618. lastShape = lastShape.next;
  28619. }
  28620. return lastShape;
  28621. };
  28622. OimoJSPlugin.prototype.runOneStep = function (time) {
  28623. this._world.step();
  28624. // Update the position of all registered meshes
  28625. var i = this._registeredMeshes.length;
  28626. var m;
  28627. while (i--) {
  28628. var body = this._registeredMeshes[i].body.body;
  28629. var mesh = this._registeredMeshes[i].mesh;
  28630. if (!this._registeredMeshes[i].delta) {
  28631. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28632. }
  28633. if (!body.sleeping) {
  28634. //TODO check that
  28635. if (body.shapes.next) {
  28636. var parentShape = this._getLastShape(body);
  28637. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28638. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28639. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28640. }
  28641. else {
  28642. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28643. }
  28644. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28645. mesh.computeWorldMatrix();
  28646. }
  28647. //check if the collide callback is set.
  28648. if (mesh.onPhysicsCollide) {
  28649. var meshUniqueName = mesh.uniqueId;
  28650. var contact = this._world.contacts;
  28651. while (contact !== null) {
  28652. //is this body colliding with any other?
  28653. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  28654. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  28655. //get the mesh and execute the callback
  28656. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  28657. if (otherMesh)
  28658. mesh.onPhysicsCollide(otherMesh);
  28659. }
  28660. contact = contact.next;
  28661. }
  28662. }
  28663. }
  28664. };
  28665. return OimoJSPlugin;
  28666. })();
  28667. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28668. })(BABYLON || (BABYLON = {}));
  28669. var BABYLON;
  28670. (function (BABYLON) {
  28671. var DisplayPassPostProcess = (function (_super) {
  28672. __extends(DisplayPassPostProcess, _super);
  28673. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28674. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28675. }
  28676. return DisplayPassPostProcess;
  28677. })(BABYLON.PostProcess);
  28678. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28679. })(BABYLON || (BABYLON = {}));
  28680. var BABYLON;
  28681. (function (BABYLON) {
  28682. var SimplificationSettings = (function () {
  28683. function SimplificationSettings(quality, distance, optimizeMesh) {
  28684. this.quality = quality;
  28685. this.distance = distance;
  28686. this.optimizeMesh = optimizeMesh;
  28687. }
  28688. return SimplificationSettings;
  28689. })();
  28690. BABYLON.SimplificationSettings = SimplificationSettings;
  28691. var SimplificationQueue = (function () {
  28692. function SimplificationQueue() {
  28693. this.running = false;
  28694. this._simplificationArray = [];
  28695. }
  28696. SimplificationQueue.prototype.addTask = function (task) {
  28697. this._simplificationArray.push(task);
  28698. };
  28699. SimplificationQueue.prototype.executeNext = function () {
  28700. var task = this._simplificationArray.pop();
  28701. if (task) {
  28702. this.running = true;
  28703. this.runSimplification(task);
  28704. }
  28705. else {
  28706. this.running = false;
  28707. }
  28708. };
  28709. SimplificationQueue.prototype.runSimplification = function (task) {
  28710. var _this = this;
  28711. if (task.parallelProcessing) {
  28712. //parallel simplifier
  28713. task.settings.forEach(function (setting) {
  28714. var simplifier = _this.getSimplifier(task);
  28715. simplifier.simplify(setting, function (newMesh) {
  28716. task.mesh.addLODLevel(setting.distance, newMesh);
  28717. newMesh.isVisible = true;
  28718. //check if it is the last
  28719. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28720. //all done, run the success callback.
  28721. task.successCallback();
  28722. }
  28723. _this.executeNext();
  28724. });
  28725. });
  28726. }
  28727. else {
  28728. //single simplifier.
  28729. var simplifier = this.getSimplifier(task);
  28730. var runDecimation = function (setting, callback) {
  28731. simplifier.simplify(setting, function (newMesh) {
  28732. task.mesh.addLODLevel(setting.distance, newMesh);
  28733. newMesh.isVisible = true;
  28734. //run the next quality level
  28735. callback();
  28736. });
  28737. };
  28738. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28739. runDecimation(task.settings[loop.index], function () {
  28740. loop.executeNext();
  28741. });
  28742. }, function () {
  28743. //execution ended, run the success callback.
  28744. if (task.successCallback) {
  28745. task.successCallback();
  28746. }
  28747. _this.executeNext();
  28748. });
  28749. }
  28750. };
  28751. SimplificationQueue.prototype.getSimplifier = function (task) {
  28752. switch (task.simplificationType) {
  28753. case SimplificationType.QUADRATIC:
  28754. default:
  28755. return new QuadraticErrorSimplification(task.mesh);
  28756. }
  28757. };
  28758. return SimplificationQueue;
  28759. })();
  28760. BABYLON.SimplificationQueue = SimplificationQueue;
  28761. /**
  28762. * The implemented types of simplification.
  28763. * At the moment only Quadratic Error Decimation is implemented.
  28764. */
  28765. (function (SimplificationType) {
  28766. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28767. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28768. var SimplificationType = BABYLON.SimplificationType;
  28769. var DecimationTriangle = (function () {
  28770. function DecimationTriangle(vertices) {
  28771. this.vertices = vertices;
  28772. this.error = new Array(4);
  28773. this.deleted = false;
  28774. this.isDirty = false;
  28775. this.deletePending = false;
  28776. this.borderFactor = 0;
  28777. }
  28778. return DecimationTriangle;
  28779. })();
  28780. BABYLON.DecimationTriangle = DecimationTriangle;
  28781. var DecimationVertex = (function () {
  28782. function DecimationVertex(position, id) {
  28783. this.position = position;
  28784. this.id = id;
  28785. this.isBorder = true;
  28786. this.q = new QuadraticMatrix();
  28787. this.triangleCount = 0;
  28788. this.triangleStart = 0;
  28789. this.originalOffsets = [];
  28790. }
  28791. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28792. this.position.copyFrom(newPosition);
  28793. };
  28794. return DecimationVertex;
  28795. })();
  28796. BABYLON.DecimationVertex = DecimationVertex;
  28797. var QuadraticMatrix = (function () {
  28798. function QuadraticMatrix(data) {
  28799. this.data = new Array(10);
  28800. for (var i = 0; i < 10; ++i) {
  28801. if (data && data[i]) {
  28802. this.data[i] = data[i];
  28803. }
  28804. else {
  28805. this.data[i] = 0;
  28806. }
  28807. }
  28808. }
  28809. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28810. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28811. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28812. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28813. return det;
  28814. };
  28815. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28816. for (var i = 0; i < 10; ++i) {
  28817. this.data[i] += matrix.data[i];
  28818. }
  28819. };
  28820. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28821. for (var i = 0; i < 10; ++i) {
  28822. this.data[i] += data[i];
  28823. }
  28824. };
  28825. QuadraticMatrix.prototype.add = function (matrix) {
  28826. var m = new QuadraticMatrix();
  28827. for (var i = 0; i < 10; ++i) {
  28828. m.data[i] = this.data[i] + matrix.data[i];
  28829. }
  28830. return m;
  28831. };
  28832. QuadraticMatrix.FromData = function (a, b, c, d) {
  28833. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28834. };
  28835. //returning an array to avoid garbage collection
  28836. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28837. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28838. };
  28839. return QuadraticMatrix;
  28840. })();
  28841. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28842. var Reference = (function () {
  28843. function Reference(vertexId, triangleId) {
  28844. this.vertexId = vertexId;
  28845. this.triangleId = triangleId;
  28846. }
  28847. return Reference;
  28848. })();
  28849. BABYLON.Reference = Reference;
  28850. /**
  28851. * An implementation of the Quadratic Error simplification algorithm.
  28852. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28853. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28854. * @author RaananW
  28855. */
  28856. var QuadraticErrorSimplification = (function () {
  28857. function QuadraticErrorSimplification(_mesh) {
  28858. this._mesh = _mesh;
  28859. this.initialized = false;
  28860. this.syncIterations = 5000;
  28861. this.aggressiveness = 7;
  28862. this.decimationIterations = 100;
  28863. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28864. }
  28865. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28866. var _this = this;
  28867. this.initDecimatedMesh();
  28868. //iterating through the submeshes array, one after the other.
  28869. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28870. _this.initWithMesh(loop.index, function () {
  28871. _this.runDecimation(settings, loop.index, function () {
  28872. loop.executeNext();
  28873. });
  28874. }, settings.optimizeMesh);
  28875. }, function () {
  28876. setTimeout(function () {
  28877. successCallback(_this._reconstructedMesh);
  28878. }, 0);
  28879. });
  28880. };
  28881. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28882. var _this = this;
  28883. var gCount = 0;
  28884. triangle.vertices.forEach(function (vertex) {
  28885. var count = 0;
  28886. var vPos = vertex.position;
  28887. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28888. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28889. ++count;
  28890. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28891. ++count;
  28892. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28893. ++count;
  28894. if (count > 1) {
  28895. ++gCount;
  28896. }
  28897. ;
  28898. });
  28899. if (gCount > 1) {
  28900. console.log(triangle, gCount);
  28901. }
  28902. return gCount > 1;
  28903. };
  28904. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28905. var _this = this;
  28906. var targetCount = ~~(this.triangles.length * settings.quality);
  28907. var deletedTriangles = 0;
  28908. var triangleCount = this.triangles.length;
  28909. var iterationFunction = function (iteration, callback) {
  28910. setTimeout(function () {
  28911. if (iteration % 5 === 0) {
  28912. _this.updateMesh(iteration === 0);
  28913. }
  28914. for (var i = 0; i < _this.triangles.length; ++i) {
  28915. _this.triangles[i].isDirty = false;
  28916. }
  28917. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28918. var trianglesIterator = function (i) {
  28919. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28920. var t = _this.triangles[tIdx];
  28921. if (!t)
  28922. return;
  28923. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28924. return;
  28925. }
  28926. for (var j = 0; j < 3; ++j) {
  28927. if (t.error[j] < threshold) {
  28928. var deleted0 = [];
  28929. var deleted1 = [];
  28930. var v0 = t.vertices[j];
  28931. var v1 = t.vertices[(j + 1) % 3];
  28932. if (v0.isBorder !== v1.isBorder)
  28933. continue;
  28934. var p = BABYLON.Vector3.Zero();
  28935. var n = BABYLON.Vector3.Zero();
  28936. var uv = BABYLON.Vector2.Zero();
  28937. var color = new BABYLON.Color4(0, 0, 0, 1);
  28938. _this.calculateError(v0, v1, p, n, uv, color);
  28939. var delTr = [];
  28940. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28941. continue;
  28942. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28943. continue;
  28944. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28945. continue;
  28946. var uniqueArray = [];
  28947. delTr.forEach(function (deletedT) {
  28948. if (uniqueArray.indexOf(deletedT) === -1) {
  28949. deletedT.deletePending = true;
  28950. uniqueArray.push(deletedT);
  28951. }
  28952. });
  28953. if (uniqueArray.length % 2 !== 0) {
  28954. continue;
  28955. }
  28956. v0.q = v1.q.add(v0.q);
  28957. v0.updatePosition(p);
  28958. var tStart = _this.references.length;
  28959. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28960. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28961. var tCount = _this.references.length - tStart;
  28962. if (tCount <= v0.triangleCount) {
  28963. if (tCount) {
  28964. for (var c = 0; c < tCount; c++) {
  28965. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28966. }
  28967. }
  28968. }
  28969. else {
  28970. v0.triangleStart = tStart;
  28971. }
  28972. v0.triangleCount = tCount;
  28973. break;
  28974. }
  28975. }
  28976. };
  28977. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28978. }, 0);
  28979. };
  28980. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28981. if (triangleCount - deletedTriangles <= targetCount)
  28982. loop.breakLoop();
  28983. else {
  28984. iterationFunction(loop.index, function () {
  28985. loop.executeNext();
  28986. });
  28987. }
  28988. }, function () {
  28989. setTimeout(function () {
  28990. //reconstruct this part of the mesh
  28991. _this.reconstructMesh(submeshIndex);
  28992. successCallback();
  28993. }, 0);
  28994. });
  28995. };
  28996. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28997. var _this = this;
  28998. this.vertices = [];
  28999. this.triangles = [];
  29000. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29001. var indices = this._mesh.getIndices();
  29002. var submesh = this._mesh.subMeshes[submeshIndex];
  29003. var findInVertices = function (positionToSearch) {
  29004. if (optimizeMesh) {
  29005. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29006. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29007. return _this.vertices[ii];
  29008. }
  29009. }
  29010. }
  29011. return null;
  29012. };
  29013. var vertexReferences = [];
  29014. var vertexInit = function (i) {
  29015. var offset = i + submesh.verticesStart;
  29016. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29017. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29018. vertex.originalOffsets.push(offset);
  29019. if (vertex.id === _this.vertices.length) {
  29020. _this.vertices.push(vertex);
  29021. }
  29022. vertexReferences.push(vertex.id);
  29023. };
  29024. //var totalVertices = mesh.getTotalVertices();
  29025. var totalVertices = submesh.verticesCount;
  29026. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29027. var indicesInit = function (i) {
  29028. var offset = (submesh.indexStart / 3) + i;
  29029. var pos = (offset * 3);
  29030. var i0 = indices[pos + 0];
  29031. var i1 = indices[pos + 1];
  29032. var i2 = indices[pos + 2];
  29033. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29034. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29035. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29036. var triangle = new DecimationTriangle([v0, v1, v2]);
  29037. triangle.originalOffset = pos;
  29038. _this.triangles.push(triangle);
  29039. };
  29040. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29041. _this.init(callback);
  29042. });
  29043. });
  29044. };
  29045. QuadraticErrorSimplification.prototype.init = function (callback) {
  29046. var _this = this;
  29047. var triangleInit1 = function (i) {
  29048. var t = _this.triangles[i];
  29049. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29050. for (var j = 0; j < 3; j++) {
  29051. 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))));
  29052. }
  29053. };
  29054. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29055. var triangleInit2 = function (i) {
  29056. var t = _this.triangles[i];
  29057. for (var j = 0; j < 3; ++j) {
  29058. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29059. }
  29060. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29061. };
  29062. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29063. _this.initialized = true;
  29064. callback();
  29065. });
  29066. });
  29067. };
  29068. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29069. var newTriangles = [];
  29070. var i;
  29071. for (i = 0; i < this.vertices.length; ++i) {
  29072. this.vertices[i].triangleCount = 0;
  29073. }
  29074. var t;
  29075. var j;
  29076. for (i = 0; i < this.triangles.length; ++i) {
  29077. if (!this.triangles[i].deleted) {
  29078. t = this.triangles[i];
  29079. for (j = 0; j < 3; ++j) {
  29080. t.vertices[j].triangleCount = 1;
  29081. }
  29082. newTriangles.push(t);
  29083. }
  29084. }
  29085. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29086. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29087. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29088. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29089. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29090. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29091. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29092. var vertexCount = 0;
  29093. for (i = 0; i < this.vertices.length; ++i) {
  29094. var vertex = this.vertices[i];
  29095. vertex.id = vertexCount;
  29096. if (vertex.triangleCount) {
  29097. vertex.originalOffsets.forEach(function (originalOffset) {
  29098. newPositionData.push(vertex.position.x);
  29099. newPositionData.push(vertex.position.y);
  29100. newPositionData.push(vertex.position.z);
  29101. newNormalData.push(normalData[originalOffset * 3]);
  29102. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29103. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29104. if (uvs && uvs.length) {
  29105. newUVsData.push(uvs[(originalOffset * 2)]);
  29106. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29107. }
  29108. else if (colorsData && colorsData.length) {
  29109. newColorsData.push(colorsData[(originalOffset * 4)]);
  29110. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29111. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29112. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29113. }
  29114. ++vertexCount;
  29115. });
  29116. }
  29117. }
  29118. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29119. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29120. var submeshesArray = this._reconstructedMesh.subMeshes;
  29121. this._reconstructedMesh.subMeshes = [];
  29122. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29123. var originalIndices = this._mesh.getIndices();
  29124. for (i = 0; i < newTriangles.length; ++i) {
  29125. t = newTriangles[i]; //now get the new referencing point for each vertex
  29126. [0, 1, 2].forEach(function (idx) {
  29127. var id = originalIndices[t.originalOffset + idx];
  29128. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29129. if (offset < 0)
  29130. offset = 0;
  29131. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29132. });
  29133. }
  29134. //overwriting the old vertex buffers and indices.
  29135. this._reconstructedMesh.setIndices(newIndicesArray);
  29136. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29137. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29138. if (newUVsData.length > 0)
  29139. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29140. if (newColorsData.length > 0)
  29141. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29142. //create submesh
  29143. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29144. if (submeshIndex > 0) {
  29145. this._reconstructedMesh.subMeshes = [];
  29146. submeshesArray.forEach(function (submesh) {
  29147. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29148. });
  29149. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29150. }
  29151. };
  29152. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29153. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29154. this._reconstructedMesh.material = this._mesh.material;
  29155. this._reconstructedMesh.parent = this._mesh.parent;
  29156. this._reconstructedMesh.isVisible = false;
  29157. };
  29158. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29159. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29160. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29161. if (t.deleted)
  29162. continue;
  29163. var s = this.references[vertex1.triangleStart + i].vertexId;
  29164. var v1 = t.vertices[(s + 1) % 3];
  29165. var v2 = t.vertices[(s + 2) % 3];
  29166. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29167. deletedArray[i] = true;
  29168. delTr.push(t);
  29169. continue;
  29170. }
  29171. var d1 = v1.position.subtract(point);
  29172. d1 = d1.normalize();
  29173. var d2 = v2.position.subtract(point);
  29174. d2 = d2.normalize();
  29175. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29176. return true;
  29177. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29178. deletedArray[i] = false;
  29179. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29180. return true;
  29181. }
  29182. return false;
  29183. };
  29184. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29185. var newDeleted = deletedTriangles;
  29186. for (var i = 0; i < vertex.triangleCount; ++i) {
  29187. var ref = this.references[vertex.triangleStart + i];
  29188. var t = this.triangles[ref.triangleId];
  29189. if (t.deleted)
  29190. continue;
  29191. if (deletedArray[i] && t.deletePending) {
  29192. t.deleted = true;
  29193. newDeleted++;
  29194. continue;
  29195. }
  29196. t.vertices[ref.vertexId] = origVertex;
  29197. t.isDirty = true;
  29198. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29199. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29200. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29201. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29202. this.references.push(ref);
  29203. }
  29204. return newDeleted;
  29205. };
  29206. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29207. for (var i = 0; i < this.vertices.length; ++i) {
  29208. var vCount = [];
  29209. var vId = [];
  29210. var v = this.vertices[i];
  29211. var j;
  29212. for (j = 0; j < v.triangleCount; ++j) {
  29213. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29214. for (var ii = 0; ii < 3; ii++) {
  29215. var ofs = 0;
  29216. var vv = triangle.vertices[ii];
  29217. while (ofs < vCount.length) {
  29218. if (vId[ofs] === vv.id)
  29219. break;
  29220. ++ofs;
  29221. }
  29222. if (ofs === vCount.length) {
  29223. vCount.push(1);
  29224. vId.push(vv.id);
  29225. }
  29226. else {
  29227. vCount[ofs]++;
  29228. }
  29229. }
  29230. }
  29231. for (j = 0; j < vCount.length; ++j) {
  29232. if (vCount[j] === 1) {
  29233. this.vertices[vId[j]].isBorder = true;
  29234. }
  29235. else {
  29236. this.vertices[vId[j]].isBorder = false;
  29237. }
  29238. }
  29239. }
  29240. };
  29241. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29242. if (identifyBorders === void 0) { identifyBorders = false; }
  29243. var i;
  29244. if (!identifyBorders) {
  29245. var newTrianglesVector = [];
  29246. for (i = 0; i < this.triangles.length; ++i) {
  29247. if (!this.triangles[i].deleted) {
  29248. newTrianglesVector.push(this.triangles[i]);
  29249. }
  29250. }
  29251. this.triangles = newTrianglesVector;
  29252. }
  29253. for (i = 0; i < this.vertices.length; ++i) {
  29254. this.vertices[i].triangleCount = 0;
  29255. this.vertices[i].triangleStart = 0;
  29256. }
  29257. var t;
  29258. var j;
  29259. var v;
  29260. for (i = 0; i < this.triangles.length; ++i) {
  29261. t = this.triangles[i];
  29262. for (j = 0; j < 3; ++j) {
  29263. v = t.vertices[j];
  29264. v.triangleCount++;
  29265. }
  29266. }
  29267. var tStart = 0;
  29268. for (i = 0; i < this.vertices.length; ++i) {
  29269. this.vertices[i].triangleStart = tStart;
  29270. tStart += this.vertices[i].triangleCount;
  29271. this.vertices[i].triangleCount = 0;
  29272. }
  29273. var newReferences = new Array(this.triangles.length * 3);
  29274. for (i = 0; i < this.triangles.length; ++i) {
  29275. t = this.triangles[i];
  29276. for (j = 0; j < 3; ++j) {
  29277. v = t.vertices[j];
  29278. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29279. v.triangleCount++;
  29280. }
  29281. }
  29282. this.references = newReferences;
  29283. if (identifyBorders) {
  29284. this.identifyBorder();
  29285. }
  29286. };
  29287. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29288. var x = point.x;
  29289. var y = point.y;
  29290. var z = point.z;
  29291. 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
  29292. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29293. };
  29294. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29295. var q = vertex1.q.add(vertex2.q);
  29296. var border = vertex1.isBorder && vertex2.isBorder;
  29297. var error = 0;
  29298. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29299. if (qDet !== 0 && !border) {
  29300. if (!pointResult) {
  29301. pointResult = BABYLON.Vector3.Zero();
  29302. }
  29303. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29304. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29305. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29306. error = this.vertexError(q, pointResult);
  29307. }
  29308. else {
  29309. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29310. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29311. var error1 = this.vertexError(q, vertex1.position);
  29312. var error2 = this.vertexError(q, vertex2.position);
  29313. var error3 = this.vertexError(q, p3);
  29314. error = Math.min(error1, error2, error3);
  29315. if (error === error1) {
  29316. if (pointResult) {
  29317. pointResult.copyFrom(vertex1.position);
  29318. }
  29319. }
  29320. else if (error === error2) {
  29321. if (pointResult) {
  29322. pointResult.copyFrom(vertex2.position);
  29323. }
  29324. }
  29325. else {
  29326. if (pointResult) {
  29327. pointResult.copyFrom(p3);
  29328. }
  29329. }
  29330. }
  29331. return error;
  29332. };
  29333. return QuadraticErrorSimplification;
  29334. })();
  29335. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29336. })(BABYLON || (BABYLON = {}));
  29337. var BABYLON;
  29338. (function (BABYLON) {
  29339. var serializeLight = function (light) {
  29340. var serializationObject = {};
  29341. serializationObject.name = light.name;
  29342. serializationObject.id = light.id;
  29343. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29344. if (light instanceof BABYLON.PointLight) {
  29345. serializationObject.type = 0;
  29346. serializationObject.position = (light).position.asArray();
  29347. }
  29348. else if (light instanceof BABYLON.DirectionalLight) {
  29349. serializationObject.type = 1;
  29350. var directionalLight = light;
  29351. serializationObject.position = directionalLight.position.asArray();
  29352. serializationObject.direction = directionalLight.direction.asArray();
  29353. }
  29354. else if (light instanceof BABYLON.SpotLight) {
  29355. serializationObject.type = 2;
  29356. var spotLight = light;
  29357. serializationObject.position = spotLight.position.asArray();
  29358. serializationObject.direction = spotLight.position.asArray();
  29359. serializationObject.angle = spotLight.angle;
  29360. serializationObject.exponent = spotLight.exponent;
  29361. }
  29362. else if (light instanceof BABYLON.HemisphericLight) {
  29363. serializationObject.type = 3;
  29364. var hemisphericLight = light;
  29365. serializationObject.direction = hemisphericLight.direction.asArray();
  29366. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29367. }
  29368. if (light.intensity) {
  29369. serializationObject.intensity = light.intensity;
  29370. }
  29371. serializationObject.range = light.range;
  29372. serializationObject.diffuse = light.diffuse.asArray();
  29373. serializationObject.specular = light.specular.asArray();
  29374. return serializationObject;
  29375. };
  29376. var serializeFresnelParameter = function (fresnelParameter) {
  29377. var serializationObject = {};
  29378. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29379. serializationObject.leftColor = fresnelParameter.leftColor;
  29380. serializationObject.rightColor = fresnelParameter.rightColor;
  29381. serializationObject.bias = fresnelParameter.bias;
  29382. serializationObject.power = fresnelParameter.power;
  29383. return serializationObject;
  29384. };
  29385. var serializeAnimation;
  29386. var appendAnimations = function (source, destination) {
  29387. if (source.animations) {
  29388. destination.animations = [];
  29389. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29390. var animation = source.animations[animationIndex];
  29391. destination.animations.push(serializeAnimation(animation));
  29392. }
  29393. }
  29394. };
  29395. var serializeCamera = function (camera) {
  29396. var serializationObject = {};
  29397. serializationObject.name = camera.name;
  29398. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29399. serializationObject.id = camera.id;
  29400. serializationObject.position = camera.position.asArray();
  29401. // Parent
  29402. if (camera.parent) {
  29403. serializationObject.parentId = camera.parent.id;
  29404. }
  29405. serializationObject.fov = camera.fov;
  29406. serializationObject.minZ = camera.minZ;
  29407. serializationObject.maxZ = camera.maxZ;
  29408. serializationObject.inertia = camera.inertia;
  29409. //setting the type
  29410. if (camera instanceof BABYLON.FreeCamera) {
  29411. serializationObject.type = "FreeCamera";
  29412. }
  29413. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29414. serializationObject.type = "ArcRotateCamera";
  29415. }
  29416. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29417. serializationObject.type = "AnaglyphArcRotateCamera";
  29418. }
  29419. else if (camera instanceof BABYLON.GamepadCamera) {
  29420. serializationObject.type = "GamepadCamera";
  29421. }
  29422. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29423. serializationObject.type = "AnaglyphFreeCamera";
  29424. }
  29425. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29426. serializationObject.type = "DeviceOrientationCamera";
  29427. }
  29428. else if (camera instanceof BABYLON.FollowCamera) {
  29429. serializationObject.type = "FollowCamera";
  29430. }
  29431. else if (camera instanceof BABYLON.TouchCamera) {
  29432. serializationObject.type = "TouchCamera";
  29433. }
  29434. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29435. serializationObject.type = "VirtualJoysticksCamera";
  29436. }
  29437. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29438. serializationObject.type = "WebVRFreeCamera";
  29439. }
  29440. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29441. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29442. }
  29443. //special properties of specific cameras
  29444. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29445. var arcCamera = camera;
  29446. serializationObject.alpha = arcCamera.alpha;
  29447. serializationObject.beta = arcCamera.beta;
  29448. serializationObject.radius = arcCamera.radius;
  29449. if (arcCamera.target && arcCamera.target.id) {
  29450. serializationObject.lockedTargetId = arcCamera.target.id;
  29451. }
  29452. }
  29453. else if (camera instanceof BABYLON.FollowCamera) {
  29454. var followCam = camera;
  29455. serializationObject.radius = followCam.radius;
  29456. serializationObject.heightOffset = followCam.heightOffset;
  29457. serializationObject.rotationOffset = followCam.rotationOffset;
  29458. }
  29459. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29460. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  29461. if (camera['_interaxialDistance'] !== undefined) {
  29462. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29463. }
  29464. }
  29465. //general properties that not all cameras have. The [] is due to typescript's type safety
  29466. if (camera['speed'] !== undefined) {
  29467. serializationObject.speed = camera['speed'];
  29468. }
  29469. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29470. serializationObject.target = camera['target'].asArray();
  29471. }
  29472. // Target
  29473. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29474. serializationObject.rotation = camera['rotation'].asArray();
  29475. }
  29476. // Locked target
  29477. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29478. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29479. }
  29480. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29481. serializationObject.applyGravity = camera['applyGravity'] || false;
  29482. if (camera['ellipsoid']) {
  29483. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29484. }
  29485. // Animations
  29486. appendAnimations(camera, serializationObject);
  29487. // Layer mask
  29488. serializationObject.layerMask = camera.layerMask;
  29489. return serializationObject;
  29490. };
  29491. serializeAnimation = function (animation) {
  29492. var serializationObject = {};
  29493. serializationObject.name = animation.name;
  29494. serializationObject.property = animation.targetProperty;
  29495. serializationObject.framePerSecond = animation.framePerSecond;
  29496. serializationObject.dataType = animation.dataType;
  29497. serializationObject.loopBehavior = animation.loopMode;
  29498. var dataType = animation.dataType;
  29499. serializationObject.keys = [];
  29500. var keys = animation.getKeys();
  29501. for (var index = 0; index < keys.length; index++) {
  29502. var animationKey = keys[index];
  29503. var key = {};
  29504. key.frame = animationKey.frame;
  29505. switch (dataType) {
  29506. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29507. key.values = [animationKey.value];
  29508. break;
  29509. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29510. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29511. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29512. key.values = animationKey.value.asArray();
  29513. break;
  29514. }
  29515. serializationObject.keys.push(key);
  29516. }
  29517. return serializationObject;
  29518. };
  29519. var serializeMultiMaterial = function (material) {
  29520. var serializationObject = {};
  29521. serializationObject.name = material.name;
  29522. serializationObject.id = material.id;
  29523. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29524. serializationObject.materials = [];
  29525. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29526. var subMat = material.subMaterials[matIndex];
  29527. if (subMat) {
  29528. serializationObject.materials.push(subMat.id);
  29529. }
  29530. else {
  29531. serializationObject.materials.push(null);
  29532. }
  29533. }
  29534. return serializationObject;
  29535. };
  29536. var serializeTexture;
  29537. var serializeMaterial = function (material) {
  29538. var serializationObject = {};
  29539. serializationObject.name = material.name;
  29540. serializationObject.ambient = material.ambientColor.asArray();
  29541. serializationObject.diffuse = material.diffuseColor.asArray();
  29542. serializationObject.specular = material.specularColor.asArray();
  29543. serializationObject.specularPower = material.specularPower;
  29544. serializationObject.emissive = material.emissiveColor.asArray();
  29545. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29546. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29547. serializationObject.alpha = material.alpha;
  29548. serializationObject.id = material.id;
  29549. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29550. serializationObject.backFaceCulling = material.backFaceCulling;
  29551. if (material.diffuseTexture) {
  29552. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29553. }
  29554. if (material.diffuseFresnelParameters) {
  29555. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29556. }
  29557. if (material.ambientTexture) {
  29558. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29559. }
  29560. if (material.opacityTexture) {
  29561. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29562. }
  29563. if (material.opacityFresnelParameters) {
  29564. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29565. }
  29566. if (material.reflectionTexture) {
  29567. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29568. }
  29569. if (material.reflectionFresnelParameters) {
  29570. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29571. }
  29572. if (material.emissiveTexture) {
  29573. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29574. }
  29575. if (material.lightmapTexture) {
  29576. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29577. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29578. }
  29579. if (material.emissiveFresnelParameters) {
  29580. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29581. }
  29582. if (material.specularTexture) {
  29583. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29584. }
  29585. if (material.bumpTexture) {
  29586. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29587. }
  29588. return serializationObject;
  29589. };
  29590. serializeTexture = function (texture) {
  29591. var serializationObject = {};
  29592. if (!texture.name) {
  29593. return null;
  29594. }
  29595. if (texture instanceof BABYLON.CubeTexture) {
  29596. serializationObject.name = texture.name;
  29597. serializationObject.hasAlpha = texture.hasAlpha;
  29598. serializationObject.isCube = true;
  29599. serializationObject.level = texture.level;
  29600. serializationObject.coordinatesMode = texture.coordinatesMode;
  29601. return serializationObject;
  29602. }
  29603. var index;
  29604. if (texture instanceof BABYLON.MirrorTexture) {
  29605. var mirrorTexture = texture;
  29606. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29607. serializationObject.renderList = [];
  29608. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29609. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29610. }
  29611. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29612. }
  29613. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29614. var renderTargetTexture = texture;
  29615. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29616. serializationObject.renderList = [];
  29617. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29618. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29619. }
  29620. }
  29621. var regularTexture = texture;
  29622. serializationObject.name = texture.name;
  29623. serializationObject.hasAlpha = texture.hasAlpha;
  29624. serializationObject.level = texture.level;
  29625. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29626. serializationObject.coordinatesMode = texture.coordinatesMode;
  29627. serializationObject.uOffset = regularTexture.uOffset;
  29628. serializationObject.vOffset = regularTexture.vOffset;
  29629. serializationObject.uScale = regularTexture.uScale;
  29630. serializationObject.vScale = regularTexture.vScale;
  29631. serializationObject.uAng = regularTexture.uAng;
  29632. serializationObject.vAng = regularTexture.vAng;
  29633. serializationObject.wAng = regularTexture.wAng;
  29634. serializationObject.wrapU = texture.wrapU;
  29635. serializationObject.wrapV = texture.wrapV;
  29636. // Animations
  29637. appendAnimations(texture, serializationObject);
  29638. return serializationObject;
  29639. };
  29640. var serializeSkeleton = function (skeleton) {
  29641. var serializationObject = {};
  29642. serializationObject.name = skeleton.name;
  29643. serializationObject.id = skeleton.id;
  29644. serializationObject.bones = [];
  29645. for (var index = 0; index < skeleton.bones.length; index++) {
  29646. var bone = skeleton.bones[index];
  29647. var serializedBone = {
  29648. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29649. name: bone.name,
  29650. matrix: bone.getLocalMatrix().toArray()
  29651. };
  29652. serializationObject.bones.push(serializedBone);
  29653. if (bone.animations && bone.animations.length > 0) {
  29654. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29655. }
  29656. }
  29657. return serializationObject;
  29658. };
  29659. var serializeParticleSystem = function (particleSystem) {
  29660. var serializationObject = {};
  29661. serializationObject.emitterId = particleSystem.emitter.id;
  29662. serializationObject.capacity = particleSystem.getCapacity();
  29663. if (particleSystem.particleTexture) {
  29664. serializationObject.textureName = particleSystem.particleTexture.name;
  29665. }
  29666. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29667. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29668. serializationObject.minSize = particleSystem.minSize;
  29669. serializationObject.maxSize = particleSystem.maxSize;
  29670. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29671. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29672. serializationObject.emitRate = particleSystem.emitRate;
  29673. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29674. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29675. serializationObject.gravity = particleSystem.gravity.asArray();
  29676. serializationObject.direction1 = particleSystem.direction1.asArray();
  29677. serializationObject.direction2 = particleSystem.direction2.asArray();
  29678. serializationObject.color1 = particleSystem.color1.asArray();
  29679. serializationObject.color2 = particleSystem.color2.asArray();
  29680. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29681. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29682. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29683. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29684. serializationObject.blendMode = particleSystem.blendMode;
  29685. return serializationObject;
  29686. };
  29687. var serializeLensFlareSystem = function (lensFlareSystem) {
  29688. var serializationObject = {};
  29689. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29690. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29691. serializationObject.flares = [];
  29692. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29693. var flare = lensFlareSystem.lensFlares[index];
  29694. serializationObject.flares.push({
  29695. size: flare.size,
  29696. position: flare.position,
  29697. color: flare.color.asArray(),
  29698. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29699. });
  29700. }
  29701. return serializationObject;
  29702. };
  29703. var serializeShadowGenerator = function (light) {
  29704. var serializationObject = {};
  29705. var shadowGenerator = light.getShadowGenerator();
  29706. serializationObject.lightId = light.id;
  29707. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29708. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29709. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29710. serializationObject.renderList = [];
  29711. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29712. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29713. serializationObject.renderList.push(mesh.id);
  29714. }
  29715. return serializationObject;
  29716. };
  29717. var serializedGeometries = [];
  29718. var serializeVertexData;
  29719. var serializeTorusKnot;
  29720. var serializePlane;
  29721. var serializeGround;
  29722. var serializeTorus;
  29723. var serializeCylinder;
  29724. var serializeSphere;
  29725. var serializeBox;
  29726. var serializeGeometry = function (geometry, serializationGeometries) {
  29727. if (serializedGeometries[geometry.id]) {
  29728. return;
  29729. }
  29730. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29731. serializationGeometries.boxes.push(serializeBox(geometry));
  29732. }
  29733. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29734. serializationGeometries.spheres.push(serializeSphere(geometry));
  29735. }
  29736. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29737. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29738. }
  29739. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29740. serializationGeometries.toruses.push(serializeTorus(geometry));
  29741. }
  29742. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29743. serializationGeometries.grounds.push(serializeGround(geometry));
  29744. }
  29745. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29746. serializationGeometries.planes.push(serializePlane(geometry));
  29747. }
  29748. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29749. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29750. }
  29751. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29752. throw new Error("Unknown primitive type");
  29753. }
  29754. else {
  29755. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29756. }
  29757. serializedGeometries[geometry.id] = true;
  29758. };
  29759. var serializeGeometryBase = function (geometry) {
  29760. var serializationObject = {};
  29761. serializationObject.id = geometry.id;
  29762. if (BABYLON.Tags.HasTags(geometry)) {
  29763. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29764. }
  29765. return serializationObject;
  29766. };
  29767. serializeVertexData = function (vertexData) {
  29768. var serializationObject = serializeGeometryBase(vertexData);
  29769. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29770. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29771. }
  29772. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29773. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29774. }
  29775. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29776. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29777. }
  29778. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29779. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29780. }
  29781. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29782. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29783. }
  29784. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29785. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29786. }
  29787. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29788. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29789. }
  29790. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29791. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29792. }
  29793. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29794. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29795. }
  29796. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29797. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29798. serializationObject.matricesIndices._isExpanded = true;
  29799. }
  29800. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29801. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29802. }
  29803. serializationObject.indices = vertexData.getIndices();
  29804. return serializationObject;
  29805. };
  29806. var serializePrimitive = function (primitive) {
  29807. var serializationObject = serializeGeometryBase(primitive);
  29808. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29809. return serializationObject;
  29810. };
  29811. serializeBox = function (box) {
  29812. var serializationObject = serializePrimitive(box);
  29813. serializationObject.size = box.size;
  29814. return serializationObject;
  29815. };
  29816. serializeSphere = function (sphere) {
  29817. var serializationObject = serializePrimitive(sphere);
  29818. serializationObject.segments = sphere.segments;
  29819. serializationObject.diameter = sphere.diameter;
  29820. return serializationObject;
  29821. };
  29822. serializeCylinder = function (cylinder) {
  29823. var serializationObject = serializePrimitive(cylinder);
  29824. serializationObject.height = cylinder.height;
  29825. serializationObject.diameterTop = cylinder.diameterTop;
  29826. serializationObject.diameterBottom = cylinder.diameterBottom;
  29827. serializationObject.tessellation = cylinder.tessellation;
  29828. return serializationObject;
  29829. };
  29830. serializeTorus = function (torus) {
  29831. var serializationObject = serializePrimitive(torus);
  29832. serializationObject.diameter = torus.diameter;
  29833. serializationObject.thickness = torus.thickness;
  29834. serializationObject.tessellation = torus.tessellation;
  29835. return serializationObject;
  29836. };
  29837. serializeGround = function (ground) {
  29838. var serializationObject = serializePrimitive(ground);
  29839. serializationObject.width = ground.width;
  29840. serializationObject.height = ground.height;
  29841. serializationObject.subdivisions = ground.subdivisions;
  29842. return serializationObject;
  29843. };
  29844. serializePlane = function (plane) {
  29845. var serializationObject = serializePrimitive(plane);
  29846. serializationObject.size = plane.size;
  29847. return serializationObject;
  29848. };
  29849. serializeTorusKnot = function (torusKnot) {
  29850. var serializationObject = serializePrimitive(torusKnot);
  29851. serializationObject.radius = torusKnot.radius;
  29852. serializationObject.tube = torusKnot.tube;
  29853. serializationObject.radialSegments = torusKnot.radialSegments;
  29854. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29855. serializationObject.p = torusKnot.p;
  29856. serializationObject.q = torusKnot.q;
  29857. return serializationObject;
  29858. };
  29859. var serializeMesh = function (mesh, serializationScene) {
  29860. var serializationObject = {};
  29861. serializationObject.name = mesh.name;
  29862. serializationObject.id = mesh.id;
  29863. if (BABYLON.Tags.HasTags(mesh)) {
  29864. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29865. }
  29866. serializationObject.position = mesh.position.asArray();
  29867. if (mesh.rotationQuaternion) {
  29868. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29869. }
  29870. else if (mesh.rotation) {
  29871. serializationObject.rotation = mesh.rotation.asArray();
  29872. }
  29873. serializationObject.scaling = mesh.scaling.asArray();
  29874. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29875. serializationObject.isEnabled = mesh.isEnabled();
  29876. serializationObject.isVisible = mesh.isVisible;
  29877. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29878. serializationObject.pickable = mesh.isPickable;
  29879. serializationObject.receiveShadows = mesh.receiveShadows;
  29880. serializationObject.billboardMode = mesh.billboardMode;
  29881. serializationObject.visibility = mesh.visibility;
  29882. serializationObject.checkCollisions = mesh.checkCollisions;
  29883. // Parent
  29884. if (mesh.parent) {
  29885. serializationObject.parentId = mesh.parent.id;
  29886. }
  29887. // Geometry
  29888. var geometry = mesh._geometry;
  29889. if (geometry) {
  29890. var geometryId = geometry.id;
  29891. serializationObject.geometryId = geometryId;
  29892. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29893. // 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
  29894. serializeGeometry(geometry, serializationScene.geometries);
  29895. }
  29896. // SubMeshes
  29897. serializationObject.subMeshes = [];
  29898. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29899. var subMesh = mesh.subMeshes[subIndex];
  29900. serializationObject.subMeshes.push({
  29901. materialIndex: subMesh.materialIndex,
  29902. verticesStart: subMesh.verticesStart,
  29903. verticesCount: subMesh.verticesCount,
  29904. indexStart: subMesh.indexStart,
  29905. indexCount: subMesh.indexCount
  29906. });
  29907. }
  29908. }
  29909. // Material
  29910. if (mesh.material) {
  29911. serializationObject.materialId = mesh.material.id;
  29912. }
  29913. else {
  29914. mesh.material = null;
  29915. }
  29916. // Skeleton
  29917. if (mesh.skeleton) {
  29918. serializationObject.skeletonId = mesh.skeleton.id;
  29919. }
  29920. // Physics
  29921. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29922. serializationObject.physicsMass = mesh.getPhysicsMass();
  29923. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29924. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29925. switch (mesh.getPhysicsImpostor()) {
  29926. case BABYLON.PhysicsEngine.BoxImpostor:
  29927. serializationObject.physicsImpostor = 1;
  29928. break;
  29929. case BABYLON.PhysicsEngine.SphereImpostor:
  29930. serializationObject.physicsImpostor = 2;
  29931. break;
  29932. }
  29933. }
  29934. // Instances
  29935. serializationObject.instances = [];
  29936. for (var index = 0; index < mesh.instances.length; index++) {
  29937. var instance = mesh.instances[index];
  29938. var serializationInstance = {
  29939. name: instance.name,
  29940. position: instance.position.asArray(),
  29941. rotation: instance.rotation.asArray(),
  29942. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29943. scaling: instance.scaling.asArray()
  29944. };
  29945. serializationObject.instances.push(serializationInstance);
  29946. // Animations
  29947. appendAnimations(instance, serializationInstance);
  29948. }
  29949. // Animations
  29950. appendAnimations(mesh, serializationObject);
  29951. // Layer mask
  29952. serializationObject.layerMask = mesh.layerMask;
  29953. return serializationObject;
  29954. };
  29955. var finalizeSingleMesh = function (mesh, serializationObject) {
  29956. //only works if the mesh is already loaded
  29957. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29958. //serialize material
  29959. if (mesh.material) {
  29960. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29961. serializationObject.materials = serializationObject.materials || [];
  29962. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29963. serializationObject.materials.push(serializeMaterial(mesh.material));
  29964. }
  29965. }
  29966. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29967. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29968. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29969. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29970. }
  29971. }
  29972. }
  29973. //serialize geometry
  29974. var geometry = mesh._geometry;
  29975. if (geometry) {
  29976. if (!serializationObject.geometries) {
  29977. serializationObject.geometries = {};
  29978. serializationObject.geometries.boxes = [];
  29979. serializationObject.geometries.spheres = [];
  29980. serializationObject.geometries.cylinders = [];
  29981. serializationObject.geometries.toruses = [];
  29982. serializationObject.geometries.grounds = [];
  29983. serializationObject.geometries.planes = [];
  29984. serializationObject.geometries.torusKnots = [];
  29985. serializationObject.geometries.vertexData = [];
  29986. }
  29987. serializeGeometry(geometry, serializationObject.geometries);
  29988. }
  29989. // Skeletons
  29990. if (mesh.skeleton) {
  29991. serializationObject.skeletons = serializationObject.skeletons || [];
  29992. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29993. }
  29994. //serialize the actual mesh
  29995. serializationObject.meshes = serializationObject.meshes || [];
  29996. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29997. }
  29998. };
  29999. var SceneSerializer = (function () {
  30000. function SceneSerializer() {
  30001. }
  30002. SceneSerializer.Serialize = function (scene) {
  30003. var serializationObject = {};
  30004. // Scene
  30005. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30006. serializationObject.autoClear = scene.autoClear;
  30007. serializationObject.clearColor = scene.clearColor.asArray();
  30008. serializationObject.ambientColor = scene.ambientColor.asArray();
  30009. serializationObject.gravity = scene.gravity.asArray();
  30010. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30011. serializationObject.workerCollisions = scene.workerCollisions;
  30012. // Fog
  30013. if (scene.fogMode && scene.fogMode !== 0) {
  30014. serializationObject.fogMode = scene.fogMode;
  30015. serializationObject.fogColor = scene.fogColor.asArray();
  30016. serializationObject.fogStart = scene.fogStart;
  30017. serializationObject.fogEnd = scene.fogEnd;
  30018. serializationObject.fogDensity = scene.fogDensity;
  30019. }
  30020. //Physics
  30021. if (scene.isPhysicsEnabled()) {
  30022. serializationObject.physicsEnabled = true;
  30023. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30024. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30025. }
  30026. // Lights
  30027. serializationObject.lights = [];
  30028. var index;
  30029. var light;
  30030. for (index = 0; index < scene.lights.length; index++) {
  30031. light = scene.lights[index];
  30032. serializationObject.lights.push(serializeLight(light));
  30033. }
  30034. // Cameras
  30035. serializationObject.cameras = [];
  30036. for (index = 0; index < scene.cameras.length; index++) {
  30037. var camera = scene.cameras[index];
  30038. serializationObject.cameras.push(serializeCamera(camera));
  30039. }
  30040. if (scene.activeCamera) {
  30041. serializationObject.activeCameraID = scene.activeCamera.id;
  30042. }
  30043. // Materials
  30044. serializationObject.materials = [];
  30045. serializationObject.multiMaterials = [];
  30046. var material;
  30047. for (index = 0; index < scene.materials.length; index++) {
  30048. material = scene.materials[index];
  30049. serializationObject.materials.push(serializeMaterial(material));
  30050. }
  30051. // MultiMaterials
  30052. serializationObject.multiMaterials = [];
  30053. for (index = 0; index < scene.multiMaterials.length; index++) {
  30054. var multiMaterial = scene.multiMaterials[index];
  30055. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  30056. }
  30057. for (index = 0; index < scene.materials.length; index++) {
  30058. material = scene.materials[index];
  30059. if (material instanceof BABYLON.StandardMaterial) {
  30060. serializationObject.materials.push(serializeMaterial(material));
  30061. }
  30062. else if (material instanceof BABYLON.MultiMaterial) {
  30063. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  30064. }
  30065. }
  30066. // Skeletons
  30067. serializationObject.skeletons = [];
  30068. for (index = 0; index < scene.skeletons.length; index++) {
  30069. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  30070. }
  30071. // Geometries
  30072. serializationObject.geometries = {};
  30073. serializationObject.geometries.boxes = [];
  30074. serializationObject.geometries.spheres = [];
  30075. serializationObject.geometries.cylinders = [];
  30076. serializationObject.geometries.toruses = [];
  30077. serializationObject.geometries.grounds = [];
  30078. serializationObject.geometries.planes = [];
  30079. serializationObject.geometries.torusKnots = [];
  30080. serializationObject.geometries.vertexData = [];
  30081. serializedGeometries = [];
  30082. var geometries = scene.getGeometries();
  30083. for (index = 0; index < geometries.length; index++) {
  30084. var geometry = geometries[index];
  30085. if (geometry.isReady()) {
  30086. serializeGeometry(geometry, serializationObject.geometries);
  30087. }
  30088. }
  30089. // Meshes
  30090. serializationObject.meshes = [];
  30091. for (index = 0; index < scene.meshes.length; index++) {
  30092. var abstractMesh = scene.meshes[index];
  30093. if (abstractMesh instanceof BABYLON.Mesh) {
  30094. var mesh = abstractMesh;
  30095. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30096. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30097. }
  30098. }
  30099. }
  30100. // Particles Systems
  30101. serializationObject.particleSystems = [];
  30102. for (index = 0; index < scene.particleSystems.length; index++) {
  30103. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  30104. }
  30105. // Lens flares
  30106. serializationObject.lensFlareSystems = [];
  30107. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30108. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30109. }
  30110. // Shadows
  30111. serializationObject.shadowGenerators = [];
  30112. for (index = 0; index < scene.lights.length; index++) {
  30113. light = scene.lights[index];
  30114. if (light.getShadowGenerator()) {
  30115. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30116. }
  30117. }
  30118. return serializationObject;
  30119. };
  30120. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30121. if (withParents === void 0) { withParents = false; }
  30122. if (withChildren === void 0) { withChildren = false; }
  30123. var serializationObject = {};
  30124. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30125. if (withParents || withChildren) {
  30126. //deliberate for loop! not for each, appended should be processed as well.
  30127. for (var i = 0; i < toSerialize.length; ++i) {
  30128. if (withChildren) {
  30129. toSerialize[i].getDescendants().forEach(function (node) {
  30130. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30131. toSerialize.push(node);
  30132. }
  30133. });
  30134. }
  30135. //make sure the array doesn't contain the object already
  30136. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30137. toSerialize.push(toSerialize[i].parent);
  30138. }
  30139. }
  30140. }
  30141. toSerialize.forEach(function (mesh) {
  30142. finalizeSingleMesh(mesh, serializationObject);
  30143. });
  30144. return serializationObject;
  30145. };
  30146. return SceneSerializer;
  30147. })();
  30148. BABYLON.SceneSerializer = SceneSerializer;
  30149. })(BABYLON || (BABYLON = {}));
  30150. var BABYLON;
  30151. (function (BABYLON) {
  30152. // Unique ID when we import meshes from Babylon to CSG
  30153. var currentCSGMeshId = 0;
  30154. // # class Vertex
  30155. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30156. // one to provide additional features like texture coordinates and vertex
  30157. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30158. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30159. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30160. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30161. // is not used anywhere else.
  30162. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30163. var Vertex = (function () {
  30164. function Vertex(pos, normal, uv) {
  30165. this.pos = pos;
  30166. this.normal = normal;
  30167. this.uv = uv;
  30168. }
  30169. Vertex.prototype.clone = function () {
  30170. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30171. };
  30172. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30173. // orientation of a polygon is flipped.
  30174. Vertex.prototype.flip = function () {
  30175. this.normal = this.normal.scale(-1);
  30176. };
  30177. // Create a new vertex between this vertex and `other` by linearly
  30178. // interpolating all properties using a parameter of `t`. Subclasses should
  30179. // override this to interpolate additional properties.
  30180. Vertex.prototype.interpolate = function (other, t) {
  30181. 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));
  30182. };
  30183. return Vertex;
  30184. })();
  30185. // # class Plane
  30186. // Represents a plane in 3D space.
  30187. var Plane = (function () {
  30188. function Plane(normal, w) {
  30189. this.normal = normal;
  30190. this.w = w;
  30191. }
  30192. Plane.FromPoints = function (a, b, c) {
  30193. var v0 = c.subtract(a);
  30194. var v1 = b.subtract(a);
  30195. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30196. return null;
  30197. }
  30198. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30199. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30200. };
  30201. Plane.prototype.clone = function () {
  30202. return new Plane(this.normal.clone(), this.w);
  30203. };
  30204. Plane.prototype.flip = function () {
  30205. this.normal.scaleInPlace(-1);
  30206. this.w = -this.w;
  30207. };
  30208. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30209. // fragments in the appropriate lists. Coplanar polygons go into either
  30210. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30211. // respect to this plane. Polygons in front or in back of this plane go into
  30212. // either `front` or `back`.
  30213. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30214. var COPLANAR = 0;
  30215. var FRONT = 1;
  30216. var BACK = 2;
  30217. var SPANNING = 3;
  30218. // Classify each point as well as the entire polygon into one of the above
  30219. // four classes.
  30220. var polygonType = 0;
  30221. var types = [];
  30222. var i;
  30223. var t;
  30224. for (i = 0; i < polygon.vertices.length; i++) {
  30225. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30226. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30227. polygonType |= type;
  30228. types.push(type);
  30229. }
  30230. // Put the polygon in the correct list, splitting it when necessary.
  30231. switch (polygonType) {
  30232. case COPLANAR:
  30233. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30234. break;
  30235. case FRONT:
  30236. front.push(polygon);
  30237. break;
  30238. case BACK:
  30239. back.push(polygon);
  30240. break;
  30241. case SPANNING:
  30242. var f = [], b = [];
  30243. for (i = 0; i < polygon.vertices.length; i++) {
  30244. var j = (i + 1) % polygon.vertices.length;
  30245. var ti = types[i], tj = types[j];
  30246. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30247. if (ti !== BACK)
  30248. f.push(vi);
  30249. if (ti !== FRONT)
  30250. b.push(ti !== BACK ? vi.clone() : vi);
  30251. if ((ti | tj) === SPANNING) {
  30252. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30253. var v = vi.interpolate(vj, t);
  30254. f.push(v);
  30255. b.push(v.clone());
  30256. }
  30257. }
  30258. var poly;
  30259. if (f.length >= 3) {
  30260. poly = new Polygon(f, polygon.shared);
  30261. if (poly.plane)
  30262. front.push(poly);
  30263. }
  30264. if (b.length >= 3) {
  30265. poly = new Polygon(b, polygon.shared);
  30266. if (poly.plane)
  30267. back.push(poly);
  30268. }
  30269. break;
  30270. }
  30271. };
  30272. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30273. // point is on the plane.
  30274. Plane.EPSILON = 1e-5;
  30275. return Plane;
  30276. })();
  30277. // # class Polygon
  30278. // Represents a convex polygon. The vertices used to initialize a polygon must
  30279. // be coplanar and form a convex loop.
  30280. //
  30281. // Each convex polygon has a `shared` property, which is shared between all
  30282. // polygons that are clones of each other or were split from the same polygon.
  30283. // This can be used to define per-polygon properties (such as surface color).
  30284. var Polygon = (function () {
  30285. function Polygon(vertices, shared) {
  30286. this.vertices = vertices;
  30287. this.shared = shared;
  30288. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30289. }
  30290. Polygon.prototype.clone = function () {
  30291. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30292. return new Polygon(vertices, this.shared);
  30293. };
  30294. Polygon.prototype.flip = function () {
  30295. this.vertices.reverse().map(function (v) { v.flip(); });
  30296. this.plane.flip();
  30297. };
  30298. return Polygon;
  30299. })();
  30300. // # class Node
  30301. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30302. // by picking a polygon to split along. That polygon (and all other coplanar
  30303. // polygons) are added directly to that node and the other polygons are added to
  30304. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30305. // no distinction between internal and leaf nodes.
  30306. var Node = (function () {
  30307. function Node(polygons) {
  30308. this.plane = null;
  30309. this.front = null;
  30310. this.back = null;
  30311. this.polygons = [];
  30312. if (polygons) {
  30313. this.build(polygons);
  30314. }
  30315. }
  30316. Node.prototype.clone = function () {
  30317. var node = new Node();
  30318. node.plane = this.plane && this.plane.clone();
  30319. node.front = this.front && this.front.clone();
  30320. node.back = this.back && this.back.clone();
  30321. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30322. return node;
  30323. };
  30324. // Convert solid space to empty space and empty space to solid space.
  30325. Node.prototype.invert = function () {
  30326. for (var i = 0; i < this.polygons.length; i++) {
  30327. this.polygons[i].flip();
  30328. }
  30329. if (this.plane) {
  30330. this.plane.flip();
  30331. }
  30332. if (this.front) {
  30333. this.front.invert();
  30334. }
  30335. if (this.back) {
  30336. this.back.invert();
  30337. }
  30338. var temp = this.front;
  30339. this.front = this.back;
  30340. this.back = temp;
  30341. };
  30342. // Recursively remove all polygons in `polygons` that are inside this BSP
  30343. // tree.
  30344. Node.prototype.clipPolygons = function (polygons) {
  30345. if (!this.plane)
  30346. return polygons.slice();
  30347. var front = [], back = [];
  30348. for (var i = 0; i < polygons.length; i++) {
  30349. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30350. }
  30351. if (this.front) {
  30352. front = this.front.clipPolygons(front);
  30353. }
  30354. if (this.back) {
  30355. back = this.back.clipPolygons(back);
  30356. }
  30357. else {
  30358. back = [];
  30359. }
  30360. return front.concat(back);
  30361. };
  30362. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30363. // `bsp`.
  30364. Node.prototype.clipTo = function (bsp) {
  30365. this.polygons = bsp.clipPolygons(this.polygons);
  30366. if (this.front)
  30367. this.front.clipTo(bsp);
  30368. if (this.back)
  30369. this.back.clipTo(bsp);
  30370. };
  30371. // Return a list of all polygons in this BSP tree.
  30372. Node.prototype.allPolygons = function () {
  30373. var polygons = this.polygons.slice();
  30374. if (this.front)
  30375. polygons = polygons.concat(this.front.allPolygons());
  30376. if (this.back)
  30377. polygons = polygons.concat(this.back.allPolygons());
  30378. return polygons;
  30379. };
  30380. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30381. // new polygons are filtered down to the bottom of the tree and become new
  30382. // nodes there. Each set of polygons is partitioned using the first polygon
  30383. // (no heuristic is used to pick a good split).
  30384. Node.prototype.build = function (polygons) {
  30385. if (!polygons.length)
  30386. return;
  30387. if (!this.plane)
  30388. this.plane = polygons[0].plane.clone();
  30389. var front = [], back = [];
  30390. for (var i = 0; i < polygons.length; i++) {
  30391. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30392. }
  30393. if (front.length) {
  30394. if (!this.front)
  30395. this.front = new Node();
  30396. this.front.build(front);
  30397. }
  30398. if (back.length) {
  30399. if (!this.back)
  30400. this.back = new Node();
  30401. this.back.build(back);
  30402. }
  30403. };
  30404. return Node;
  30405. })();
  30406. var CSG = (function () {
  30407. function CSG() {
  30408. this.polygons = new Array();
  30409. }
  30410. // Convert BABYLON.Mesh to BABYLON.CSG
  30411. CSG.FromMesh = function (mesh) {
  30412. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30413. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30414. if (mesh instanceof BABYLON.Mesh) {
  30415. mesh.computeWorldMatrix(true);
  30416. matrix = mesh.getWorldMatrix();
  30417. meshPosition = mesh.position.clone();
  30418. meshRotation = mesh.rotation.clone();
  30419. if (mesh.rotationQuaternion) {
  30420. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30421. }
  30422. meshScaling = mesh.scaling.clone();
  30423. }
  30424. else {
  30425. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30426. }
  30427. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30428. var subMeshes = mesh.subMeshes;
  30429. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30430. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30431. vertices = [];
  30432. for (var j = 0; j < 3; j++) {
  30433. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30434. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30435. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30436. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30437. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30438. vertex = new Vertex(position, normal, uv);
  30439. vertices.push(vertex);
  30440. }
  30441. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30442. // To handle the case of degenerated triangle
  30443. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30444. if (polygon.plane)
  30445. polygons.push(polygon);
  30446. }
  30447. }
  30448. var csg = CSG.FromPolygons(polygons);
  30449. csg.matrix = matrix;
  30450. csg.position = meshPosition;
  30451. csg.rotation = meshRotation;
  30452. csg.scaling = meshScaling;
  30453. csg.rotationQuaternion = meshRotationQuaternion;
  30454. currentCSGMeshId++;
  30455. return csg;
  30456. };
  30457. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30458. CSG.FromPolygons = function (polygons) {
  30459. var csg = new CSG();
  30460. csg.polygons = polygons;
  30461. return csg;
  30462. };
  30463. CSG.prototype.clone = function () {
  30464. var csg = new CSG();
  30465. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30466. csg.copyTransformAttributes(this);
  30467. return csg;
  30468. };
  30469. CSG.prototype.toPolygons = function () {
  30470. return this.polygons;
  30471. };
  30472. CSG.prototype.union = function (csg) {
  30473. var a = new Node(this.clone().polygons);
  30474. var b = new Node(csg.clone().polygons);
  30475. a.clipTo(b);
  30476. b.clipTo(a);
  30477. b.invert();
  30478. b.clipTo(a);
  30479. b.invert();
  30480. a.build(b.allPolygons());
  30481. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30482. };
  30483. CSG.prototype.unionInPlace = function (csg) {
  30484. var a = new Node(this.polygons);
  30485. var b = new Node(csg.polygons);
  30486. a.clipTo(b);
  30487. b.clipTo(a);
  30488. b.invert();
  30489. b.clipTo(a);
  30490. b.invert();
  30491. a.build(b.allPolygons());
  30492. this.polygons = a.allPolygons();
  30493. };
  30494. CSG.prototype.subtract = function (csg) {
  30495. var a = new Node(this.clone().polygons);
  30496. var b = new Node(csg.clone().polygons);
  30497. a.invert();
  30498. a.clipTo(b);
  30499. b.clipTo(a);
  30500. b.invert();
  30501. b.clipTo(a);
  30502. b.invert();
  30503. a.build(b.allPolygons());
  30504. a.invert();
  30505. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30506. };
  30507. CSG.prototype.subtractInPlace = function (csg) {
  30508. var a = new Node(this.polygons);
  30509. var b = new Node(csg.polygons);
  30510. a.invert();
  30511. a.clipTo(b);
  30512. b.clipTo(a);
  30513. b.invert();
  30514. b.clipTo(a);
  30515. b.invert();
  30516. a.build(b.allPolygons());
  30517. a.invert();
  30518. this.polygons = a.allPolygons();
  30519. };
  30520. CSG.prototype.intersect = function (csg) {
  30521. var a = new Node(this.clone().polygons);
  30522. var b = new Node(csg.clone().polygons);
  30523. a.invert();
  30524. b.clipTo(a);
  30525. b.invert();
  30526. a.clipTo(b);
  30527. b.clipTo(a);
  30528. a.build(b.allPolygons());
  30529. a.invert();
  30530. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30531. };
  30532. CSG.prototype.intersectInPlace = function (csg) {
  30533. var a = new Node(this.polygons);
  30534. var b = new Node(csg.polygons);
  30535. a.invert();
  30536. b.clipTo(a);
  30537. b.invert();
  30538. a.clipTo(b);
  30539. b.clipTo(a);
  30540. a.build(b.allPolygons());
  30541. a.invert();
  30542. this.polygons = a.allPolygons();
  30543. };
  30544. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30545. // not modified.
  30546. CSG.prototype.inverse = function () {
  30547. var csg = this.clone();
  30548. csg.inverseInPlace();
  30549. return csg;
  30550. };
  30551. CSG.prototype.inverseInPlace = function () {
  30552. this.polygons.map(function (p) { p.flip(); });
  30553. };
  30554. // This is used to keep meshes transformations so they can be restored
  30555. // when we build back a Babylon Mesh
  30556. // NB : All CSG operations are performed in world coordinates
  30557. CSG.prototype.copyTransformAttributes = function (csg) {
  30558. this.matrix = csg.matrix;
  30559. this.position = csg.position;
  30560. this.rotation = csg.rotation;
  30561. this.scaling = csg.scaling;
  30562. this.rotationQuaternion = csg.rotationQuaternion;
  30563. return this;
  30564. };
  30565. // Build Raw mesh from CSG
  30566. // Coordinates here are in world space
  30567. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30568. var matrix = this.matrix.clone();
  30569. matrix.invert();
  30570. 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;
  30571. if (keepSubMeshes) {
  30572. // Sort Polygons, since subMeshes are indices range
  30573. polygons.sort(function (a, b) {
  30574. if (a.shared.meshId === b.shared.meshId) {
  30575. return a.shared.subMeshId - b.shared.subMeshId;
  30576. }
  30577. else {
  30578. return a.shared.meshId - b.shared.meshId;
  30579. }
  30580. });
  30581. }
  30582. for (var i = 0, il = polygons.length; i < il; i++) {
  30583. polygon = polygons[i];
  30584. // Building SubMeshes
  30585. if (!subMesh_dict[polygon.shared.meshId]) {
  30586. subMesh_dict[polygon.shared.meshId] = {};
  30587. }
  30588. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30589. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30590. indexStart: +Infinity,
  30591. indexEnd: -Infinity,
  30592. materialIndex: polygon.shared.materialIndex
  30593. };
  30594. }
  30595. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30596. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30597. polygonIndices[0] = 0;
  30598. polygonIndices[1] = j - 1;
  30599. polygonIndices[2] = j;
  30600. for (var k = 0; k < 3; k++) {
  30601. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30602. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30603. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30604. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30605. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30606. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30607. // Check if 2 points can be merged
  30608. if (!(typeof vertex_idx !== 'undefined' &&
  30609. normals[vertex_idx * 3] === localNormal.x &&
  30610. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30611. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30612. uvs[vertex_idx * 2] === uv.x &&
  30613. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30614. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30615. uvs.push(uv.x, uv.y);
  30616. normals.push(normal.x, normal.y, normal.z);
  30617. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30618. }
  30619. indices.push(vertex_idx);
  30620. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30621. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30622. currentIndex++;
  30623. }
  30624. }
  30625. }
  30626. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30627. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30628. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30629. mesh.setIndices(indices);
  30630. if (keepSubMeshes) {
  30631. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30632. var materialIndexOffset = 0, materialMaxIndex;
  30633. mesh.subMeshes = new Array();
  30634. for (var m in subMesh_dict) {
  30635. materialMaxIndex = -1;
  30636. for (var sm in subMesh_dict[m]) {
  30637. subMesh_obj = subMesh_dict[m][sm];
  30638. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30639. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30640. }
  30641. materialIndexOffset += ++materialMaxIndex;
  30642. }
  30643. }
  30644. return mesh;
  30645. };
  30646. // Build Mesh from CSG taking material and transforms into account
  30647. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30648. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30649. mesh.material = material;
  30650. mesh.position.copyFrom(this.position);
  30651. mesh.rotation.copyFrom(this.rotation);
  30652. if (this.rotationQuaternion) {
  30653. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30654. }
  30655. mesh.scaling.copyFrom(this.scaling);
  30656. mesh.computeWorldMatrix(true);
  30657. return mesh;
  30658. };
  30659. return CSG;
  30660. })();
  30661. BABYLON.CSG = CSG;
  30662. })(BABYLON || (BABYLON = {}));
  30663. var BABYLON;
  30664. (function (BABYLON) {
  30665. var VRDistortionCorrectionPostProcess = (function (_super) {
  30666. __extends(VRDistortionCorrectionPostProcess, _super);
  30667. //ANY
  30668. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30669. var _this = this;
  30670. _super.call(this, name, "vrDistortionCorrection", [
  30671. 'LensCenter',
  30672. 'Scale',
  30673. 'ScaleIn',
  30674. 'HmdWarpParam'
  30675. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30676. this._isRightEye = isRightEye;
  30677. this._distortionFactors = vrMetrics.distortionK;
  30678. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30679. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30680. this.onSizeChanged = function () {
  30681. _this.aspectRatio = _this.width * .5 / _this.height;
  30682. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30683. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30684. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30685. };
  30686. this.onApply = function (effect) {
  30687. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30688. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30689. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30690. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30691. };
  30692. }
  30693. return VRDistortionCorrectionPostProcess;
  30694. })(BABYLON.PostProcess);
  30695. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30696. })(BABYLON || (BABYLON = {}));
  30697. // Mainly based on these 2 articles :
  30698. // 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
  30699. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30700. var BABYLON;
  30701. (function (BABYLON) {
  30702. (function (JoystickAxis) {
  30703. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30704. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30705. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30706. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30707. var JoystickAxis = BABYLON.JoystickAxis;
  30708. var VirtualJoystick = (function () {
  30709. function VirtualJoystick(leftJoystick) {
  30710. var _this = this;
  30711. if (leftJoystick) {
  30712. this._leftJoystick = true;
  30713. }
  30714. else {
  30715. this._leftJoystick = false;
  30716. }
  30717. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30718. VirtualJoystick._globalJoystickIndex++;
  30719. // By default left & right arrow keys are moving the X
  30720. // and up & down keys are moving the Y
  30721. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30722. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30723. this.reverseLeftRight = false;
  30724. this.reverseUpDown = false;
  30725. // collections of pointers
  30726. this._touches = new BABYLON.SmartCollection();
  30727. this.deltaPosition = BABYLON.Vector3.Zero();
  30728. this._joystickSensibility = 25;
  30729. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30730. this._rotationSpeed = 25;
  30731. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30732. this._rotateOnAxisRelativeToMesh = false;
  30733. this._onResize = function (evt) {
  30734. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30735. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30736. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30737. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30738. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30739. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30740. };
  30741. // injecting a canvas element on top of the canvas 3D game
  30742. if (!VirtualJoystick.vjCanvas) {
  30743. window.addEventListener("resize", this._onResize, false);
  30744. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30745. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30746. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30747. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30748. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30749. VirtualJoystick.vjCanvas.style.width = "100%";
  30750. VirtualJoystick.vjCanvas.style.height = "100%";
  30751. VirtualJoystick.vjCanvas.style.position = "absolute";
  30752. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30753. VirtualJoystick.vjCanvas.style.top = "0px";
  30754. VirtualJoystick.vjCanvas.style.left = "0px";
  30755. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30756. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30757. // Support for jQuery PEP polyfill
  30758. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30759. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30760. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30761. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30762. document.body.appendChild(VirtualJoystick.vjCanvas);
  30763. }
  30764. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30765. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30766. this.pressed = false;
  30767. // default joystick color
  30768. this._joystickColor = "cyan";
  30769. this._joystickPointerID = -1;
  30770. // current joystick position
  30771. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30772. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30773. // origin joystick position
  30774. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30775. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30776. this._onPointerDownHandlerRef = function (evt) {
  30777. _this._onPointerDown(evt);
  30778. };
  30779. this._onPointerMoveHandlerRef = function (evt) {
  30780. _this._onPointerMove(evt);
  30781. };
  30782. this._onPointerOutHandlerRef = function (evt) {
  30783. _this._onPointerUp(evt);
  30784. };
  30785. this._onPointerUpHandlerRef = function (evt) {
  30786. _this._onPointerUp(evt);
  30787. };
  30788. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30789. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30790. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30791. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30792. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30793. evt.preventDefault(); // Disables system menu
  30794. }, false);
  30795. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30796. }
  30797. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30798. this._joystickSensibility = newJoystickSensibility;
  30799. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30800. };
  30801. VirtualJoystick.prototype._onPointerDown = function (e) {
  30802. var positionOnScreenCondition;
  30803. e.preventDefault();
  30804. if (this._leftJoystick === true) {
  30805. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30806. }
  30807. else {
  30808. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30809. }
  30810. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30811. // First contact will be dedicated to the virtual joystick
  30812. this._joystickPointerID = e.pointerId;
  30813. this._joystickPointerStartPos.x = e.clientX;
  30814. this._joystickPointerStartPos.y = e.clientY;
  30815. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30816. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30817. this._deltaJoystickVector.x = 0;
  30818. this._deltaJoystickVector.y = 0;
  30819. this.pressed = true;
  30820. this._touches.add(e.pointerId.toString(), e);
  30821. }
  30822. else {
  30823. // You can only trigger the action buttons with a joystick declared
  30824. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30825. this._action();
  30826. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30827. }
  30828. }
  30829. };
  30830. VirtualJoystick.prototype._onPointerMove = function (e) {
  30831. // If the current pointer is the one associated to the joystick (first touch contact)
  30832. if (this._joystickPointerID == e.pointerId) {
  30833. this._joystickPointerPos.x = e.clientX;
  30834. this._joystickPointerPos.y = e.clientY;
  30835. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30836. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30837. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30838. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30839. switch (this._axisTargetedByLeftAndRight) {
  30840. case JoystickAxis.X:
  30841. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30842. break;
  30843. case JoystickAxis.Y:
  30844. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30845. break;
  30846. case JoystickAxis.Z:
  30847. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30848. break;
  30849. }
  30850. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30851. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30852. switch (this._axisTargetedByUpAndDown) {
  30853. case JoystickAxis.X:
  30854. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30855. break;
  30856. case JoystickAxis.Y:
  30857. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30858. break;
  30859. case JoystickAxis.Z:
  30860. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30861. break;
  30862. }
  30863. }
  30864. else {
  30865. if (this._touches.item(e.pointerId.toString())) {
  30866. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30867. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30868. }
  30869. }
  30870. };
  30871. VirtualJoystick.prototype._onPointerUp = function (e) {
  30872. if (this._joystickPointerID == e.pointerId) {
  30873. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30874. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30875. this._joystickPointerID = -1;
  30876. this.pressed = false;
  30877. }
  30878. else {
  30879. var touch = this._touches.item(e.pointerId.toString());
  30880. if (touch) {
  30881. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30882. }
  30883. }
  30884. this._deltaJoystickVector.x = 0;
  30885. this._deltaJoystickVector.y = 0;
  30886. this._touches.remove(e.pointerId.toString());
  30887. };
  30888. /**
  30889. * Change the color of the virtual joystick
  30890. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30891. */
  30892. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30893. this._joystickColor = newColor;
  30894. };
  30895. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30896. this._action = action;
  30897. };
  30898. // Define which axis you'd like to control for left & right
  30899. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30900. switch (axis) {
  30901. case JoystickAxis.X:
  30902. case JoystickAxis.Y:
  30903. case JoystickAxis.Z:
  30904. this._axisTargetedByLeftAndRight = axis;
  30905. break;
  30906. default:
  30907. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30908. break;
  30909. }
  30910. };
  30911. // Define which axis you'd like to control for up & down
  30912. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30913. switch (axis) {
  30914. case JoystickAxis.X:
  30915. case JoystickAxis.Y:
  30916. case JoystickAxis.Z:
  30917. this._axisTargetedByUpAndDown = axis;
  30918. break;
  30919. default:
  30920. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30921. break;
  30922. }
  30923. };
  30924. VirtualJoystick.prototype._clearCanvas = function () {
  30925. if (this._leftJoystick) {
  30926. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30927. }
  30928. else {
  30929. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30930. }
  30931. };
  30932. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30933. var _this = this;
  30934. if (this.pressed) {
  30935. this._touches.forEach(function (touch) {
  30936. if (touch.pointerId === _this._joystickPointerID) {
  30937. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30938. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30939. VirtualJoystick.vjCanvasContext.beginPath();
  30940. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30941. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30942. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30943. VirtualJoystick.vjCanvasContext.stroke();
  30944. VirtualJoystick.vjCanvasContext.closePath();
  30945. VirtualJoystick.vjCanvasContext.beginPath();
  30946. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30947. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30948. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30949. VirtualJoystick.vjCanvasContext.stroke();
  30950. VirtualJoystick.vjCanvasContext.closePath();
  30951. VirtualJoystick.vjCanvasContext.beginPath();
  30952. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30953. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30954. VirtualJoystick.vjCanvasContext.stroke();
  30955. VirtualJoystick.vjCanvasContext.closePath();
  30956. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30957. }
  30958. else {
  30959. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30960. VirtualJoystick.vjCanvasContext.beginPath();
  30961. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30962. VirtualJoystick.vjCanvasContext.beginPath();
  30963. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30964. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30965. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30966. VirtualJoystick.vjCanvasContext.stroke();
  30967. VirtualJoystick.vjCanvasContext.closePath();
  30968. touch.prevX = touch.x;
  30969. touch.prevY = touch.y;
  30970. }
  30971. ;
  30972. });
  30973. }
  30974. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30975. };
  30976. VirtualJoystick.prototype.releaseCanvas = function () {
  30977. if (VirtualJoystick.vjCanvas) {
  30978. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30979. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30980. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30981. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30982. window.removeEventListener("resize", this._onResize);
  30983. document.body.removeChild(VirtualJoystick.vjCanvas);
  30984. VirtualJoystick.vjCanvas = null;
  30985. }
  30986. };
  30987. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30988. VirtualJoystick._globalJoystickIndex = 0;
  30989. return VirtualJoystick;
  30990. })();
  30991. BABYLON.VirtualJoystick = VirtualJoystick;
  30992. })(BABYLON || (BABYLON = {}));
  30993. var BABYLON;
  30994. (function (BABYLON) {
  30995. // We're mainly based on the logic defined into the FreeCamera code
  30996. var VirtualJoysticksCamera = (function (_super) {
  30997. __extends(VirtualJoysticksCamera, _super);
  30998. function VirtualJoysticksCamera(name, position, scene) {
  30999. _super.call(this, name, position, scene);
  31000. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31001. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31002. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31003. this._leftjoystick.setJoystickSensibility(0.15);
  31004. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31005. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31006. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31007. this._rightjoystick.reverseUpDown = true;
  31008. this._rightjoystick.setJoystickSensibility(0.05);
  31009. this._rightjoystick.setJoystickColor("yellow");
  31010. }
  31011. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31012. return this._leftjoystick;
  31013. };
  31014. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31015. return this._rightjoystick;
  31016. };
  31017. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31018. var speed = this._computeLocalCameraSpeed() * 50;
  31019. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31020. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31021. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31022. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31023. if (!this._leftjoystick.pressed) {
  31024. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31025. }
  31026. if (!this._rightjoystick.pressed) {
  31027. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31028. }
  31029. _super.prototype._checkInputs.call(this);
  31030. };
  31031. VirtualJoysticksCamera.prototype.dispose = function () {
  31032. this._leftjoystick.releaseCanvas();
  31033. _super.prototype.dispose.call(this);
  31034. };
  31035. return VirtualJoysticksCamera;
  31036. })(BABYLON.FreeCamera);
  31037. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31038. })(BABYLON || (BABYLON = {}));
  31039. var BABYLON;
  31040. (function (BABYLON) {
  31041. var AnaglyphPostProcess = (function (_super) {
  31042. __extends(AnaglyphPostProcess, _super);
  31043. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31044. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31045. }
  31046. return AnaglyphPostProcess;
  31047. })(BABYLON.PostProcess);
  31048. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31049. })(BABYLON || (BABYLON = {}));
  31050. var BABYLON;
  31051. (function (BABYLON) {
  31052. var OutlineRenderer = (function () {
  31053. function OutlineRenderer(scene) {
  31054. this._scene = scene;
  31055. }
  31056. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31057. var _this = this;
  31058. if (useOverlay === void 0) { useOverlay = false; }
  31059. var scene = this._scene;
  31060. var engine = this._scene.getEngine();
  31061. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31062. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31063. return;
  31064. }
  31065. var mesh = subMesh.getRenderingMesh();
  31066. var material = subMesh.getMaterial();
  31067. engine.enableEffect(this._effect);
  31068. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31069. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31070. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31071. // Bones
  31072. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31073. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31074. }
  31075. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31076. // Alpha test
  31077. if (material && material.needAlphaTesting()) {
  31078. var alphaTexture = material.getAlphaTestTexture();
  31079. this._effect.setTexture("diffuseSampler", alphaTexture);
  31080. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31081. }
  31082. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31083. };
  31084. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31085. var defines = [];
  31086. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31087. var mesh = subMesh.getMesh();
  31088. var material = subMesh.getMaterial();
  31089. // Alpha test
  31090. if (material && material.needAlphaTesting()) {
  31091. defines.push("#define ALPHATEST");
  31092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31093. attribs.push(BABYLON.VertexBuffer.UVKind);
  31094. defines.push("#define UV1");
  31095. }
  31096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31098. defines.push("#define UV2");
  31099. }
  31100. }
  31101. // Bones
  31102. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31103. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31104. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31105. if (mesh.numBoneInfluencers > 4) {
  31106. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31107. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31108. }
  31109. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31110. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31111. }
  31112. else {
  31113. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31114. }
  31115. // Instances
  31116. if (useInstances) {
  31117. defines.push("#define INSTANCES");
  31118. attribs.push("world0");
  31119. attribs.push("world1");
  31120. attribs.push("world2");
  31121. attribs.push("world3");
  31122. }
  31123. // Get correct effect
  31124. var join = defines.join("\n");
  31125. if (this._cachedDefines !== join) {
  31126. this._cachedDefines = join;
  31127. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31128. }
  31129. return this._effect.isReady();
  31130. };
  31131. return OutlineRenderer;
  31132. })();
  31133. BABYLON.OutlineRenderer = OutlineRenderer;
  31134. })(BABYLON || (BABYLON = {}));
  31135. var BABYLON;
  31136. (function (BABYLON) {
  31137. var MeshAssetTask = (function () {
  31138. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31139. this.name = name;
  31140. this.meshesNames = meshesNames;
  31141. this.rootUrl = rootUrl;
  31142. this.sceneFilename = sceneFilename;
  31143. this.isCompleted = false;
  31144. }
  31145. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31146. var _this = this;
  31147. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31148. _this.loadedMeshes = meshes;
  31149. _this.loadedParticleSystems = particleSystems;
  31150. _this.loadedSkeletons = skeletons;
  31151. _this.isCompleted = true;
  31152. if (_this.onSuccess) {
  31153. _this.onSuccess(_this);
  31154. }
  31155. onSuccess();
  31156. }, null, function () {
  31157. if (_this.onError) {
  31158. _this.onError(_this);
  31159. }
  31160. onError();
  31161. });
  31162. };
  31163. return MeshAssetTask;
  31164. })();
  31165. BABYLON.MeshAssetTask = MeshAssetTask;
  31166. var TextFileAssetTask = (function () {
  31167. function TextFileAssetTask(name, url) {
  31168. this.name = name;
  31169. this.url = url;
  31170. this.isCompleted = false;
  31171. }
  31172. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31173. var _this = this;
  31174. BABYLON.Tools.LoadFile(this.url, function (data) {
  31175. _this.text = data;
  31176. _this.isCompleted = true;
  31177. if (_this.onSuccess) {
  31178. _this.onSuccess(_this);
  31179. }
  31180. onSuccess();
  31181. }, null, scene.database, false, function () {
  31182. if (_this.onError) {
  31183. _this.onError(_this);
  31184. }
  31185. onError();
  31186. });
  31187. };
  31188. return TextFileAssetTask;
  31189. })();
  31190. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31191. var BinaryFileAssetTask = (function () {
  31192. function BinaryFileAssetTask(name, url) {
  31193. this.name = name;
  31194. this.url = url;
  31195. this.isCompleted = false;
  31196. }
  31197. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31198. var _this = this;
  31199. BABYLON.Tools.LoadFile(this.url, function (data) {
  31200. _this.data = data;
  31201. _this.isCompleted = true;
  31202. if (_this.onSuccess) {
  31203. _this.onSuccess(_this);
  31204. }
  31205. onSuccess();
  31206. }, null, scene.database, true, function () {
  31207. if (_this.onError) {
  31208. _this.onError(_this);
  31209. }
  31210. onError();
  31211. });
  31212. };
  31213. return BinaryFileAssetTask;
  31214. })();
  31215. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31216. var ImageAssetTask = (function () {
  31217. function ImageAssetTask(name, url) {
  31218. this.name = name;
  31219. this.url = url;
  31220. this.isCompleted = false;
  31221. }
  31222. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31223. var _this = this;
  31224. var img = new Image();
  31225. img.onload = function () {
  31226. _this.image = img;
  31227. _this.isCompleted = true;
  31228. if (_this.onSuccess) {
  31229. _this.onSuccess(_this);
  31230. }
  31231. onSuccess();
  31232. };
  31233. img.onerror = function () {
  31234. if (_this.onError) {
  31235. _this.onError(_this);
  31236. }
  31237. onError();
  31238. };
  31239. img.src = this.url;
  31240. };
  31241. return ImageAssetTask;
  31242. })();
  31243. BABYLON.ImageAssetTask = ImageAssetTask;
  31244. var TextureAssetTask = (function () {
  31245. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31247. this.name = name;
  31248. this.url = url;
  31249. this.noMipmap = noMipmap;
  31250. this.invertY = invertY;
  31251. this.samplingMode = samplingMode;
  31252. this.isCompleted = false;
  31253. }
  31254. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31255. var _this = this;
  31256. var onload = function () {
  31257. _this.isCompleted = true;
  31258. if (_this.onSuccess) {
  31259. _this.onSuccess(_this);
  31260. }
  31261. onSuccess();
  31262. };
  31263. var onerror = function () {
  31264. if (_this.onError) {
  31265. _this.onError(_this);
  31266. }
  31267. onError();
  31268. };
  31269. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31270. };
  31271. return TextureAssetTask;
  31272. })();
  31273. BABYLON.TextureAssetTask = TextureAssetTask;
  31274. var AssetsManager = (function () {
  31275. function AssetsManager(scene) {
  31276. this._tasks = new Array();
  31277. this._waitingTasksCount = 0;
  31278. this.useDefaultLoadingScreen = true;
  31279. this._scene = scene;
  31280. }
  31281. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31282. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31283. this._tasks.push(task);
  31284. return task;
  31285. };
  31286. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31287. var task = new TextFileAssetTask(taskName, url);
  31288. this._tasks.push(task);
  31289. return task;
  31290. };
  31291. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31292. var task = new BinaryFileAssetTask(taskName, url);
  31293. this._tasks.push(task);
  31294. return task;
  31295. };
  31296. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31297. var task = new ImageAssetTask(taskName, url);
  31298. this._tasks.push(task);
  31299. return task;
  31300. };
  31301. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31303. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31304. this._tasks.push(task);
  31305. return task;
  31306. };
  31307. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31308. this._waitingTasksCount--;
  31309. if (this._waitingTasksCount === 0) {
  31310. if (this.onFinish) {
  31311. this.onFinish(this._tasks);
  31312. }
  31313. this._scene.getEngine().hideLoadingUI();
  31314. }
  31315. };
  31316. AssetsManager.prototype._runTask = function (task) {
  31317. var _this = this;
  31318. task.run(this._scene, function () {
  31319. if (_this.onTaskSuccess) {
  31320. _this.onTaskSuccess(task);
  31321. }
  31322. _this._decreaseWaitingTasksCount();
  31323. }, function () {
  31324. if (_this.onTaskError) {
  31325. _this.onTaskError(task);
  31326. }
  31327. _this._decreaseWaitingTasksCount();
  31328. });
  31329. };
  31330. AssetsManager.prototype.reset = function () {
  31331. this._tasks = new Array();
  31332. return this;
  31333. };
  31334. AssetsManager.prototype.load = function () {
  31335. this._waitingTasksCount = this._tasks.length;
  31336. if (this._waitingTasksCount === 0) {
  31337. if (this.onFinish) {
  31338. this.onFinish(this._tasks);
  31339. }
  31340. return this;
  31341. }
  31342. if (this.useDefaultLoadingScreen) {
  31343. this._scene.getEngine().displayLoadingUI();
  31344. }
  31345. for (var index = 0; index < this._tasks.length; index++) {
  31346. var task = this._tasks[index];
  31347. this._runTask(task);
  31348. }
  31349. return this;
  31350. };
  31351. return AssetsManager;
  31352. })();
  31353. BABYLON.AssetsManager = AssetsManager;
  31354. })(BABYLON || (BABYLON = {}));
  31355. var BABYLON;
  31356. (function (BABYLON) {
  31357. var VRDeviceOrientationFreeCamera = (function (_super) {
  31358. __extends(VRDeviceOrientationFreeCamera, _super);
  31359. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31360. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31361. _super.call(this, name, position, scene);
  31362. this._alpha = 0;
  31363. this._beta = 0;
  31364. this._gamma = 0;
  31365. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31366. metrics.compensateDistortion = compensateDistortion;
  31367. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31368. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31369. }
  31370. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31371. this._alpha = +evt.alpha | 0;
  31372. this._beta = +evt.beta | 0;
  31373. this._gamma = +evt.gamma | 0;
  31374. if (this._gamma < 0) {
  31375. this._gamma = 90 + this._gamma;
  31376. }
  31377. else {
  31378. // Incline it in the correct angle.
  31379. this._gamma = 270 - this._gamma;
  31380. }
  31381. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31382. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31383. this.rotation.z = this._beta / 180.0 * Math.PI;
  31384. };
  31385. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31386. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31387. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31388. };
  31389. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31390. _super.prototype.detachControl.call(this, element);
  31391. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31392. };
  31393. return VRDeviceOrientationFreeCamera;
  31394. })(BABYLON.FreeCamera);
  31395. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31396. })(BABYLON || (BABYLON = {}));
  31397. var BABYLON;
  31398. (function (BABYLON) {
  31399. var WebVRFreeCamera = (function (_super) {
  31400. __extends(WebVRFreeCamera, _super);
  31401. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31402. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31403. _super.call(this, name, position, scene);
  31404. this._hmdDevice = null;
  31405. this._sensorDevice = null;
  31406. this._cacheState = null;
  31407. this._cacheQuaternion = new BABYLON.Quaternion();
  31408. this._cacheRotation = BABYLON.Vector3.Zero();
  31409. this._vrEnabled = false;
  31410. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31411. metrics.compensateDistortion = compensateDistortion;
  31412. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31413. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31414. }
  31415. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31416. var size = devices.length;
  31417. var i = 0;
  31418. // Reset devices.
  31419. this._sensorDevice = null;
  31420. this._hmdDevice = null;
  31421. // Search for a HmdDevice.
  31422. while (i < size && this._hmdDevice === null) {
  31423. if (devices[i] instanceof HMDVRDevice) {
  31424. this._hmdDevice = devices[i];
  31425. }
  31426. i++;
  31427. }
  31428. i = 0;
  31429. while (i < size && this._sensorDevice === null) {
  31430. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31431. this._sensorDevice = devices[i];
  31432. }
  31433. i++;
  31434. }
  31435. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31436. };
  31437. WebVRFreeCamera.prototype._checkInputs = function () {
  31438. if (this._vrEnabled) {
  31439. this._cacheState = this._sensorDevice.getState();
  31440. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31441. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31442. this.rotation.x = -this._cacheRotation.z;
  31443. this.rotation.y = -this._cacheRotation.y;
  31444. this.rotation.z = this._cacheRotation.x;
  31445. }
  31446. _super.prototype._checkInputs.call(this);
  31447. };
  31448. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31449. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31450. if (navigator.getVRDevices) {
  31451. navigator.getVRDevices().then(this._getWebVRDevices);
  31452. }
  31453. else if (navigator.mozGetVRDevices) {
  31454. navigator.mozGetVRDevices(this._getWebVRDevices);
  31455. }
  31456. };
  31457. WebVRFreeCamera.prototype.detachControl = function (element) {
  31458. _super.prototype.detachControl.call(this, element);
  31459. this._vrEnabled = false;
  31460. };
  31461. return WebVRFreeCamera;
  31462. })(BABYLON.FreeCamera);
  31463. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31464. })(BABYLON || (BABYLON = {}));
  31465. var BABYLON;
  31466. (function (BABYLON) {
  31467. // Standard optimizations
  31468. var SceneOptimization = (function () {
  31469. function SceneOptimization(priority) {
  31470. if (priority === void 0) { priority = 0; }
  31471. this.priority = priority;
  31472. this.apply = function (scene) {
  31473. return true; // Return true if everything that can be done was applied
  31474. };
  31475. }
  31476. return SceneOptimization;
  31477. })();
  31478. BABYLON.SceneOptimization = SceneOptimization;
  31479. var TextureOptimization = (function (_super) {
  31480. __extends(TextureOptimization, _super);
  31481. function TextureOptimization(priority, maximumSize) {
  31482. var _this = this;
  31483. if (priority === void 0) { priority = 0; }
  31484. if (maximumSize === void 0) { maximumSize = 1024; }
  31485. _super.call(this, priority);
  31486. this.priority = priority;
  31487. this.maximumSize = maximumSize;
  31488. this.apply = function (scene) {
  31489. var allDone = true;
  31490. for (var index = 0; index < scene.textures.length; index++) {
  31491. var texture = scene.textures[index];
  31492. if (!texture.canRescale) {
  31493. continue;
  31494. }
  31495. var currentSize = texture.getSize();
  31496. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31497. if (maxDimension > _this.maximumSize) {
  31498. texture.scale(0.5);
  31499. allDone = false;
  31500. }
  31501. }
  31502. return allDone;
  31503. };
  31504. }
  31505. return TextureOptimization;
  31506. })(SceneOptimization);
  31507. BABYLON.TextureOptimization = TextureOptimization;
  31508. var HardwareScalingOptimization = (function (_super) {
  31509. __extends(HardwareScalingOptimization, _super);
  31510. function HardwareScalingOptimization(priority, maximumScale) {
  31511. var _this = this;
  31512. if (priority === void 0) { priority = 0; }
  31513. if (maximumScale === void 0) { maximumScale = 2; }
  31514. _super.call(this, priority);
  31515. this.priority = priority;
  31516. this.maximumScale = maximumScale;
  31517. this._currentScale = 1;
  31518. this.apply = function (scene) {
  31519. _this._currentScale++;
  31520. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31521. return _this._currentScale >= _this.maximumScale;
  31522. };
  31523. }
  31524. return HardwareScalingOptimization;
  31525. })(SceneOptimization);
  31526. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31527. var ShadowsOptimization = (function (_super) {
  31528. __extends(ShadowsOptimization, _super);
  31529. function ShadowsOptimization() {
  31530. _super.apply(this, arguments);
  31531. this.apply = function (scene) {
  31532. scene.shadowsEnabled = false;
  31533. return true;
  31534. };
  31535. }
  31536. return ShadowsOptimization;
  31537. })(SceneOptimization);
  31538. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31539. var PostProcessesOptimization = (function (_super) {
  31540. __extends(PostProcessesOptimization, _super);
  31541. function PostProcessesOptimization() {
  31542. _super.apply(this, arguments);
  31543. this.apply = function (scene) {
  31544. scene.postProcessesEnabled = false;
  31545. return true;
  31546. };
  31547. }
  31548. return PostProcessesOptimization;
  31549. })(SceneOptimization);
  31550. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31551. var LensFlaresOptimization = (function (_super) {
  31552. __extends(LensFlaresOptimization, _super);
  31553. function LensFlaresOptimization() {
  31554. _super.apply(this, arguments);
  31555. this.apply = function (scene) {
  31556. scene.lensFlaresEnabled = false;
  31557. return true;
  31558. };
  31559. }
  31560. return LensFlaresOptimization;
  31561. })(SceneOptimization);
  31562. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31563. var ParticlesOptimization = (function (_super) {
  31564. __extends(ParticlesOptimization, _super);
  31565. function ParticlesOptimization() {
  31566. _super.apply(this, arguments);
  31567. this.apply = function (scene) {
  31568. scene.particlesEnabled = false;
  31569. return true;
  31570. };
  31571. }
  31572. return ParticlesOptimization;
  31573. })(SceneOptimization);
  31574. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31575. var RenderTargetsOptimization = (function (_super) {
  31576. __extends(RenderTargetsOptimization, _super);
  31577. function RenderTargetsOptimization() {
  31578. _super.apply(this, arguments);
  31579. this.apply = function (scene) {
  31580. scene.renderTargetsEnabled = false;
  31581. return true;
  31582. };
  31583. }
  31584. return RenderTargetsOptimization;
  31585. })(SceneOptimization);
  31586. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31587. var MergeMeshesOptimization = (function (_super) {
  31588. __extends(MergeMeshesOptimization, _super);
  31589. function MergeMeshesOptimization() {
  31590. var _this = this;
  31591. _super.apply(this, arguments);
  31592. this._canBeMerged = function (abstractMesh) {
  31593. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31594. return false;
  31595. }
  31596. var mesh = abstractMesh;
  31597. if (!mesh.isVisible || !mesh.isEnabled()) {
  31598. return false;
  31599. }
  31600. if (mesh.instances.length > 0) {
  31601. return false;
  31602. }
  31603. if (mesh.skeleton || mesh.hasLODLevels) {
  31604. return false;
  31605. }
  31606. if (mesh.parent) {
  31607. return false;
  31608. }
  31609. return true;
  31610. };
  31611. this.apply = function (scene, updateSelectionTree) {
  31612. var globalPool = scene.meshes.slice(0);
  31613. var globalLength = globalPool.length;
  31614. for (var index = 0; index < globalLength; index++) {
  31615. var currentPool = new Array();
  31616. var current = globalPool[index];
  31617. // Checks
  31618. if (!_this._canBeMerged(current)) {
  31619. continue;
  31620. }
  31621. currentPool.push(current);
  31622. // Find compatible meshes
  31623. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31624. var otherMesh = globalPool[subIndex];
  31625. if (!_this._canBeMerged(otherMesh)) {
  31626. continue;
  31627. }
  31628. if (otherMesh.material !== current.material) {
  31629. continue;
  31630. }
  31631. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31632. continue;
  31633. }
  31634. currentPool.push(otherMesh);
  31635. globalLength--;
  31636. globalPool.splice(subIndex, 1);
  31637. subIndex--;
  31638. }
  31639. if (currentPool.length < 2) {
  31640. continue;
  31641. }
  31642. // Merge meshes
  31643. BABYLON.Mesh.MergeMeshes(currentPool);
  31644. }
  31645. if (updateSelectionTree != undefined) {
  31646. if (updateSelectionTree) {
  31647. scene.createOrUpdateSelectionOctree();
  31648. }
  31649. }
  31650. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31651. scene.createOrUpdateSelectionOctree();
  31652. }
  31653. return true;
  31654. };
  31655. }
  31656. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31657. get: function () {
  31658. return MergeMeshesOptimization._UpdateSelectionTree;
  31659. },
  31660. set: function (value) {
  31661. MergeMeshesOptimization._UpdateSelectionTree = value;
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. MergeMeshesOptimization._UpdateSelectionTree = false;
  31667. return MergeMeshesOptimization;
  31668. })(SceneOptimization);
  31669. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31670. // Options
  31671. var SceneOptimizerOptions = (function () {
  31672. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31673. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31674. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31675. this.targetFrameRate = targetFrameRate;
  31676. this.trackerDuration = trackerDuration;
  31677. this.optimizations = new Array();
  31678. }
  31679. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31680. var result = new SceneOptimizerOptions(targetFrameRate);
  31681. var priority = 0;
  31682. result.optimizations.push(new MergeMeshesOptimization(priority));
  31683. result.optimizations.push(new ShadowsOptimization(priority));
  31684. result.optimizations.push(new LensFlaresOptimization(priority));
  31685. // Next priority
  31686. priority++;
  31687. result.optimizations.push(new PostProcessesOptimization(priority));
  31688. result.optimizations.push(new ParticlesOptimization(priority));
  31689. // Next priority
  31690. priority++;
  31691. result.optimizations.push(new TextureOptimization(priority, 1024));
  31692. return result;
  31693. };
  31694. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31695. var result = new SceneOptimizerOptions(targetFrameRate);
  31696. var priority = 0;
  31697. result.optimizations.push(new MergeMeshesOptimization(priority));
  31698. result.optimizations.push(new ShadowsOptimization(priority));
  31699. result.optimizations.push(new LensFlaresOptimization(priority));
  31700. // Next priority
  31701. priority++;
  31702. result.optimizations.push(new PostProcessesOptimization(priority));
  31703. result.optimizations.push(new ParticlesOptimization(priority));
  31704. // Next priority
  31705. priority++;
  31706. result.optimizations.push(new TextureOptimization(priority, 512));
  31707. // Next priority
  31708. priority++;
  31709. result.optimizations.push(new RenderTargetsOptimization(priority));
  31710. // Next priority
  31711. priority++;
  31712. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31713. return result;
  31714. };
  31715. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31716. var result = new SceneOptimizerOptions(targetFrameRate);
  31717. var priority = 0;
  31718. result.optimizations.push(new MergeMeshesOptimization(priority));
  31719. result.optimizations.push(new ShadowsOptimization(priority));
  31720. result.optimizations.push(new LensFlaresOptimization(priority));
  31721. // Next priority
  31722. priority++;
  31723. result.optimizations.push(new PostProcessesOptimization(priority));
  31724. result.optimizations.push(new ParticlesOptimization(priority));
  31725. // Next priority
  31726. priority++;
  31727. result.optimizations.push(new TextureOptimization(priority, 256));
  31728. // Next priority
  31729. priority++;
  31730. result.optimizations.push(new RenderTargetsOptimization(priority));
  31731. // Next priority
  31732. priority++;
  31733. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31734. return result;
  31735. };
  31736. return SceneOptimizerOptions;
  31737. })();
  31738. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31739. // Scene optimizer tool
  31740. var SceneOptimizer = (function () {
  31741. function SceneOptimizer() {
  31742. }
  31743. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31744. // TODO: add an epsilon
  31745. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31746. if (onSuccess) {
  31747. onSuccess();
  31748. }
  31749. return;
  31750. }
  31751. // Apply current level of optimizations
  31752. var allDone = true;
  31753. var noOptimizationApplied = true;
  31754. for (var index = 0; index < options.optimizations.length; index++) {
  31755. var optimization = options.optimizations[index];
  31756. if (optimization.priority === currentPriorityLevel) {
  31757. noOptimizationApplied = false;
  31758. allDone = allDone && optimization.apply(scene);
  31759. }
  31760. }
  31761. // If no optimization was applied, this is a failure :(
  31762. if (noOptimizationApplied) {
  31763. if (onFailure) {
  31764. onFailure();
  31765. }
  31766. return;
  31767. }
  31768. // If all optimizations were done, move to next level
  31769. if (allDone) {
  31770. currentPriorityLevel++;
  31771. }
  31772. // Let's the system running for a specific amount of time before checking FPS
  31773. scene.executeWhenReady(function () {
  31774. setTimeout(function () {
  31775. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31776. }, options.trackerDuration);
  31777. });
  31778. };
  31779. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31780. if (!options) {
  31781. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31782. }
  31783. // Let's the system running for a specific amount of time before checking FPS
  31784. scene.executeWhenReady(function () {
  31785. setTimeout(function () {
  31786. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31787. }, options.trackerDuration);
  31788. });
  31789. };
  31790. return SceneOptimizer;
  31791. })();
  31792. BABYLON.SceneOptimizer = SceneOptimizer;
  31793. })(BABYLON || (BABYLON = {}));
  31794. var BABYLON;
  31795. (function (BABYLON) {
  31796. var Internals;
  31797. (function (Internals) {
  31798. var MeshLODLevel = (function () {
  31799. function MeshLODLevel(distance, mesh) {
  31800. this.distance = distance;
  31801. this.mesh = mesh;
  31802. }
  31803. return MeshLODLevel;
  31804. })();
  31805. Internals.MeshLODLevel = MeshLODLevel;
  31806. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31807. })(BABYLON || (BABYLON = {}));
  31808. var BABYLON;
  31809. (function (BABYLON) {
  31810. var RawTexture = (function (_super) {
  31811. __extends(RawTexture, _super);
  31812. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31813. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31814. if (invertY === void 0) { invertY = false; }
  31815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31816. _super.call(this, null, scene, !generateMipMaps, invertY);
  31817. this.format = format;
  31818. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31819. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31820. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31821. }
  31822. RawTexture.prototype.update = function (data) {
  31823. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31824. };
  31825. // Statics
  31826. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31827. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31828. if (invertY === void 0) { invertY = false; }
  31829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31830. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31831. };
  31832. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31833. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31834. if (invertY === void 0) { invertY = false; }
  31835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31836. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31837. };
  31838. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31839. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31840. if (invertY === void 0) { invertY = false; }
  31841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31842. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31843. };
  31844. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31845. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31846. if (invertY === void 0) { invertY = false; }
  31847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31848. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31849. };
  31850. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31851. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31852. if (invertY === void 0) { invertY = false; }
  31853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31854. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31855. };
  31856. return RawTexture;
  31857. })(BABYLON.Texture);
  31858. BABYLON.RawTexture = RawTexture;
  31859. })(BABYLON || (BABYLON = {}));
  31860. var BABYLON;
  31861. (function (BABYLON) {
  31862. var IndexedVector2 = (function (_super) {
  31863. __extends(IndexedVector2, _super);
  31864. function IndexedVector2(original, index) {
  31865. _super.call(this, original.x, original.y);
  31866. this.index = index;
  31867. }
  31868. return IndexedVector2;
  31869. })(BABYLON.Vector2);
  31870. var PolygonPoints = (function () {
  31871. function PolygonPoints() {
  31872. this.elements = new Array();
  31873. }
  31874. PolygonPoints.prototype.add = function (originalPoints) {
  31875. var _this = this;
  31876. var result = new Array();
  31877. originalPoints.forEach(function (point) {
  31878. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31879. var newPoint = new IndexedVector2(point, _this.elements.length);
  31880. result.push(newPoint);
  31881. _this.elements.push(newPoint);
  31882. }
  31883. });
  31884. return result;
  31885. };
  31886. PolygonPoints.prototype.computeBounds = function () {
  31887. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31888. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31889. this.elements.forEach(function (point) {
  31890. // x
  31891. if (point.x < lmin.x) {
  31892. lmin.x = point.x;
  31893. }
  31894. else if (point.x > lmax.x) {
  31895. lmax.x = point.x;
  31896. }
  31897. // y
  31898. if (point.y < lmin.y) {
  31899. lmin.y = point.y;
  31900. }
  31901. else if (point.y > lmax.y) {
  31902. lmax.y = point.y;
  31903. }
  31904. });
  31905. return {
  31906. min: lmin,
  31907. max: lmax,
  31908. width: lmax.x - lmin.x,
  31909. height: lmax.y - lmin.y
  31910. };
  31911. };
  31912. return PolygonPoints;
  31913. })();
  31914. var Polygon = (function () {
  31915. function Polygon() {
  31916. }
  31917. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31918. return [
  31919. new BABYLON.Vector2(xmin, ymin),
  31920. new BABYLON.Vector2(xmax, ymin),
  31921. new BABYLON.Vector2(xmax, ymax),
  31922. new BABYLON.Vector2(xmin, ymax)
  31923. ];
  31924. };
  31925. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31926. if (cx === void 0) { cx = 0; }
  31927. if (cy === void 0) { cy = 0; }
  31928. if (numberOfSides === void 0) { numberOfSides = 32; }
  31929. var result = new Array();
  31930. var angle = 0;
  31931. var increment = (Math.PI * 2) / numberOfSides;
  31932. for (var i = 0; i < numberOfSides; i++) {
  31933. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31934. angle -= increment;
  31935. }
  31936. return result;
  31937. };
  31938. Polygon.Parse = function (input) {
  31939. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31940. var i, result = [];
  31941. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31942. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31943. }
  31944. return result;
  31945. };
  31946. Polygon.StartingAt = function (x, y) {
  31947. return BABYLON.Path2.StartingAt(x, y);
  31948. };
  31949. return Polygon;
  31950. })();
  31951. BABYLON.Polygon = Polygon;
  31952. var PolygonMeshBuilder = (function () {
  31953. function PolygonMeshBuilder(name, contours, scene) {
  31954. this._points = new PolygonPoints();
  31955. this._outlinepoints = new PolygonPoints();
  31956. this._holes = [];
  31957. if (!("poly2tri" in window)) {
  31958. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31959. }
  31960. this._name = name;
  31961. this._scene = scene;
  31962. var points;
  31963. if (contours instanceof BABYLON.Path2) {
  31964. points = contours.getPoints();
  31965. }
  31966. else {
  31967. points = contours;
  31968. }
  31969. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31970. this._outlinepoints.add(points);
  31971. }
  31972. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31973. this._swctx.addHole(this._points.add(hole));
  31974. var holepoints = new PolygonPoints();
  31975. holepoints.add(hole);
  31976. this._holes.push(holepoints);
  31977. return this;
  31978. };
  31979. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31980. var _this = this;
  31981. if (updatable === void 0) { updatable = false; }
  31982. var result = new BABYLON.Mesh(this._name, this._scene);
  31983. var normals = [];
  31984. var positions = [];
  31985. var uvs = [];
  31986. var bounds = this._points.computeBounds();
  31987. this._points.elements.forEach(function (p) {
  31988. normals.push(0, 1.0, 0);
  31989. positions.push(p.x, 0, p.y);
  31990. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31991. });
  31992. var indices = [];
  31993. this._swctx.triangulate();
  31994. this._swctx.getTriangles().forEach(function (triangle) {
  31995. triangle.getPoints().forEach(function (point) {
  31996. indices.push(point.index);
  31997. });
  31998. });
  31999. if (depth > 0) {
  32000. var positionscount = (positions.length / 3); //get the current pointcount
  32001. this._points.elements.forEach(function (p) {
  32002. normals.push(0, -1.0, 0);
  32003. positions.push(p.x, -depth, p.y);
  32004. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32005. });
  32006. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32007. var p2;
  32008. var poscounter = 0;
  32009. this._swctx.getTriangles().forEach(function (triangle) {
  32010. triangle.getPoints().forEach(function (point) {
  32011. switch (poscounter) {
  32012. case 0:
  32013. p1 = point;
  32014. break;
  32015. case 1:
  32016. p2 = point;
  32017. break;
  32018. case 2:
  32019. indices.push(point.index + positionscount);
  32020. indices.push(p2.index + positionscount);
  32021. indices.push(p1.index + positionscount);
  32022. poscounter = -1;
  32023. break;
  32024. }
  32025. poscounter++;
  32026. //indices.push((<IndexedVector2>point).index + positionscount);
  32027. });
  32028. });
  32029. //Add the sides
  32030. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32031. this._holes.forEach(function (hole) {
  32032. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32033. });
  32034. }
  32035. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32036. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32037. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32038. result.setIndices(indices);
  32039. return result;
  32040. };
  32041. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32042. var StartIndex = positions.length / 3;
  32043. var ulength = 0;
  32044. for (var i = 0; i < points.elements.length; i++) {
  32045. var p = points.elements[i];
  32046. var p1;
  32047. if ((i + 1) > points.elements.length - 1) {
  32048. p1 = points.elements[0];
  32049. }
  32050. else {
  32051. p1 = points.elements[i + 1];
  32052. }
  32053. positions.push(p.x, 0, p.y);
  32054. positions.push(p.x, -depth, p.y);
  32055. positions.push(p1.x, 0, p1.y);
  32056. positions.push(p1.x, -depth, p1.y);
  32057. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32058. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32059. var v3 = v2.subtract(v1);
  32060. var v4 = new BABYLON.Vector3(0, 1, 0);
  32061. var vn = BABYLON.Vector3.Cross(v3, v4);
  32062. vn = vn.normalize();
  32063. uvs.push(ulength / bounds.width, 0);
  32064. uvs.push(ulength / bounds.width, 1);
  32065. ulength += v3.length();
  32066. uvs.push((ulength / bounds.width), 0);
  32067. uvs.push((ulength / bounds.width), 1);
  32068. if (!flip) {
  32069. normals.push(-vn.x, -vn.y, -vn.z);
  32070. normals.push(-vn.x, -vn.y, -vn.z);
  32071. normals.push(-vn.x, -vn.y, -vn.z);
  32072. normals.push(-vn.x, -vn.y, -vn.z);
  32073. indices.push(StartIndex);
  32074. indices.push(StartIndex + 1);
  32075. indices.push(StartIndex + 2);
  32076. indices.push(StartIndex + 1);
  32077. indices.push(StartIndex + 3);
  32078. indices.push(StartIndex + 2);
  32079. }
  32080. else {
  32081. normals.push(vn.x, vn.y, vn.z);
  32082. normals.push(vn.x, vn.y, vn.z);
  32083. normals.push(vn.x, vn.y, vn.z);
  32084. normals.push(vn.x, vn.y, vn.z);
  32085. indices.push(StartIndex);
  32086. indices.push(StartIndex + 2);
  32087. indices.push(StartIndex + 1);
  32088. indices.push(StartIndex + 1);
  32089. indices.push(StartIndex + 2);
  32090. indices.push(StartIndex + 3);
  32091. }
  32092. StartIndex += 4;
  32093. }
  32094. ;
  32095. };
  32096. return PolygonMeshBuilder;
  32097. })();
  32098. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32099. })(BABYLON || (BABYLON = {}));
  32100. var BABYLON;
  32101. (function (BABYLON) {
  32102. var Octree = (function () {
  32103. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32104. if (maxDepth === void 0) { maxDepth = 2; }
  32105. this.maxDepth = maxDepth;
  32106. this.dynamicContent = new Array();
  32107. this._maxBlockCapacity = maxBlockCapacity || 64;
  32108. this._selectionContent = new BABYLON.SmartArray(1024);
  32109. this._creationFunc = creationFunc;
  32110. }
  32111. // Methods
  32112. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32113. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32114. };
  32115. Octree.prototype.addMesh = function (entry) {
  32116. for (var index = 0; index < this.blocks.length; index++) {
  32117. var block = this.blocks[index];
  32118. block.addEntry(entry);
  32119. }
  32120. };
  32121. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32122. this._selectionContent.reset();
  32123. for (var index = 0; index < this.blocks.length; index++) {
  32124. var block = this.blocks[index];
  32125. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32126. }
  32127. if (allowDuplicate) {
  32128. this._selectionContent.concat(this.dynamicContent);
  32129. }
  32130. else {
  32131. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32132. }
  32133. return this._selectionContent;
  32134. };
  32135. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32136. this._selectionContent.reset();
  32137. for (var index = 0; index < this.blocks.length; index++) {
  32138. var block = this.blocks[index];
  32139. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32140. }
  32141. if (allowDuplicate) {
  32142. this._selectionContent.concat(this.dynamicContent);
  32143. }
  32144. else {
  32145. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32146. }
  32147. return this._selectionContent;
  32148. };
  32149. Octree.prototype.intersectsRay = function (ray) {
  32150. this._selectionContent.reset();
  32151. for (var index = 0; index < this.blocks.length; index++) {
  32152. var block = this.blocks[index];
  32153. block.intersectsRay(ray, this._selectionContent);
  32154. }
  32155. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32156. return this._selectionContent;
  32157. };
  32158. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32159. target.blocks = new Array();
  32160. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32161. // Segmenting space
  32162. for (var x = 0; x < 2; x++) {
  32163. for (var y = 0; y < 2; y++) {
  32164. for (var z = 0; z < 2; z++) {
  32165. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32166. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32167. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32168. block.addEntries(entries);
  32169. target.blocks.push(block);
  32170. }
  32171. }
  32172. }
  32173. };
  32174. Octree.CreationFuncForMeshes = function (entry, block) {
  32175. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32176. block.entries.push(entry);
  32177. }
  32178. };
  32179. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32180. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32181. block.entries.push(entry);
  32182. }
  32183. };
  32184. return Octree;
  32185. })();
  32186. BABYLON.Octree = Octree;
  32187. })(BABYLON || (BABYLON = {}));
  32188. var BABYLON;
  32189. (function (BABYLON) {
  32190. var OctreeBlock = (function () {
  32191. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32192. this.entries = new Array();
  32193. this._boundingVectors = new Array();
  32194. this._capacity = capacity;
  32195. this._depth = depth;
  32196. this._maxDepth = maxDepth;
  32197. this._creationFunc = creationFunc;
  32198. this._minPoint = minPoint;
  32199. this._maxPoint = maxPoint;
  32200. this._boundingVectors.push(minPoint.clone());
  32201. this._boundingVectors.push(maxPoint.clone());
  32202. this._boundingVectors.push(minPoint.clone());
  32203. this._boundingVectors[2].x = maxPoint.x;
  32204. this._boundingVectors.push(minPoint.clone());
  32205. this._boundingVectors[3].y = maxPoint.y;
  32206. this._boundingVectors.push(minPoint.clone());
  32207. this._boundingVectors[4].z = maxPoint.z;
  32208. this._boundingVectors.push(maxPoint.clone());
  32209. this._boundingVectors[5].z = minPoint.z;
  32210. this._boundingVectors.push(maxPoint.clone());
  32211. this._boundingVectors[6].x = minPoint.x;
  32212. this._boundingVectors.push(maxPoint.clone());
  32213. this._boundingVectors[7].y = minPoint.y;
  32214. }
  32215. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32216. // Property
  32217. get: function () {
  32218. return this._capacity;
  32219. },
  32220. enumerable: true,
  32221. configurable: true
  32222. });
  32223. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32224. get: function () {
  32225. return this._minPoint;
  32226. },
  32227. enumerable: true,
  32228. configurable: true
  32229. });
  32230. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32231. get: function () {
  32232. return this._maxPoint;
  32233. },
  32234. enumerable: true,
  32235. configurable: true
  32236. });
  32237. // Methods
  32238. OctreeBlock.prototype.addEntry = function (entry) {
  32239. if (this.blocks) {
  32240. for (var index = 0; index < this.blocks.length; index++) {
  32241. var block = this.blocks[index];
  32242. block.addEntry(entry);
  32243. }
  32244. return;
  32245. }
  32246. this._creationFunc(entry, this);
  32247. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32248. this.createInnerBlocks();
  32249. }
  32250. };
  32251. OctreeBlock.prototype.addEntries = function (entries) {
  32252. for (var index = 0; index < entries.length; index++) {
  32253. var mesh = entries[index];
  32254. this.addEntry(mesh);
  32255. }
  32256. };
  32257. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32258. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32259. if (this.blocks) {
  32260. for (var index = 0; index < this.blocks.length; index++) {
  32261. var block = this.blocks[index];
  32262. block.select(frustumPlanes, selection, allowDuplicate);
  32263. }
  32264. return;
  32265. }
  32266. if (allowDuplicate) {
  32267. selection.concat(this.entries);
  32268. }
  32269. else {
  32270. selection.concatWithNoDuplicate(this.entries);
  32271. }
  32272. }
  32273. };
  32274. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32275. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32276. if (this.blocks) {
  32277. for (var index = 0; index < this.blocks.length; index++) {
  32278. var block = this.blocks[index];
  32279. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32280. }
  32281. return;
  32282. }
  32283. if (allowDuplicate) {
  32284. selection.concat(this.entries);
  32285. }
  32286. else {
  32287. selection.concatWithNoDuplicate(this.entries);
  32288. }
  32289. }
  32290. };
  32291. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32292. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32293. if (this.blocks) {
  32294. for (var index = 0; index < this.blocks.length; index++) {
  32295. var block = this.blocks[index];
  32296. block.intersectsRay(ray, selection);
  32297. }
  32298. return;
  32299. }
  32300. selection.concatWithNoDuplicate(this.entries);
  32301. }
  32302. };
  32303. OctreeBlock.prototype.createInnerBlocks = function () {
  32304. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32305. };
  32306. return OctreeBlock;
  32307. })();
  32308. BABYLON.OctreeBlock = OctreeBlock;
  32309. })(BABYLON || (BABYLON = {}));
  32310. var BABYLON;
  32311. (function (BABYLON) {
  32312. var BlurPostProcess = (function (_super) {
  32313. __extends(BlurPostProcess, _super);
  32314. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32315. var _this = this;
  32316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32317. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32318. this.direction = direction;
  32319. this.blurWidth = blurWidth;
  32320. this.onApply = function (effect) {
  32321. effect.setFloat2("screenSize", _this.width, _this.height);
  32322. effect.setVector2("direction", _this.direction);
  32323. effect.setFloat("blurWidth", _this.blurWidth);
  32324. };
  32325. }
  32326. return BlurPostProcess;
  32327. })(BABYLON.PostProcess);
  32328. BABYLON.BlurPostProcess = BlurPostProcess;
  32329. })(BABYLON || (BABYLON = {}));
  32330. var BABYLON;
  32331. (function (BABYLON) {
  32332. var RefractionPostProcess = (function (_super) {
  32333. __extends(RefractionPostProcess, _super);
  32334. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32335. var _this = this;
  32336. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32337. this.color = color;
  32338. this.depth = depth;
  32339. this.colorLevel = colorLevel;
  32340. this.onActivate = function (cam) {
  32341. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32342. };
  32343. this.onApply = function (effect) {
  32344. effect.setColor3("baseColor", _this.color);
  32345. effect.setFloat("depth", _this.depth);
  32346. effect.setFloat("colorLevel", _this.colorLevel);
  32347. effect.setTexture("refractionSampler", _this._refRexture);
  32348. };
  32349. }
  32350. // Methods
  32351. RefractionPostProcess.prototype.dispose = function (camera) {
  32352. if (this._refRexture) {
  32353. this._refRexture.dispose();
  32354. }
  32355. _super.prototype.dispose.call(this, camera);
  32356. };
  32357. return RefractionPostProcess;
  32358. })(BABYLON.PostProcess);
  32359. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32360. })(BABYLON || (BABYLON = {}));
  32361. var BABYLON;
  32362. (function (BABYLON) {
  32363. var BlackAndWhitePostProcess = (function (_super) {
  32364. __extends(BlackAndWhitePostProcess, _super);
  32365. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32366. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32367. }
  32368. return BlackAndWhitePostProcess;
  32369. })(BABYLON.PostProcess);
  32370. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32371. })(BABYLON || (BABYLON = {}));
  32372. var BABYLON;
  32373. (function (BABYLON) {
  32374. var ConvolutionPostProcess = (function (_super) {
  32375. __extends(ConvolutionPostProcess, _super);
  32376. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32377. var _this = this;
  32378. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32379. this.kernel = kernel;
  32380. this.onApply = function (effect) {
  32381. effect.setFloat2("screenSize", _this.width, _this.height);
  32382. effect.setArray("kernel", _this.kernel);
  32383. };
  32384. }
  32385. // Statics
  32386. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32387. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32388. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32389. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32390. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32391. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32392. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32393. return ConvolutionPostProcess;
  32394. })(BABYLON.PostProcess);
  32395. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32396. })(BABYLON || (BABYLON = {}));
  32397. var BABYLON;
  32398. (function (BABYLON) {
  32399. var FilterPostProcess = (function (_super) {
  32400. __extends(FilterPostProcess, _super);
  32401. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32402. var _this = this;
  32403. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32404. this.kernelMatrix = kernelMatrix;
  32405. this.onApply = function (effect) {
  32406. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32407. };
  32408. }
  32409. return FilterPostProcess;
  32410. })(BABYLON.PostProcess);
  32411. BABYLON.FilterPostProcess = FilterPostProcess;
  32412. })(BABYLON || (BABYLON = {}));
  32413. var BABYLON;
  32414. (function (BABYLON) {
  32415. var FxaaPostProcess = (function (_super) {
  32416. __extends(FxaaPostProcess, _super);
  32417. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32418. var _this = this;
  32419. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32420. this.onSizeChanged = function () {
  32421. _this.texelWidth = 1.0 / _this.width;
  32422. _this.texelHeight = 1.0 / _this.height;
  32423. };
  32424. this.onApply = function (effect) {
  32425. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32426. };
  32427. }
  32428. return FxaaPostProcess;
  32429. })(BABYLON.PostProcess);
  32430. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32431. })(BABYLON || (BABYLON = {}));
  32432. var BABYLON;
  32433. (function (BABYLON) {
  32434. var StereoscopicInterlacePostProcess = (function (_super) {
  32435. __extends(StereoscopicInterlacePostProcess, _super);
  32436. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32437. var _this = this;
  32438. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32439. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32440. this.onSizeChanged = function () {
  32441. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32442. };
  32443. this.onApply = function (effect) {
  32444. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32445. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32446. };
  32447. }
  32448. return StereoscopicInterlacePostProcess;
  32449. })(BABYLON.PostProcess);
  32450. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32451. })(BABYLON || (BABYLON = {}));
  32452. var BABYLON;
  32453. (function (BABYLON) {
  32454. var LensFlare = (function () {
  32455. function LensFlare(size, position, color, imgUrl, system) {
  32456. this.size = size;
  32457. this.position = position;
  32458. this.dispose = function () {
  32459. if (this.texture) {
  32460. this.texture.dispose();
  32461. }
  32462. // Remove from scene
  32463. var index = this._system.lensFlares.indexOf(this);
  32464. this._system.lensFlares.splice(index, 1);
  32465. };
  32466. this.color = color || new BABYLON.Color3(1, 1, 1);
  32467. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32468. this._system = system;
  32469. system.lensFlares.push(this);
  32470. }
  32471. return LensFlare;
  32472. })();
  32473. BABYLON.LensFlare = LensFlare;
  32474. })(BABYLON || (BABYLON = {}));
  32475. var BABYLON;
  32476. (function (BABYLON) {
  32477. var LensFlareSystem = (function () {
  32478. function LensFlareSystem(name, emitter, scene) {
  32479. this.name = name;
  32480. this.lensFlares = new Array();
  32481. this.borderLimit = 300;
  32482. this.layerMask = 0x0FFFFFFF;
  32483. this._vertexDeclaration = [2];
  32484. this._vertexStrideSize = 2 * 4;
  32485. this._isEnabled = true;
  32486. this._scene = scene;
  32487. this._emitter = emitter;
  32488. scene.lensFlareSystems.push(this);
  32489. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32490. // VBO
  32491. var vertices = [];
  32492. vertices.push(1, 1);
  32493. vertices.push(-1, 1);
  32494. vertices.push(-1, -1);
  32495. vertices.push(1, -1);
  32496. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32497. // Indices
  32498. var indices = [];
  32499. indices.push(0);
  32500. indices.push(1);
  32501. indices.push(2);
  32502. indices.push(0);
  32503. indices.push(2);
  32504. indices.push(3);
  32505. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32506. // Effects
  32507. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32508. }
  32509. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32510. get: function () {
  32511. return this._isEnabled;
  32512. },
  32513. set: function (value) {
  32514. this._isEnabled = value;
  32515. },
  32516. enumerable: true,
  32517. configurable: true
  32518. });
  32519. LensFlareSystem.prototype.getScene = function () {
  32520. return this._scene;
  32521. };
  32522. LensFlareSystem.prototype.getEmitter = function () {
  32523. return this._emitter;
  32524. };
  32525. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32526. this._emitter = newEmitter;
  32527. };
  32528. LensFlareSystem.prototype.getEmitterPosition = function () {
  32529. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32530. };
  32531. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32532. var position = this.getEmitterPosition();
  32533. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32534. this._positionX = position.x;
  32535. this._positionY = position.y;
  32536. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32537. if (position.z > 0) {
  32538. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32539. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32540. return true;
  32541. }
  32542. }
  32543. return false;
  32544. };
  32545. LensFlareSystem.prototype._isVisible = function () {
  32546. if (!this._isEnabled) {
  32547. return false;
  32548. }
  32549. var emitterPosition = this.getEmitterPosition();
  32550. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32551. var distance = direction.length();
  32552. direction.normalize();
  32553. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32554. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32555. return !pickInfo.hit || pickInfo.distance > distance;
  32556. };
  32557. LensFlareSystem.prototype.render = function () {
  32558. if (!this._effect.isReady())
  32559. return false;
  32560. var engine = this._scene.getEngine();
  32561. var viewport = this._scene.activeCamera.viewport;
  32562. var globalViewport = viewport.toGlobal(engine);
  32563. // Position
  32564. if (!this.computeEffectivePosition(globalViewport)) {
  32565. return false;
  32566. }
  32567. // Visibility
  32568. if (!this._isVisible()) {
  32569. return false;
  32570. }
  32571. // Intensity
  32572. var awayX;
  32573. var awayY;
  32574. if (this._positionX < this.borderLimit + globalViewport.x) {
  32575. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32576. }
  32577. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32578. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32579. }
  32580. else {
  32581. awayX = 0;
  32582. }
  32583. if (this._positionY < this.borderLimit + globalViewport.y) {
  32584. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32585. }
  32586. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32587. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32588. }
  32589. else {
  32590. awayY = 0;
  32591. }
  32592. var away = (awayX > awayY) ? awayX : awayY;
  32593. if (away > this.borderLimit) {
  32594. away = this.borderLimit;
  32595. }
  32596. var intensity = 1.0 - (away / this.borderLimit);
  32597. if (intensity < 0) {
  32598. return false;
  32599. }
  32600. if (intensity > 1.0) {
  32601. intensity = 1.0;
  32602. }
  32603. // Position
  32604. var centerX = globalViewport.x + globalViewport.width / 2;
  32605. var centerY = globalViewport.y + globalViewport.height / 2;
  32606. var distX = centerX - this._positionX;
  32607. var distY = centerY - this._positionY;
  32608. // Effects
  32609. engine.enableEffect(this._effect);
  32610. engine.setState(false);
  32611. engine.setDepthBuffer(false);
  32612. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32613. // VBOs
  32614. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32615. // Flares
  32616. for (var index = 0; index < this.lensFlares.length; index++) {
  32617. var flare = this.lensFlares[index];
  32618. var x = centerX - (distX * flare.position);
  32619. var y = centerY - (distY * flare.position);
  32620. var cw = flare.size;
  32621. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32622. var cx = 2 * (x / globalViewport.width) - 1.0;
  32623. var cy = 1.0 - 2 * (y / globalViewport.height);
  32624. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32625. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32626. // Texture
  32627. this._effect.setTexture("textureSampler", flare.texture);
  32628. // Color
  32629. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32630. // Draw order
  32631. engine.draw(true, 0, 6);
  32632. }
  32633. engine.setDepthBuffer(true);
  32634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32635. return true;
  32636. };
  32637. LensFlareSystem.prototype.dispose = function () {
  32638. if (this._vertexBuffer) {
  32639. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32640. this._vertexBuffer = null;
  32641. }
  32642. if (this._indexBuffer) {
  32643. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32644. this._indexBuffer = null;
  32645. }
  32646. while (this.lensFlares.length) {
  32647. this.lensFlares[0].dispose();
  32648. }
  32649. // Remove from scene
  32650. var index = this._scene.lensFlareSystems.indexOf(this);
  32651. this._scene.lensFlareSystems.splice(index, 1);
  32652. };
  32653. return LensFlareSystem;
  32654. })();
  32655. BABYLON.LensFlareSystem = LensFlareSystem;
  32656. })(BABYLON || (BABYLON = {}));
  32657. var BABYLON;
  32658. (function (BABYLON) {
  32659. // We're mainly based on the logic defined into the FreeCamera code
  32660. var DeviceOrientationCamera = (function (_super) {
  32661. __extends(DeviceOrientationCamera, _super);
  32662. function DeviceOrientationCamera(name, position, scene) {
  32663. var _this = this;
  32664. _super.call(this, name, position, scene);
  32665. this._offsetX = null;
  32666. this._offsetY = null;
  32667. this._orientationGamma = 0;
  32668. this._orientationBeta = 0;
  32669. this._initialOrientationGamma = 0;
  32670. this._initialOrientationBeta = 0;
  32671. this.angularSensibility = 10000.0;
  32672. this.moveSensibility = 50.0;
  32673. window.addEventListener("resize", function () {
  32674. _this._initialOrientationGamma = null;
  32675. }, false);
  32676. }
  32677. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32678. var _this = this;
  32679. if (this._attachedCanvas) {
  32680. return;
  32681. }
  32682. this._attachedCanvas = canvas;
  32683. if (!this._orientationChanged) {
  32684. this._orientationChanged = function (evt) {
  32685. if (!_this._initialOrientationGamma) {
  32686. _this._initialOrientationGamma = evt.gamma;
  32687. _this._initialOrientationBeta = evt.beta;
  32688. }
  32689. _this._orientationGamma = evt.gamma;
  32690. _this._orientationBeta = evt.beta;
  32691. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32692. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32693. };
  32694. }
  32695. window.addEventListener("deviceorientation", this._orientationChanged);
  32696. };
  32697. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32698. if (this._attachedCanvas != canvas) {
  32699. return;
  32700. }
  32701. window.removeEventListener("deviceorientation", this._orientationChanged);
  32702. this._attachedCanvas = null;
  32703. this._orientationGamma = 0;
  32704. this._orientationBeta = 0;
  32705. this._initialOrientationGamma = 0;
  32706. this._initialOrientationBeta = 0;
  32707. };
  32708. DeviceOrientationCamera.prototype._checkInputs = function () {
  32709. if (!this._offsetX) {
  32710. return;
  32711. }
  32712. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32713. var speed = this._computeLocalCameraSpeed();
  32714. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32715. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32716. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32717. _super.prototype._checkInputs.call(this);
  32718. };
  32719. return DeviceOrientationCamera;
  32720. })(BABYLON.FreeCamera);
  32721. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32722. })(BABYLON || (BABYLON = {}));
  32723. var BABYLON;
  32724. (function (BABYLON) {
  32725. var Gamepads = (function () {
  32726. function Gamepads(ongamedpadconnected) {
  32727. var _this = this;
  32728. this.babylonGamepads = [];
  32729. this.oneGamepadConnected = false;
  32730. this.isMonitoring = false;
  32731. this.gamepadEventSupported = 'GamepadEvent' in window;
  32732. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32733. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32734. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  32735. this._callbackGamepadConnected = ongamedpadconnected;
  32736. if (this.gamepadSupportAvailable) {
  32737. // Checking if the gamepad connected event is supported (like in Firefox)
  32738. if (this.gamepadEventSupported) {
  32739. window.addEventListener('gamepadconnected', function (evt) {
  32740. _this._onGamepadConnected(evt);
  32741. }, false);
  32742. window.addEventListener('gamepaddisconnected', function (evt) {
  32743. _this._onGamepadDisconnected(evt);
  32744. }, false);
  32745. }
  32746. else {
  32747. this._startMonitoringGamepads();
  32748. }
  32749. if (!this.oneGamepadConnected) {
  32750. this._insertGamepadDOMInstructions();
  32751. }
  32752. }
  32753. else {
  32754. this._insertGamepadDOMNotSupported();
  32755. }
  32756. }
  32757. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32758. Gamepads.gamepadDOMInfo = document.createElement("div");
  32759. var buttonAImage = document.createElement("img");
  32760. buttonAImage.src = this.buttonADataURL;
  32761. var spanMessage = document.createElement("span");
  32762. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32763. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32764. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32765. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32766. Gamepads.gamepadDOMInfo.style.width = "100%";
  32767. Gamepads.gamepadDOMInfo.style.height = "48px";
  32768. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32769. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32770. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32771. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32772. buttonAImage.style.position = "relative";
  32773. buttonAImage.style.bottom = "8px";
  32774. spanMessage.style.position = "relative";
  32775. spanMessage.style.fontSize = "32px";
  32776. spanMessage.style.bottom = "32px";
  32777. spanMessage.style.color = "green";
  32778. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32779. };
  32780. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32781. Gamepads.gamepadDOMInfo = document.createElement("div");
  32782. var spanMessage = document.createElement("span");
  32783. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32784. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32785. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32786. Gamepads.gamepadDOMInfo.style.width = "100%";
  32787. Gamepads.gamepadDOMInfo.style.height = "40px";
  32788. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32789. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32790. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32791. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32792. spanMessage.style.position = "relative";
  32793. spanMessage.style.fontSize = "32px";
  32794. spanMessage.style.color = "red";
  32795. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32796. };
  32797. Gamepads.prototype.dispose = function () {
  32798. if (Gamepads.gamepadDOMInfo) {
  32799. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32800. }
  32801. };
  32802. Gamepads.prototype._onGamepadConnected = function (evt) {
  32803. var newGamepad = this._addNewGamepad(evt.gamepad);
  32804. if (this._callbackGamepadConnected)
  32805. this._callbackGamepadConnected(newGamepad);
  32806. this._startMonitoringGamepads();
  32807. };
  32808. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32809. if (!this.oneGamepadConnected) {
  32810. this.oneGamepadConnected = true;
  32811. if (Gamepads.gamepadDOMInfo) {
  32812. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32813. Gamepads.gamepadDOMInfo = null;
  32814. }
  32815. }
  32816. var newGamepad;
  32817. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32818. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32819. }
  32820. else {
  32821. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32822. }
  32823. this.babylonGamepads.push(newGamepad);
  32824. return newGamepad;
  32825. };
  32826. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32827. // Remove the gamepad from the list of gamepads to monitor.
  32828. for (var i in this.babylonGamepads) {
  32829. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32830. this.babylonGamepads.splice(i, 1);
  32831. break;
  32832. }
  32833. }
  32834. // If no gamepads are left, stop the polling loop.
  32835. if (this.babylonGamepads.length == 0) {
  32836. this._stopMonitoringGamepads();
  32837. }
  32838. };
  32839. Gamepads.prototype._startMonitoringGamepads = function () {
  32840. if (!this.isMonitoring) {
  32841. this.isMonitoring = true;
  32842. this._checkGamepadsStatus();
  32843. }
  32844. };
  32845. Gamepads.prototype._stopMonitoringGamepads = function () {
  32846. this.isMonitoring = false;
  32847. };
  32848. Gamepads.prototype._checkGamepadsStatus = function () {
  32849. var _this = this;
  32850. // updating gamepad objects
  32851. this._updateGamepadObjects();
  32852. for (var i in this.babylonGamepads) {
  32853. this.babylonGamepads[i].update();
  32854. }
  32855. if (this.isMonitoring) {
  32856. if (window.requestAnimationFrame) {
  32857. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32858. }
  32859. else if (window.mozRequestAnimationFrame) {
  32860. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32861. }
  32862. else if (window.webkitRequestAnimationFrame) {
  32863. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32864. }
  32865. }
  32866. };
  32867. // This function is called only on Chrome, which does not yet support
  32868. // connection/disconnection events, but requires you to monitor
  32869. // an array for changes.
  32870. Gamepads.prototype._updateGamepadObjects = function () {
  32871. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32872. for (var i = 0; i < gamepads.length; i++) {
  32873. if (gamepads[i]) {
  32874. if (!(gamepads[i].index in this.babylonGamepads)) {
  32875. var newGamepad = this._addNewGamepad(gamepads[i]);
  32876. if (this._callbackGamepadConnected) {
  32877. this._callbackGamepadConnected(newGamepad);
  32878. }
  32879. }
  32880. else {
  32881. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32882. }
  32883. }
  32884. }
  32885. };
  32886. return Gamepads;
  32887. })();
  32888. BABYLON.Gamepads = Gamepads;
  32889. var StickValues = (function () {
  32890. function StickValues(x, y) {
  32891. this.x = x;
  32892. this.y = y;
  32893. }
  32894. return StickValues;
  32895. })();
  32896. BABYLON.StickValues = StickValues;
  32897. var Gamepad = (function () {
  32898. function Gamepad(id, index, browserGamepad) {
  32899. this.id = id;
  32900. this.index = index;
  32901. this.browserGamepad = browserGamepad;
  32902. if (this.browserGamepad.axes.length >= 2) {
  32903. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32904. }
  32905. if (this.browserGamepad.axes.length >= 4) {
  32906. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32907. }
  32908. }
  32909. Gamepad.prototype.onleftstickchanged = function (callback) {
  32910. this._onleftstickchanged = callback;
  32911. };
  32912. Gamepad.prototype.onrightstickchanged = function (callback) {
  32913. this._onrightstickchanged = callback;
  32914. };
  32915. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32916. get: function () {
  32917. return this._leftStick;
  32918. },
  32919. set: function (newValues) {
  32920. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32921. this._onleftstickchanged(newValues);
  32922. }
  32923. this._leftStick = newValues;
  32924. },
  32925. enumerable: true,
  32926. configurable: true
  32927. });
  32928. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32929. get: function () {
  32930. return this._rightStick;
  32931. },
  32932. set: function (newValues) {
  32933. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32934. this._onrightstickchanged(newValues);
  32935. }
  32936. this._rightStick = newValues;
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. Gamepad.prototype.update = function () {
  32942. if (this._leftStick) {
  32943. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32944. }
  32945. if (this._rightStick) {
  32946. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32947. }
  32948. };
  32949. return Gamepad;
  32950. })();
  32951. BABYLON.Gamepad = Gamepad;
  32952. var GenericPad = (function (_super) {
  32953. __extends(GenericPad, _super);
  32954. function GenericPad(id, index, gamepad) {
  32955. _super.call(this, id, index, gamepad);
  32956. this.id = id;
  32957. this.index = index;
  32958. this.gamepad = gamepad;
  32959. this._buttons = new Array(gamepad.buttons.length);
  32960. }
  32961. GenericPad.prototype.onbuttondown = function (callback) {
  32962. this._onbuttondown = callback;
  32963. };
  32964. GenericPad.prototype.onbuttonup = function (callback) {
  32965. this._onbuttonup = callback;
  32966. };
  32967. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32968. if (newValue !== currentValue) {
  32969. if (this._onbuttondown && newValue === 1) {
  32970. this._onbuttondown(buttonIndex);
  32971. }
  32972. if (this._onbuttonup && newValue === 0) {
  32973. this._onbuttonup(buttonIndex);
  32974. }
  32975. }
  32976. return newValue;
  32977. };
  32978. GenericPad.prototype.update = function () {
  32979. _super.prototype.update.call(this);
  32980. for (var index = 0; index < this._buttons.length; index++) {
  32981. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32982. }
  32983. };
  32984. return GenericPad;
  32985. })(Gamepad);
  32986. BABYLON.GenericPad = GenericPad;
  32987. (function (Xbox360Button) {
  32988. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32989. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32990. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32991. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32992. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32993. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32994. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32995. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32996. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32997. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32998. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32999. var Xbox360Button = BABYLON.Xbox360Button;
  33000. (function (Xbox360Dpad) {
  33001. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33002. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33003. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33004. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33005. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33006. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33007. var Xbox360Pad = (function (_super) {
  33008. __extends(Xbox360Pad, _super);
  33009. function Xbox360Pad() {
  33010. _super.apply(this, arguments);
  33011. this._leftTrigger = 0;
  33012. this._rightTrigger = 0;
  33013. this._buttonA = 0;
  33014. this._buttonB = 0;
  33015. this._buttonX = 0;
  33016. this._buttonY = 0;
  33017. this._buttonBack = 0;
  33018. this._buttonStart = 0;
  33019. this._buttonLB = 0;
  33020. this._buttonRB = 0;
  33021. this._buttonLeftStick = 0;
  33022. this._buttonRightStick = 0;
  33023. this._dPadUp = 0;
  33024. this._dPadDown = 0;
  33025. this._dPadLeft = 0;
  33026. this._dPadRight = 0;
  33027. }
  33028. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33029. this._onlefttriggerchanged = callback;
  33030. };
  33031. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33032. this._onrighttriggerchanged = callback;
  33033. };
  33034. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33035. get: function () {
  33036. return this._leftTrigger;
  33037. },
  33038. set: function (newValue) {
  33039. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33040. this._onlefttriggerchanged(newValue);
  33041. }
  33042. this._leftTrigger = newValue;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33048. get: function () {
  33049. return this._rightTrigger;
  33050. },
  33051. set: function (newValue) {
  33052. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33053. this._onrighttriggerchanged(newValue);
  33054. }
  33055. this._rightTrigger = newValue;
  33056. },
  33057. enumerable: true,
  33058. configurable: true
  33059. });
  33060. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33061. this._onbuttondown = callback;
  33062. };
  33063. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33064. this._onbuttonup = callback;
  33065. };
  33066. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33067. this._ondpaddown = callback;
  33068. };
  33069. Xbox360Pad.prototype.ondpadup = function (callback) {
  33070. this._ondpadup = callback;
  33071. };
  33072. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33073. if (newValue !== currentValue) {
  33074. if (this._onbuttondown && newValue === 1) {
  33075. this._onbuttondown(buttonType);
  33076. }
  33077. if (this._onbuttonup && newValue === 0) {
  33078. this._onbuttonup(buttonType);
  33079. }
  33080. }
  33081. return newValue;
  33082. };
  33083. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33084. if (newValue !== currentValue) {
  33085. if (this._ondpaddown && newValue === 1) {
  33086. this._ondpaddown(buttonType);
  33087. }
  33088. if (this._ondpadup && newValue === 0) {
  33089. this._ondpadup(buttonType);
  33090. }
  33091. }
  33092. return newValue;
  33093. };
  33094. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33095. get: function () {
  33096. return this._buttonA;
  33097. },
  33098. set: function (value) {
  33099. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33100. },
  33101. enumerable: true,
  33102. configurable: true
  33103. });
  33104. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33105. get: function () {
  33106. return this._buttonB;
  33107. },
  33108. set: function (value) {
  33109. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33110. },
  33111. enumerable: true,
  33112. configurable: true
  33113. });
  33114. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33115. get: function () {
  33116. return this._buttonX;
  33117. },
  33118. set: function (value) {
  33119. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33120. },
  33121. enumerable: true,
  33122. configurable: true
  33123. });
  33124. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33125. get: function () {
  33126. return this._buttonY;
  33127. },
  33128. set: function (value) {
  33129. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33130. },
  33131. enumerable: true,
  33132. configurable: true
  33133. });
  33134. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33135. get: function () {
  33136. return this._buttonStart;
  33137. },
  33138. set: function (value) {
  33139. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33140. },
  33141. enumerable: true,
  33142. configurable: true
  33143. });
  33144. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33145. get: function () {
  33146. return this._buttonBack;
  33147. },
  33148. set: function (value) {
  33149. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33150. },
  33151. enumerable: true,
  33152. configurable: true
  33153. });
  33154. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33155. get: function () {
  33156. return this._buttonLB;
  33157. },
  33158. set: function (value) {
  33159. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33160. },
  33161. enumerable: true,
  33162. configurable: true
  33163. });
  33164. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33165. get: function () {
  33166. return this._buttonRB;
  33167. },
  33168. set: function (value) {
  33169. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33170. },
  33171. enumerable: true,
  33172. configurable: true
  33173. });
  33174. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33175. get: function () {
  33176. return this._buttonLeftStick;
  33177. },
  33178. set: function (value) {
  33179. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33180. },
  33181. enumerable: true,
  33182. configurable: true
  33183. });
  33184. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33185. get: function () {
  33186. return this._buttonRightStick;
  33187. },
  33188. set: function (value) {
  33189. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33190. },
  33191. enumerable: true,
  33192. configurable: true
  33193. });
  33194. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33195. get: function () {
  33196. return this._dPadUp;
  33197. },
  33198. set: function (value) {
  33199. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33200. },
  33201. enumerable: true,
  33202. configurable: true
  33203. });
  33204. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33205. get: function () {
  33206. return this._dPadDown;
  33207. },
  33208. set: function (value) {
  33209. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33210. },
  33211. enumerable: true,
  33212. configurable: true
  33213. });
  33214. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33215. get: function () {
  33216. return this._dPadLeft;
  33217. },
  33218. set: function (value) {
  33219. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33220. },
  33221. enumerable: true,
  33222. configurable: true
  33223. });
  33224. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33225. get: function () {
  33226. return this._dPadRight;
  33227. },
  33228. set: function (value) {
  33229. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33230. },
  33231. enumerable: true,
  33232. configurable: true
  33233. });
  33234. Xbox360Pad.prototype.update = function () {
  33235. _super.prototype.update.call(this);
  33236. this.buttonA = this.browserGamepad.buttons[0].value;
  33237. this.buttonB = this.browserGamepad.buttons[1].value;
  33238. this.buttonX = this.browserGamepad.buttons[2].value;
  33239. this.buttonY = this.browserGamepad.buttons[3].value;
  33240. this.buttonLB = this.browserGamepad.buttons[4].value;
  33241. this.buttonRB = this.browserGamepad.buttons[5].value;
  33242. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33243. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33244. this.buttonBack = this.browserGamepad.buttons[8].value;
  33245. this.buttonStart = this.browserGamepad.buttons[9].value;
  33246. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33247. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33248. this.dPadUp = this.browserGamepad.buttons[12].value;
  33249. this.dPadDown = this.browserGamepad.buttons[13].value;
  33250. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33251. this.dPadRight = this.browserGamepad.buttons[15].value;
  33252. };
  33253. return Xbox360Pad;
  33254. })(Gamepad);
  33255. BABYLON.Xbox360Pad = Xbox360Pad;
  33256. })(BABYLON || (BABYLON = {}));
  33257. var BABYLON;
  33258. (function (BABYLON) {
  33259. // We're mainly based on the logic defined into the FreeCamera code
  33260. var GamepadCamera = (function (_super) {
  33261. __extends(GamepadCamera, _super);
  33262. function GamepadCamera(name, position, scene) {
  33263. var _this = this;
  33264. _super.call(this, name, position, scene);
  33265. this.angularSensibility = 200;
  33266. this.moveSensibility = 75;
  33267. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33268. }
  33269. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33270. // Only the first gamepad can control the camera
  33271. if (gamepad.index === 0) {
  33272. this._gamepad = gamepad;
  33273. }
  33274. };
  33275. GamepadCamera.prototype._checkInputs = function () {
  33276. if (this._gamepad) {
  33277. var LSValues = this._gamepad.leftStick;
  33278. var normalizedLX = LSValues.x / this.moveSensibility;
  33279. var normalizedLY = LSValues.y / this.moveSensibility;
  33280. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33281. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33282. var RSValues = this._gamepad.rightStick;
  33283. var normalizedRX = RSValues.x / this.angularSensibility;
  33284. var normalizedRY = RSValues.y / this.angularSensibility;
  33285. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33286. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33287. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33288. var speed = this._computeLocalCameraSpeed() * 50.0;
  33289. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33290. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33291. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33292. }
  33293. _super.prototype._checkInputs.call(this);
  33294. };
  33295. GamepadCamera.prototype.dispose = function () {
  33296. this._gamepads.dispose();
  33297. _super.prototype.dispose.call(this);
  33298. };
  33299. return GamepadCamera;
  33300. })(BABYLON.FreeCamera);
  33301. BABYLON.GamepadCamera = GamepadCamera;
  33302. })(BABYLON || (BABYLON = {}));
  33303. var BABYLON;
  33304. (function (BABYLON) {
  33305. var Analyser = (function () {
  33306. function Analyser(scene) {
  33307. this.SMOOTHING = 0.75;
  33308. this.FFT_SIZE = 512;
  33309. this.BARGRAPHAMPLITUDE = 256;
  33310. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33311. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33312. this._scene = scene;
  33313. this._audioEngine = BABYLON.Engine.audioEngine;
  33314. if (this._audioEngine.canUseWebAudio) {
  33315. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33316. this._webAudioAnalyser.minDecibels = -140;
  33317. this._webAudioAnalyser.maxDecibels = 0;
  33318. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33319. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33320. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33321. }
  33322. }
  33323. Analyser.prototype.getFrequencyBinCount = function () {
  33324. if (this._audioEngine.canUseWebAudio) {
  33325. return this._webAudioAnalyser.frequencyBinCount;
  33326. }
  33327. else {
  33328. return 0;
  33329. }
  33330. };
  33331. Analyser.prototype.getByteFrequencyData = function () {
  33332. if (this._audioEngine.canUseWebAudio) {
  33333. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33334. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33335. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33336. }
  33337. return this._byteFreqs;
  33338. };
  33339. Analyser.prototype.getByteTimeDomainData = function () {
  33340. if (this._audioEngine.canUseWebAudio) {
  33341. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33342. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33343. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33344. }
  33345. return this._byteTime;
  33346. };
  33347. Analyser.prototype.getFloatFrequencyData = function () {
  33348. if (this._audioEngine.canUseWebAudio) {
  33349. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33350. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33351. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33352. }
  33353. return this._floatFreqs;
  33354. };
  33355. Analyser.prototype.drawDebugCanvas = function () {
  33356. var _this = this;
  33357. if (this._audioEngine.canUseWebAudio) {
  33358. if (!this._debugCanvas) {
  33359. this._debugCanvas = document.createElement("canvas");
  33360. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33361. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33362. this._debugCanvas.style.position = "absolute";
  33363. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33364. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33365. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33366. document.body.appendChild(this._debugCanvas);
  33367. this._registerFunc = function () {
  33368. _this.drawDebugCanvas();
  33369. };
  33370. this._scene.registerBeforeRender(this._registerFunc);
  33371. }
  33372. if (this._registerFunc) {
  33373. var workingArray = this.getByteFrequencyData();
  33374. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33375. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33376. // Draw the frequency domain chart.
  33377. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33378. var value = workingArray[i];
  33379. var percent = value / this.BARGRAPHAMPLITUDE;
  33380. var height = this.DEBUGCANVASSIZE.height * percent;
  33381. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33382. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33383. var hue = i / this.getFrequencyBinCount() * 360;
  33384. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33385. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33386. }
  33387. }
  33388. }
  33389. };
  33390. Analyser.prototype.stopDebugCanvas = function () {
  33391. if (this._debugCanvas) {
  33392. this._scene.unregisterBeforeRender(this._registerFunc);
  33393. this._registerFunc = null;
  33394. document.body.removeChild(this._debugCanvas);
  33395. this._debugCanvas = null;
  33396. this._debugCanvasContext = null;
  33397. }
  33398. };
  33399. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33400. if (this._audioEngine.canUseWebAudio) {
  33401. inputAudioNode.connect(this._webAudioAnalyser);
  33402. this._webAudioAnalyser.connect(outputAudioNode);
  33403. }
  33404. };
  33405. Analyser.prototype.dispose = function () {
  33406. if (this._audioEngine.canUseWebAudio) {
  33407. this._webAudioAnalyser.disconnect();
  33408. }
  33409. };
  33410. return Analyser;
  33411. })();
  33412. BABYLON.Analyser = Analyser;
  33413. })(BABYLON || (BABYLON = {}));
  33414. var BABYLON;
  33415. (function (BABYLON) {
  33416. var AudioEngine = (function () {
  33417. function AudioEngine() {
  33418. this._audioContext = null;
  33419. this._audioContextInitialized = false;
  33420. this.canUseWebAudio = false;
  33421. this.WarnedWebAudioUnsupported = false;
  33422. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33423. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33424. this.canUseWebAudio = true;
  33425. }
  33426. }
  33427. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33428. get: function () {
  33429. if (!this._audioContextInitialized) {
  33430. this._initializeAudioContext();
  33431. }
  33432. return this._audioContext;
  33433. },
  33434. enumerable: true,
  33435. configurable: true
  33436. });
  33437. AudioEngine.prototype._initializeAudioContext = function () {
  33438. try {
  33439. if (this.canUseWebAudio) {
  33440. this._audioContext = new AudioContext();
  33441. // create a global volume gain node
  33442. this.masterGain = this._audioContext.createGain();
  33443. this.masterGain.gain.value = 1;
  33444. this.masterGain.connect(this._audioContext.destination);
  33445. this._audioContextInitialized = true;
  33446. }
  33447. }
  33448. catch (e) {
  33449. this.canUseWebAudio = false;
  33450. BABYLON.Tools.Error("Web Audio: " + e.message);
  33451. }
  33452. };
  33453. AudioEngine.prototype.dispose = function () {
  33454. if (this.canUseWebAudio && this._audioContextInitialized) {
  33455. if (this._connectedAnalyser) {
  33456. this._connectedAnalyser.stopDebugCanvas();
  33457. this._connectedAnalyser.dispose();
  33458. this.masterGain.disconnect();
  33459. this.masterGain.connect(this._audioContext.destination);
  33460. this._connectedAnalyser = null;
  33461. }
  33462. this.masterGain.gain.value = 1;
  33463. }
  33464. this.WarnedWebAudioUnsupported = false;
  33465. };
  33466. AudioEngine.prototype.getGlobalVolume = function () {
  33467. if (this.canUseWebAudio && this._audioContextInitialized) {
  33468. return this.masterGain.gain.value;
  33469. }
  33470. else {
  33471. return -1;
  33472. }
  33473. };
  33474. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33475. if (this.canUseWebAudio && this._audioContextInitialized) {
  33476. this.masterGain.gain.value = newVolume;
  33477. }
  33478. };
  33479. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33480. if (this._connectedAnalyser) {
  33481. this._connectedAnalyser.stopDebugCanvas();
  33482. }
  33483. if (this.canUseWebAudio && this._audioContextInitialized) {
  33484. this._connectedAnalyser = analyser;
  33485. this.masterGain.disconnect();
  33486. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33487. }
  33488. };
  33489. return AudioEngine;
  33490. })();
  33491. BABYLON.AudioEngine = AudioEngine;
  33492. })(BABYLON || (BABYLON = {}));
  33493. var BABYLON;
  33494. (function (BABYLON) {
  33495. var Sound = (function () {
  33496. /**
  33497. * Create a sound and attach it to a scene
  33498. * @param name Name of your sound
  33499. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33500. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33501. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33502. */
  33503. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33504. var _this = this;
  33505. this.autoplay = false;
  33506. this.loop = false;
  33507. this.useCustomAttenuation = false;
  33508. this.spatialSound = false;
  33509. this.refDistance = 1;
  33510. this.rolloffFactor = 1;
  33511. this.maxDistance = 100;
  33512. this.distanceModel = "linear";
  33513. this._panningModel = "equalpower";
  33514. this._playbackRate = 1;
  33515. this._streaming = false;
  33516. this._startTime = 0;
  33517. this._startOffset = 0;
  33518. this._position = BABYLON.Vector3.Zero();
  33519. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33520. this._volume = 1;
  33521. this._isLoaded = false;
  33522. this._isReadyToPlay = false;
  33523. this.isPlaying = false;
  33524. this.isPaused = false;
  33525. this._isDirectional = false;
  33526. // Used if you'd like to create a directional sound.
  33527. // If not set, the sound will be omnidirectional
  33528. this._coneInnerAngle = 360;
  33529. this._coneOuterAngle = 360;
  33530. this._coneOuterGain = 0;
  33531. this._isOutputConnected = false;
  33532. this.name = name;
  33533. this._scene = scene;
  33534. this._readyToPlayCallback = readyToPlayCallback;
  33535. // Default custom attenuation function is a linear attenuation
  33536. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33537. if (currentDistance < maxDistance) {
  33538. return currentVolume * (1 - currentDistance / maxDistance);
  33539. }
  33540. else {
  33541. return 0;
  33542. }
  33543. };
  33544. if (options) {
  33545. this.autoplay = options.autoplay || false;
  33546. this.loop = options.loop || false;
  33547. // if volume === 0, we need another way to check this option
  33548. if (options.volume !== undefined) {
  33549. this._volume = options.volume;
  33550. }
  33551. this.spatialSound = options.spatialSound || false;
  33552. this.maxDistance = options.maxDistance || 100;
  33553. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33554. this.rolloffFactor = options.rolloffFactor || 1;
  33555. this.refDistance = options.refDistance || 1;
  33556. this.distanceModel = options.distanceModel || "linear";
  33557. this._playbackRate = options.playbackRate || 1;
  33558. this._streaming = options.streaming || false;
  33559. }
  33560. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33561. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33562. this._soundGain.gain.value = this._volume;
  33563. this._inputAudioNode = this._soundGain;
  33564. this._ouputAudioNode = this._soundGain;
  33565. if (this.spatialSound) {
  33566. this._createSpatialParameters();
  33567. }
  33568. this._scene.mainSoundTrack.AddSound(this);
  33569. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33570. if (urlOrArrayBuffer) {
  33571. // If it's an URL
  33572. if (typeof (urlOrArrayBuffer) === "string") {
  33573. // Loading sound using XHR2
  33574. if (!this._streaming) {
  33575. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33576. }
  33577. else {
  33578. this._htmlAudioElement = new Audio();
  33579. this._htmlAudioElement.src = urlOrArrayBuffer;
  33580. this._htmlAudioElement.controls = false;
  33581. this._htmlAudioElement.loop = this.loop;
  33582. this._htmlAudioElement.crossOrigin = "anonymous";
  33583. this._isReadyToPlay = true;
  33584. document.body.appendChild(this._htmlAudioElement);
  33585. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33586. if (this._readyToPlayCallback) {
  33587. window.setTimeout(function () {
  33588. _this._readyToPlayCallback();
  33589. }, 1000);
  33590. }
  33591. if (this.autoplay) {
  33592. this.play();
  33593. }
  33594. }
  33595. }
  33596. else {
  33597. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33598. this._soundLoaded(urlOrArrayBuffer);
  33599. }
  33600. else {
  33601. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33602. }
  33603. }
  33604. }
  33605. }
  33606. else {
  33607. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33608. this._scene.mainSoundTrack.AddSound(this);
  33609. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33610. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33611. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33612. }
  33613. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33614. if (this._readyToPlayCallback) {
  33615. window.setTimeout(function () {
  33616. _this._readyToPlayCallback();
  33617. }, 1000);
  33618. }
  33619. }
  33620. }
  33621. Sound.prototype.dispose = function () {
  33622. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33623. if (this.isPlaying) {
  33624. this.stop();
  33625. }
  33626. this._isReadyToPlay = false;
  33627. if (this.soundTrackId === -1) {
  33628. this._scene.mainSoundTrack.RemoveSound(this);
  33629. }
  33630. else {
  33631. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33632. }
  33633. if (this._soundGain) {
  33634. this._soundGain.disconnect();
  33635. this._soundGain = null;
  33636. }
  33637. if (this._soundPanner) {
  33638. this._soundPanner.disconnect();
  33639. this._soundPanner = null;
  33640. }
  33641. if (this._soundSource) {
  33642. this._soundSource.disconnect();
  33643. this._soundSource = null;
  33644. }
  33645. this._audioBuffer = null;
  33646. if (this._htmlAudioElement) {
  33647. this._htmlAudioElement.pause();
  33648. this._htmlAudioElement.src = "";
  33649. document.body.removeChild(this._htmlAudioElement);
  33650. }
  33651. if (this._connectedMesh) {
  33652. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33653. this._connectedMesh = null;
  33654. }
  33655. }
  33656. };
  33657. Sound.prototype._soundLoaded = function (audioData) {
  33658. var _this = this;
  33659. this._isLoaded = true;
  33660. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33661. _this._audioBuffer = buffer;
  33662. _this._isReadyToPlay = true;
  33663. if (_this.autoplay) {
  33664. _this.play();
  33665. }
  33666. if (_this._readyToPlayCallback) {
  33667. _this._readyToPlayCallback();
  33668. }
  33669. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33670. };
  33671. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33673. this._audioBuffer = audioBuffer;
  33674. this._isReadyToPlay = true;
  33675. }
  33676. };
  33677. Sound.prototype.updateOptions = function (options) {
  33678. if (options) {
  33679. this.loop = options.loop || this.loop;
  33680. this.maxDistance = options.maxDistance || this.maxDistance;
  33681. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33682. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33683. this.refDistance = options.refDistance || this.refDistance;
  33684. this.distanceModel = options.distanceModel || this.distanceModel;
  33685. this._playbackRate = options.playbackRate || this._playbackRate;
  33686. this._updateSpatialParameters();
  33687. if (this.isPlaying) {
  33688. if (this._streaming) {
  33689. this._htmlAudioElement.playbackRate = this._playbackRate;
  33690. }
  33691. else {
  33692. this._soundSource.playbackRate.value = this._playbackRate;
  33693. }
  33694. }
  33695. }
  33696. };
  33697. Sound.prototype._createSpatialParameters = function () {
  33698. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33699. if (this._scene.headphone) {
  33700. this._panningModel = "HRTF";
  33701. }
  33702. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33703. this._updateSpatialParameters();
  33704. this._soundPanner.connect(this._ouputAudioNode);
  33705. this._inputAudioNode = this._soundPanner;
  33706. }
  33707. };
  33708. Sound.prototype._updateSpatialParameters = function () {
  33709. if (this.spatialSound) {
  33710. if (this.useCustomAttenuation) {
  33711. // Tricks to disable in a way embedded Web Audio attenuation
  33712. this._soundPanner.distanceModel = "linear";
  33713. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33714. this._soundPanner.refDistance = 1;
  33715. this._soundPanner.rolloffFactor = 1;
  33716. this._soundPanner.panningModel = this._panningModel;
  33717. }
  33718. else {
  33719. this._soundPanner.distanceModel = this.distanceModel;
  33720. this._soundPanner.maxDistance = this.maxDistance;
  33721. this._soundPanner.refDistance = this.refDistance;
  33722. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33723. this._soundPanner.panningModel = this._panningModel;
  33724. }
  33725. }
  33726. };
  33727. Sound.prototype.switchPanningModelToHRTF = function () {
  33728. this._panningModel = "HRTF";
  33729. this._switchPanningModel();
  33730. };
  33731. Sound.prototype.switchPanningModelToEqualPower = function () {
  33732. this._panningModel = "equalpower";
  33733. this._switchPanningModel();
  33734. };
  33735. Sound.prototype._switchPanningModel = function () {
  33736. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33737. this._soundPanner.panningModel = this._panningModel;
  33738. }
  33739. };
  33740. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33741. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33742. if (this._isOutputConnected) {
  33743. this._ouputAudioNode.disconnect();
  33744. }
  33745. this._ouputAudioNode.connect(soundTrackAudioNode);
  33746. this._isOutputConnected = true;
  33747. }
  33748. };
  33749. /**
  33750. * Transform this sound into a directional source
  33751. * @param coneInnerAngle Size of the inner cone in degree
  33752. * @param coneOuterAngle Size of the outer cone in degree
  33753. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33754. */
  33755. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33756. if (coneOuterAngle < coneInnerAngle) {
  33757. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33758. return;
  33759. }
  33760. this._coneInnerAngle = coneInnerAngle;
  33761. this._coneOuterAngle = coneOuterAngle;
  33762. this._coneOuterGain = coneOuterGain;
  33763. this._isDirectional = true;
  33764. if (this.isPlaying && this.loop) {
  33765. this.stop();
  33766. this.play();
  33767. }
  33768. };
  33769. Sound.prototype.setPosition = function (newPosition) {
  33770. this._position = newPosition;
  33771. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33772. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33773. }
  33774. };
  33775. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33776. this._localDirection = newLocalDirection;
  33777. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33778. this._updateDirection();
  33779. }
  33780. };
  33781. Sound.prototype._updateDirection = function () {
  33782. var mat = this._connectedMesh.getWorldMatrix();
  33783. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33784. direction.normalize();
  33785. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33786. };
  33787. Sound.prototype.updateDistanceFromListener = function () {
  33788. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33789. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33790. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33791. }
  33792. };
  33793. Sound.prototype.setAttenuationFunction = function (callback) {
  33794. this._customAttenuationFunction = callback;
  33795. };
  33796. /**
  33797. * Play the sound
  33798. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33799. */
  33800. Sound.prototype.play = function (time) {
  33801. var _this = this;
  33802. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33803. try {
  33804. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33805. if (!this._soundSource || !this._streamingSource) {
  33806. if (this.spatialSound) {
  33807. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33808. if (this._isDirectional) {
  33809. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33810. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33811. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33812. if (this._connectedMesh) {
  33813. this._updateDirection();
  33814. }
  33815. else {
  33816. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33817. }
  33818. }
  33819. }
  33820. }
  33821. if (this._streaming) {
  33822. if (!this._streamingSource) {
  33823. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33824. this._htmlAudioElement.onended = function () { _this._onended(); };
  33825. this._htmlAudioElement.playbackRate = this._playbackRate;
  33826. }
  33827. this._streamingSource.disconnect();
  33828. this._streamingSource.connect(this._inputAudioNode);
  33829. this._htmlAudioElement.play();
  33830. }
  33831. else {
  33832. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33833. this._soundSource.buffer = this._audioBuffer;
  33834. this._soundSource.connect(this._inputAudioNode);
  33835. this._soundSource.loop = this.loop;
  33836. this._soundSource.playbackRate.value = this._playbackRate;
  33837. this._soundSource.onended = function () { _this._onended(); };
  33838. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33839. }
  33840. this._startTime = startTime;
  33841. this.isPlaying = true;
  33842. this.isPaused = false;
  33843. }
  33844. catch (ex) {
  33845. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33846. }
  33847. }
  33848. };
  33849. Sound.prototype._onended = function () {
  33850. this.isPlaying = false;
  33851. if (this.onended) {
  33852. this.onended();
  33853. }
  33854. };
  33855. /**
  33856. * Stop the sound
  33857. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33858. */
  33859. Sound.prototype.stop = function (time) {
  33860. if (this.isPlaying) {
  33861. if (this._streaming) {
  33862. this._htmlAudioElement.pause();
  33863. // Test needed for Firefox or it will generate an Invalid State Error
  33864. if (this._htmlAudioElement.currentTime > 0) {
  33865. this._htmlAudioElement.currentTime = 0;
  33866. }
  33867. }
  33868. else {
  33869. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33870. this._soundSource.stop(stopTime);
  33871. }
  33872. this.isPlaying = false;
  33873. }
  33874. };
  33875. Sound.prototype.pause = function () {
  33876. if (this.isPlaying) {
  33877. if (this._streaming) {
  33878. this._htmlAudioElement.pause();
  33879. }
  33880. else {
  33881. this.stop(0);
  33882. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33883. }
  33884. this.isPaused = true;
  33885. }
  33886. };
  33887. Sound.prototype.setVolume = function (newVolume, time) {
  33888. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33889. if (time) {
  33890. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33891. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33892. }
  33893. else {
  33894. this._soundGain.gain.value = newVolume;
  33895. }
  33896. }
  33897. this._volume = newVolume;
  33898. };
  33899. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33900. this._playbackRate = newPlaybackRate;
  33901. if (this.isPlaying) {
  33902. if (this._streaming) {
  33903. this._htmlAudioElement.playbackRate = this._playbackRate;
  33904. }
  33905. else {
  33906. this._soundSource.playbackRate.value = this._playbackRate;
  33907. }
  33908. }
  33909. };
  33910. Sound.prototype.getVolume = function () {
  33911. return this._volume;
  33912. };
  33913. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33914. var _this = this;
  33915. this._connectedMesh = meshToConnectTo;
  33916. if (!this.spatialSound) {
  33917. this.spatialSound = true;
  33918. this._createSpatialParameters();
  33919. if (this.isPlaying && this.loop) {
  33920. this.stop();
  33921. this.play();
  33922. }
  33923. }
  33924. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33925. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33926. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33927. };
  33928. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33929. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33931. this._updateDirection();
  33932. }
  33933. };
  33934. return Sound;
  33935. })();
  33936. BABYLON.Sound = Sound;
  33937. })(BABYLON || (BABYLON = {}));
  33938. var BABYLON;
  33939. (function (BABYLON) {
  33940. var SoundTrack = (function () {
  33941. function SoundTrack(scene, options) {
  33942. this.id = -1;
  33943. this._isMainTrack = false;
  33944. this._isInitialized = false;
  33945. this._scene = scene;
  33946. this.soundCollection = new Array();
  33947. this._options = options;
  33948. if (!this._isMainTrack) {
  33949. this._scene.soundTracks.push(this);
  33950. this.id = this._scene.soundTracks.length - 1;
  33951. }
  33952. }
  33953. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33954. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33955. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33956. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33957. if (this._options) {
  33958. if (this._options.volume) {
  33959. this._outputAudioNode.gain.value = this._options.volume;
  33960. }
  33961. if (this._options.mainTrack) {
  33962. this._isMainTrack = this._options.mainTrack;
  33963. }
  33964. }
  33965. this._isInitialized = true;
  33966. }
  33967. };
  33968. SoundTrack.prototype.dispose = function () {
  33969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33970. if (this._connectedAnalyser) {
  33971. this._connectedAnalyser.stopDebugCanvas();
  33972. }
  33973. while (this.soundCollection.length) {
  33974. this.soundCollection[0].dispose();
  33975. }
  33976. if (this._outputAudioNode) {
  33977. this._outputAudioNode.disconnect();
  33978. }
  33979. this._outputAudioNode = null;
  33980. }
  33981. };
  33982. SoundTrack.prototype.AddSound = function (sound) {
  33983. if (!this._isInitialized) {
  33984. this._initializeSoundTrackAudioGraph();
  33985. }
  33986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33987. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33988. }
  33989. if (sound.soundTrackId) {
  33990. if (sound.soundTrackId === -1) {
  33991. this._scene.mainSoundTrack.RemoveSound(sound);
  33992. }
  33993. else {
  33994. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33995. }
  33996. }
  33997. this.soundCollection.push(sound);
  33998. sound.soundTrackId = this.id;
  33999. };
  34000. SoundTrack.prototype.RemoveSound = function (sound) {
  34001. var index = this.soundCollection.indexOf(sound);
  34002. if (index !== -1) {
  34003. this.soundCollection.splice(index, 1);
  34004. }
  34005. };
  34006. SoundTrack.prototype.setVolume = function (newVolume) {
  34007. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34008. this._outputAudioNode.gain.value = newVolume;
  34009. }
  34010. };
  34011. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34012. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34013. for (var i = 0; i < this.soundCollection.length; i++) {
  34014. this.soundCollection[i].switchPanningModelToHRTF();
  34015. }
  34016. }
  34017. };
  34018. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34019. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34020. for (var i = 0; i < this.soundCollection.length; i++) {
  34021. this.soundCollection[i].switchPanningModelToEqualPower();
  34022. }
  34023. }
  34024. };
  34025. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34026. if (this._connectedAnalyser) {
  34027. this._connectedAnalyser.stopDebugCanvas();
  34028. }
  34029. this._connectedAnalyser = analyser;
  34030. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34031. this._outputAudioNode.disconnect();
  34032. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34033. }
  34034. };
  34035. return SoundTrack;
  34036. })();
  34037. BABYLON.SoundTrack = SoundTrack;
  34038. })(BABYLON || (BABYLON = {}));
  34039. var BABYLON;
  34040. (function (BABYLON) {
  34041. var DepthRenderer = (function () {
  34042. function DepthRenderer(scene, type) {
  34043. var _this = this;
  34044. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34045. this._viewMatrix = BABYLON.Matrix.Zero();
  34046. this._projectionMatrix = BABYLON.Matrix.Zero();
  34047. this._transformMatrix = BABYLON.Matrix.Zero();
  34048. this._worldViewProjection = BABYLON.Matrix.Zero();
  34049. this._scene = scene;
  34050. var engine = scene.getEngine();
  34051. // Render target
  34052. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34053. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34054. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34055. this._depthMap.refreshRate = 1;
  34056. this._depthMap.renderParticles = false;
  34057. this._depthMap.renderList = null;
  34058. // set default depth value to 1.0 (far away)
  34059. this._depthMap.onClear = function (engine) {
  34060. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34061. };
  34062. // Custom render function
  34063. var renderSubMesh = function (subMesh) {
  34064. var mesh = subMesh.getRenderingMesh();
  34065. var scene = _this._scene;
  34066. var engine = scene.getEngine();
  34067. // Culling
  34068. engine.setState(subMesh.getMaterial().backFaceCulling);
  34069. // Managing instances
  34070. var batch = mesh._getInstancesRenderList(subMesh._id);
  34071. if (batch.mustReturn) {
  34072. return;
  34073. }
  34074. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34075. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34076. engine.enableEffect(_this._effect);
  34077. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34078. var material = subMesh.getMaterial();
  34079. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34080. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34081. // Alpha test
  34082. if (material && material.needAlphaTesting()) {
  34083. var alphaTexture = material.getAlphaTestTexture();
  34084. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34085. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34086. }
  34087. // Bones
  34088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34089. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34090. }
  34091. // Draw
  34092. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34093. }
  34094. };
  34095. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34096. var index;
  34097. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34098. renderSubMesh(opaqueSubMeshes.data[index]);
  34099. }
  34100. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34101. renderSubMesh(alphaTestSubMeshes.data[index]);
  34102. }
  34103. };
  34104. }
  34105. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34106. var defines = [];
  34107. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34108. var mesh = subMesh.getMesh();
  34109. var scene = mesh.getScene();
  34110. var material = subMesh.getMaterial();
  34111. // Alpha test
  34112. if (material && material.needAlphaTesting()) {
  34113. defines.push("#define ALPHATEST");
  34114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34115. attribs.push(BABYLON.VertexBuffer.UVKind);
  34116. defines.push("#define UV1");
  34117. }
  34118. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34119. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34120. defines.push("#define UV2");
  34121. }
  34122. }
  34123. // Bones
  34124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34127. if (mesh.numBoneInfluencers > 4) {
  34128. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34129. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34130. }
  34131. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34132. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34133. }
  34134. else {
  34135. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34136. }
  34137. // Instances
  34138. if (useInstances) {
  34139. defines.push("#define INSTANCES");
  34140. attribs.push("world0");
  34141. attribs.push("world1");
  34142. attribs.push("world2");
  34143. attribs.push("world3");
  34144. }
  34145. // Get correct effect
  34146. var join = defines.join("\n");
  34147. if (this._cachedDefines !== join) {
  34148. this._cachedDefines = join;
  34149. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34150. }
  34151. return this._effect.isReady();
  34152. };
  34153. DepthRenderer.prototype.getDepthMap = function () {
  34154. return this._depthMap;
  34155. };
  34156. // Methods
  34157. DepthRenderer.prototype.dispose = function () {
  34158. this._depthMap.dispose();
  34159. };
  34160. return DepthRenderer;
  34161. })();
  34162. BABYLON.DepthRenderer = DepthRenderer;
  34163. })(BABYLON || (BABYLON = {}));
  34164. var BABYLON;
  34165. (function (BABYLON) {
  34166. var SSAORenderingPipeline = (function (_super) {
  34167. __extends(SSAORenderingPipeline, _super);
  34168. /**
  34169. * @constructor
  34170. * @param {string} name - The rendering pipeline name
  34171. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34172. * @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 }
  34173. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34174. */
  34175. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34176. var _this = this;
  34177. _super.call(this, scene.getEngine(), name);
  34178. // Members
  34179. /**
  34180. * The PassPostProcess id in the pipeline that contains the original scene color
  34181. * @type {string}
  34182. */
  34183. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34184. /**
  34185. * The SSAO PostProcess id in the pipeline
  34186. * @type {string}
  34187. */
  34188. this.SSAORenderEffect = "SSAORenderEffect";
  34189. /**
  34190. * The horizontal blur PostProcess id in the pipeline
  34191. * @type {string}
  34192. */
  34193. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34194. /**
  34195. * The vertical blur PostProcess id in the pipeline
  34196. * @type {string}
  34197. */
  34198. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34199. /**
  34200. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34201. * @type {string}
  34202. */
  34203. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34204. /**
  34205. * The output strength of the SSAO post-process. Default value is 1.0.
  34206. * @type {number}
  34207. */
  34208. this.totalStrength = 1.0;
  34209. /**
  34210. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34211. * @type {number}
  34212. */
  34213. this.radius = 0.0001;
  34214. /**
  34215. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34216. * Must not be equal to fallOff and superior to fallOff.
  34217. * Default value is 0.975
  34218. * @type {number}
  34219. */
  34220. this.area = 0.0075;
  34221. /**
  34222. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34223. * Must not be equal to area and inferior to area.
  34224. * Default value is 0.0
  34225. * @type {number}
  34226. */
  34227. this.fallOff = 0.000001;
  34228. /**
  34229. * The base color of the SSAO post-process
  34230. * The final result is "base + ssao" between [0, 1]
  34231. * @type {number}
  34232. */
  34233. this.base = 0.5;
  34234. this._firstUpdate = true;
  34235. this._scene = scene;
  34236. // Set up assets
  34237. this._createRandomTexture();
  34238. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34239. var ssaoRatio = ratio.ssaoRatio || ratio;
  34240. var combineRatio = ratio.combineRatio || ratio;
  34241. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34242. this._createSSAOPostProcess(ssaoRatio);
  34243. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34244. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34245. this._createSSAOCombinePostProcess(combineRatio);
  34246. // Set up pipeline
  34247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34250. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34252. // Finish
  34253. scene.postProcessRenderPipelineManager.addPipeline(this);
  34254. if (cameras)
  34255. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34256. }
  34257. // Public Methods
  34258. /**
  34259. * Returns the horizontal blur PostProcess
  34260. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34261. */
  34262. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34263. return this._blurHPostProcess;
  34264. };
  34265. /**
  34266. * Returns the vertical blur PostProcess
  34267. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34268. */
  34269. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34270. return this._blurVPostProcess;
  34271. };
  34272. /**
  34273. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34274. */
  34275. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34276. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34277. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34278. this._originalColorPostProcess = undefined;
  34279. this._ssaoPostProcess = undefined;
  34280. this._blurHPostProcess = undefined;
  34281. this._blurVPostProcess = undefined;
  34282. this._ssaoCombinePostProcess = undefined;
  34283. this._randomTexture.dispose();
  34284. if (disableDepthRender)
  34285. this._scene.disableDepthRenderer();
  34286. };
  34287. // Private Methods
  34288. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34289. var _this = this;
  34290. var numSamples = 16;
  34291. var sampleSphere = [
  34292. 0.5381, 0.1856, -0.4319,
  34293. 0.1379, 0.2486, 0.4430,
  34294. 0.3371, 0.5679, -0.0057,
  34295. -0.6999, -0.0451, -0.0019,
  34296. 0.0689, -0.1598, -0.8547,
  34297. 0.0560, 0.0069, -0.1843,
  34298. -0.0146, 0.1402, 0.0762,
  34299. 0.0100, -0.1924, -0.0344,
  34300. -0.3577, -0.5301, -0.4358,
  34301. -0.3169, 0.1063, 0.0158,
  34302. 0.0103, -0.5869, 0.0046,
  34303. -0.0897, -0.4940, 0.3287,
  34304. 0.7119, -0.0154, -0.0918,
  34305. -0.0533, 0.0596, -0.5411,
  34306. 0.0352, -0.0631, 0.5460,
  34307. -0.4776, 0.2847, -0.0271
  34308. ];
  34309. var samplesFactor = 1.0 / numSamples;
  34310. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34311. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34312. "area", "fallOff", "base"
  34313. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34314. this._ssaoPostProcess.onApply = function (effect) {
  34315. if (_this._firstUpdate) {
  34316. effect.setArray3("sampleSphere", sampleSphere);
  34317. effect.setFloat("samplesFactor", samplesFactor);
  34318. effect.setFloat("randTextureTiles", 4.0);
  34319. _this._firstUpdate = false;
  34320. }
  34321. effect.setFloat("totalStrength", _this.totalStrength);
  34322. effect.setFloat("radius", _this.radius);
  34323. effect.setFloat("area", _this.area);
  34324. effect.setFloat("fallOff", _this.fallOff);
  34325. effect.setFloat("base", _this.base);
  34326. effect.setTexture("textureSampler", _this._depthTexture);
  34327. effect.setTexture("randomSampler", _this._randomTexture);
  34328. };
  34329. };
  34330. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34331. var _this = this;
  34332. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34333. this._ssaoCombinePostProcess.onApply = function (effect) {
  34334. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34335. };
  34336. };
  34337. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34338. var size = 512;
  34339. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34340. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34341. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34342. var context = this._randomTexture.getContext();
  34343. var rand = function (min, max) {
  34344. return Math.random() * (max - min) + min;
  34345. };
  34346. var randVector = BABYLON.Vector3.Zero();
  34347. for (var x = 0; x < size; x++) {
  34348. for (var y = 0; y < size; y++) {
  34349. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34350. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34351. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34352. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34353. context.fillRect(x, y, 1, 1);
  34354. }
  34355. }
  34356. this._randomTexture.update(false);
  34357. };
  34358. return SSAORenderingPipeline;
  34359. })(BABYLON.PostProcessRenderPipeline);
  34360. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34361. })(BABYLON || (BABYLON = {}));
  34362. var BABYLON;
  34363. (function (BABYLON) {
  34364. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34365. var VolumetricLightScatteringPostProcess = (function (_super) {
  34366. __extends(VolumetricLightScatteringPostProcess, _super);
  34367. /**
  34368. * @constructor
  34369. * @param {string} name - The post-process name
  34370. * @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)
  34371. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34372. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34373. * @param {number} samples - The post-process quality, default 100
  34374. * @param {number} samplingMode - The post-process filtering mode
  34375. * @param {BABYLON.Engine} engine - The babylon engine
  34376. * @param {boolean} reusable - If the post-process is reusable
  34377. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34378. */
  34379. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34380. var _this = this;
  34381. if (samples === void 0) { samples = 100; }
  34382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34383. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34384. this._screenCoordinates = BABYLON.Vector2.Zero();
  34385. /**
  34386. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34387. * @type {boolean}
  34388. */
  34389. this.useCustomMeshPosition = false;
  34390. /**
  34391. * If the post-process should inverse the light scattering direction
  34392. * @type {boolean}
  34393. */
  34394. this.invert = true;
  34395. /**
  34396. * Set to true to use the diffuseColor instead of the diffuseTexture
  34397. * @type {boolean}
  34398. */
  34399. this.useDiffuseColor = false;
  34400. /**
  34401. * Array containing the excluded meshes not rendered in the internal pass
  34402. */
  34403. this.excludedMeshes = new Array();
  34404. /**
  34405. * Controls the overall intensity of the post-process
  34406. * @type {number}
  34407. */
  34408. this.exposure = 0.3;
  34409. /**
  34410. * Dissipates each sample's contribution in range [0, 1]
  34411. * @type {number}
  34412. */
  34413. this.decay = 0.96815;
  34414. /**
  34415. * Controls the overall intensity of each sample
  34416. * @type {number}
  34417. */
  34418. this.weight = 0.58767;
  34419. /**
  34420. * Controls the density of each sample
  34421. * @type {number}
  34422. */
  34423. this.density = 0.926;
  34424. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34425. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34426. // Configure mesh
  34427. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34428. // Configure
  34429. this._createPass(scene, ratio.passRatio || ratio);
  34430. this.onActivate = function (camera) {
  34431. if (!_this.isSupported) {
  34432. _this.dispose(camera);
  34433. }
  34434. _this.onActivate = null;
  34435. };
  34436. this.onApply = function (effect) {
  34437. _this._updateMeshScreenCoordinates(scene);
  34438. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34439. effect.setFloat("exposure", _this.exposure);
  34440. effect.setFloat("decay", _this.decay);
  34441. effect.setFloat("weight", _this.weight);
  34442. effect.setFloat("density", _this.density);
  34443. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34444. };
  34445. }
  34446. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34447. var mesh = subMesh.getMesh();
  34448. var defines = [];
  34449. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34450. var material = subMesh.getMaterial();
  34451. var needUV = false;
  34452. // Render this.mesh as default
  34453. if (mesh === this.mesh) {
  34454. if (this.useDiffuseColor) {
  34455. defines.push("#define DIFFUSE_COLOR_RENDER");
  34456. }
  34457. else if (material) {
  34458. if (material.diffuseTexture !== undefined) {
  34459. defines.push("#define BASIC_RENDER");
  34460. }
  34461. else {
  34462. defines.push("#define DIFFUSE_COLOR_RENDER");
  34463. }
  34464. }
  34465. defines.push("#define NEED_UV");
  34466. needUV = true;
  34467. }
  34468. // Alpha test
  34469. if (material) {
  34470. if (material.needAlphaTesting()) {
  34471. defines.push("#define ALPHATEST");
  34472. }
  34473. if (material.opacityTexture !== undefined) {
  34474. defines.push("#define OPACITY");
  34475. if (material.opacityTexture.getAlphaFromRGB) {
  34476. defines.push("#define OPACITYRGB");
  34477. }
  34478. if (!needUV) {
  34479. defines.push("#define NEED_UV");
  34480. }
  34481. }
  34482. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34483. attribs.push(BABYLON.VertexBuffer.UVKind);
  34484. defines.push("#define UV1");
  34485. }
  34486. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34487. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34488. defines.push("#define UV2");
  34489. }
  34490. }
  34491. // Bones
  34492. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34495. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34496. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34497. }
  34498. else {
  34499. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34500. }
  34501. // Instances
  34502. if (useInstances) {
  34503. defines.push("#define INSTANCES");
  34504. attribs.push("world0");
  34505. attribs.push("world1");
  34506. attribs.push("world2");
  34507. attribs.push("world3");
  34508. }
  34509. // Get correct effect
  34510. var join = defines.join("\n");
  34511. if (this._cachedDefines !== join) {
  34512. this._cachedDefines = join;
  34513. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34514. }
  34515. return this._volumetricLightScatteringPass.isReady();
  34516. };
  34517. /**
  34518. * Sets the new light position for light scattering effect
  34519. * @param {BABYLON.Vector3} The new custom light position
  34520. */
  34521. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34522. this._customMeshPosition = position;
  34523. };
  34524. /**
  34525. * Returns the light position for light scattering effect
  34526. * @return {BABYLON.Vector3} The custom light position
  34527. */
  34528. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34529. return this._customMeshPosition;
  34530. };
  34531. /**
  34532. * Disposes the internal assets and detaches the post-process from the camera
  34533. */
  34534. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34535. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34536. if (rttIndex !== -1) {
  34537. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34538. }
  34539. this._volumetricLightScatteringRTT.dispose();
  34540. _super.prototype.dispose.call(this, camera);
  34541. };
  34542. /**
  34543. * Returns the render target texture used by the post-process
  34544. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34545. */
  34546. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34547. return this._volumetricLightScatteringRTT;
  34548. };
  34549. // Private methods
  34550. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34551. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34552. return true;
  34553. }
  34554. return false;
  34555. };
  34556. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34557. var _this = this;
  34558. var engine = scene.getEngine();
  34559. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34560. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34561. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34562. this._volumetricLightScatteringRTT.renderList = null;
  34563. this._volumetricLightScatteringRTT.renderParticles = false;
  34564. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34565. // Custom render function for submeshes
  34566. var renderSubMesh = function (subMesh) {
  34567. var mesh = subMesh.getRenderingMesh();
  34568. if (_this._meshExcluded(mesh)) {
  34569. return;
  34570. }
  34571. var scene = mesh.getScene();
  34572. var engine = scene.getEngine();
  34573. // Culling
  34574. engine.setState(subMesh.getMaterial().backFaceCulling);
  34575. // Managing instances
  34576. var batch = mesh._getInstancesRenderList(subMesh._id);
  34577. if (batch.mustReturn) {
  34578. return;
  34579. }
  34580. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34581. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34582. engine.enableEffect(_this._volumetricLightScatteringPass);
  34583. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34584. var material = subMesh.getMaterial();
  34585. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34586. // Alpha test
  34587. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34588. var alphaTexture = material.getAlphaTestTexture();
  34589. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34590. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34591. }
  34592. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34593. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34594. if (alphaTexture) {
  34595. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34596. }
  34597. }
  34598. if (material.opacityTexture !== undefined) {
  34599. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34600. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34601. }
  34602. }
  34603. // Bones
  34604. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34605. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34606. }
  34607. // Draw
  34608. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34609. }
  34610. };
  34611. // Render target texture callbacks
  34612. var savedSceneClearColor;
  34613. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34614. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34615. savedSceneClearColor = scene.clearColor;
  34616. scene.clearColor = sceneClearColor;
  34617. };
  34618. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34619. scene.clearColor = savedSceneClearColor;
  34620. };
  34621. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34622. var engine = scene.getEngine();
  34623. var index;
  34624. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34625. renderSubMesh(opaqueSubMeshes.data[index]);
  34626. }
  34627. engine.setAlphaTesting(true);
  34628. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34629. renderSubMesh(alphaTestSubMeshes.data[index]);
  34630. }
  34631. engine.setAlphaTesting(false);
  34632. if (transparentSubMeshes.length) {
  34633. // Sort sub meshes
  34634. for (index = 0; index < transparentSubMeshes.length; index++) {
  34635. var submesh = transparentSubMeshes.data[index];
  34636. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34637. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34638. }
  34639. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34640. sortedArray.sort(function (a, b) {
  34641. // Alpha index first
  34642. if (a._alphaIndex > b._alphaIndex) {
  34643. return 1;
  34644. }
  34645. if (a._alphaIndex < b._alphaIndex) {
  34646. return -1;
  34647. }
  34648. // Then distance to camera
  34649. if (a._distanceToCamera < b._distanceToCamera) {
  34650. return 1;
  34651. }
  34652. if (a._distanceToCamera > b._distanceToCamera) {
  34653. return -1;
  34654. }
  34655. return 0;
  34656. });
  34657. // Render sub meshes
  34658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34659. for (index = 0; index < sortedArray.length; index++) {
  34660. renderSubMesh(sortedArray[index]);
  34661. }
  34662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34663. }
  34664. };
  34665. };
  34666. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34667. var transform = scene.getTransformMatrix();
  34668. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34669. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34670. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34671. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34672. if (this.invert)
  34673. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34674. };
  34675. // Static methods
  34676. /**
  34677. * Creates a default mesh for the Volumeric Light Scattering post-process
  34678. * @param {string} The mesh name
  34679. * @param {BABYLON.Scene} The scene where to create the mesh
  34680. * @return {BABYLON.Mesh} the default mesh
  34681. */
  34682. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34683. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34684. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34685. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34686. return mesh;
  34687. };
  34688. return VolumetricLightScatteringPostProcess;
  34689. })(BABYLON.PostProcess);
  34690. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34691. })(BABYLON || (BABYLON = {}));
  34692. // BABYLON.JS Chromatic Aberration GLSL Shader
  34693. // Author: Olivier Guyot
  34694. // Separates very slightly R, G and B colors on the edges of the screen
  34695. // Inspired by Francois Tarlier & Martins Upitis
  34696. var BABYLON;
  34697. (function (BABYLON) {
  34698. var LensRenderingPipeline = (function (_super) {
  34699. __extends(LensRenderingPipeline, _super);
  34700. /**
  34701. * @constructor
  34702. *
  34703. * Effect parameters are as follow:
  34704. * {
  34705. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34706. * edge_blur: number; // from 0 to x (1 for realism)
  34707. * distortion: number; // from 0 to x (1 for realism)
  34708. * grain_amount: number; // from 0 to 1
  34709. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34710. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34711. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34712. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34713. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34714. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34715. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34716. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34717. * }
  34718. * Note: if an effect parameter is unset, effect is disabled
  34719. *
  34720. * @param {string} name - The rendering pipeline name
  34721. * @param {object} parameters - An object containing all parameters (see above)
  34722. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34723. * @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)
  34724. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34725. */
  34726. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34727. var _this = this;
  34728. if (ratio === void 0) { ratio = 1.0; }
  34729. _super.call(this, scene.getEngine(), name);
  34730. // Lens effects can be of the following:
  34731. // - chromatic aberration (slight shift of RGB colors)
  34732. // - blur on the edge of the lens
  34733. // - lens distortion
  34734. // - depth-of-field blur & highlights enhancing
  34735. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34736. // - grain effect (noise or custom texture)
  34737. // Two additional texture samplers are needed:
  34738. // - depth map (for depth-of-field)
  34739. // - grain texture
  34740. /**
  34741. * The chromatic aberration PostProcess id in the pipeline
  34742. * @type {string}
  34743. */
  34744. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34745. /**
  34746. * The highlights enhancing PostProcess id in the pipeline
  34747. * @type {string}
  34748. */
  34749. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34750. /**
  34751. * The depth-of-field PostProcess id in the pipeline
  34752. * @type {string}
  34753. */
  34754. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34755. this._scene = scene;
  34756. // Fetch texture samplers
  34757. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34758. if (parameters.grain_texture) {
  34759. this._grainTexture = parameters.grain_texture;
  34760. }
  34761. else {
  34762. this._createGrainTexture();
  34763. }
  34764. // save parameters
  34765. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34766. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34767. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34768. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34769. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34770. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34771. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34772. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34773. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34774. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34775. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34776. // Create effects
  34777. this._createChromaticAberrationPostProcess(ratio);
  34778. this._createHighlightsPostProcess(ratio);
  34779. this._createDepthOfFieldPostProcess(ratio / 4);
  34780. // Set up pipeline
  34781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34784. if (this._highlightsGain === -1) {
  34785. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34786. }
  34787. // Finish
  34788. scene.postProcessRenderPipelineManager.addPipeline(this);
  34789. if (cameras) {
  34790. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34791. }
  34792. }
  34793. // public methods (self explanatory)
  34794. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34795. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34796. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34797. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34798. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34799. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34800. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34801. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34802. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34803. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34804. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34805. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34806. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34807. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34808. };
  34809. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34810. this._highlightsPostProcess.updateEffect();
  34811. };
  34812. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34813. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34814. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34815. this._highlightsGain = amount;
  34816. };
  34817. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34818. if (this._highlightsGain === -1) {
  34819. this._highlightsGain = 1.0;
  34820. }
  34821. this._highlightsThreshold = amount;
  34822. };
  34823. LensRenderingPipeline.prototype.disableHighlights = function () {
  34824. this._highlightsGain = -1;
  34825. };
  34826. /**
  34827. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34828. */
  34829. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34830. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34831. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34832. this._chromaticAberrationPostProcess = undefined;
  34833. this._highlightsPostProcess = undefined;
  34834. this._depthOfFieldPostProcess = undefined;
  34835. this._grainTexture.dispose();
  34836. if (disableDepthRender)
  34837. this._scene.disableDepthRenderer();
  34838. };
  34839. // colors shifting and distortion
  34840. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34841. var _this = this;
  34842. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34843. [], // samplers
  34844. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34845. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34846. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34847. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34848. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34849. };
  34850. };
  34851. // highlights enhancing
  34852. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34853. var _this = this;
  34854. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  34855. [], // samplers
  34856. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  34857. this._highlightsPostProcess.onApply = function (effect) {
  34858. effect.setFloat('gain', _this._highlightsGain);
  34859. effect.setFloat('threshold', _this._highlightsThreshold);
  34860. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34861. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34862. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34863. };
  34864. };
  34865. // colors shifting and distortion
  34866. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34867. var _this = this;
  34868. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34869. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34870. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34871. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34872. this._depthOfFieldPostProcess.onApply = function (effect) {
  34873. effect.setTexture("depthSampler", _this._depthTexture);
  34874. effect.setTexture("grainSampler", _this._grainTexture);
  34875. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34876. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34877. effect.setFloat('grain_amount', _this._grainAmount);
  34878. effect.setBool('blur_noise', _this._blurNoise);
  34879. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34880. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34881. effect.setFloat('distortion', _this._distortion);
  34882. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  34883. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34884. effect.setFloat('aperture', _this._dofAperture);
  34885. effect.setFloat('darken', _this._dofDarken);
  34886. effect.setFloat('edge_blur', _this._edgeBlur);
  34887. effect.setBool('highlights', (_this._highlightsGain !== -1));
  34888. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34889. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34890. };
  34891. };
  34892. // creates a black and white random noise texture, 512x512
  34893. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34894. var size = 512;
  34895. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34896. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34897. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34898. var context = this._grainTexture.getContext();
  34899. var rand = function (min, max) {
  34900. return Math.random() * (max - min) + min;
  34901. };
  34902. var value;
  34903. for (var x = 0; x < size; x++) {
  34904. for (var y = 0; y < size; y++) {
  34905. value = Math.floor(rand(0.42, 0.58) * 255);
  34906. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34907. context.fillRect(x, y, 1, 1);
  34908. }
  34909. }
  34910. this._grainTexture.update(false);
  34911. };
  34912. return LensRenderingPipeline;
  34913. })(BABYLON.PostProcessRenderPipeline);
  34914. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34915. })(BABYLON || (BABYLON = {}));
  34916. //
  34917. // This post-process allows the modification of rendered colors by using
  34918. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34919. //
  34920. // The object needs to be provided an url to a texture containing the color
  34921. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34922. // Use an image editing software to tweak the LUT to match your needs.
  34923. //
  34924. // For an example of a color LUT, see here:
  34925. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34926. // For explanations on color grading, see here:
  34927. // http://udn.epicgames.com/Three/ColorGrading.html
  34928. //
  34929. var BABYLON;
  34930. (function (BABYLON) {
  34931. var ColorCorrectionPostProcess = (function (_super) {
  34932. __extends(ColorCorrectionPostProcess, _super);
  34933. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34934. var _this = this;
  34935. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34936. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34937. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34938. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34939. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34940. this.onApply = function (effect) {
  34941. effect.setTexture("colorTable", _this._colorTableTexture);
  34942. };
  34943. }
  34944. return ColorCorrectionPostProcess;
  34945. })(BABYLON.PostProcess);
  34946. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34947. })(BABYLON || (BABYLON = {}));
  34948. var BABYLON;
  34949. (function (BABYLON) {
  34950. var AnaglyphFreeCamera = (function (_super) {
  34951. __extends(AnaglyphFreeCamera, _super);
  34952. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34953. _super.call(this, name, position, scene);
  34954. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34955. }
  34956. return AnaglyphFreeCamera;
  34957. })(BABYLON.FreeCamera);
  34958. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34959. var AnaglyphArcRotateCamera = (function (_super) {
  34960. __extends(AnaglyphArcRotateCamera, _super);
  34961. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34962. _super.call(this, name, alpha, beta, radius, target, scene);
  34963. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34964. }
  34965. return AnaglyphArcRotateCamera;
  34966. })(BABYLON.ArcRotateCamera);
  34967. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34968. var AnaglyphGamepadCamera = (function (_super) {
  34969. __extends(AnaglyphGamepadCamera, _super);
  34970. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34971. _super.call(this, name, position, scene);
  34972. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34973. }
  34974. return AnaglyphGamepadCamera;
  34975. })(BABYLON.GamepadCamera);
  34976. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34977. var StereoscopicFreeCamera = (function (_super) {
  34978. __extends(StereoscopicFreeCamera, _super);
  34979. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34980. _super.call(this, name, position, scene);
  34981. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34982. }
  34983. return StereoscopicFreeCamera;
  34984. })(BABYLON.FreeCamera);
  34985. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34986. var StereoscopicArcRotateCamera = (function (_super) {
  34987. __extends(StereoscopicArcRotateCamera, _super);
  34988. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34989. _super.call(this, name, alpha, beta, radius, target, scene);
  34990. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34991. }
  34992. return StereoscopicArcRotateCamera;
  34993. })(BABYLON.ArcRotateCamera);
  34994. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34995. var StereoscopicGamepadCamera = (function (_super) {
  34996. __extends(StereoscopicGamepadCamera, _super);
  34997. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34998. _super.call(this, name, position, scene);
  34999. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35000. }
  35001. return StereoscopicGamepadCamera;
  35002. })(BABYLON.GamepadCamera);
  35003. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35004. })(BABYLON || (BABYLON = {}));
  35005. var BABYLON;
  35006. (function (BABYLON) {
  35007. var HDRRenderingPipeline = (function (_super) {
  35008. __extends(HDRRenderingPipeline, _super);
  35009. /**
  35010. * @constructor
  35011. * @param {string} name - The rendering pipeline name
  35012. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35013. * @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)
  35014. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35015. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35016. */
  35017. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35018. var _this = this;
  35019. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35020. _super.call(this, scene.getEngine(), name);
  35021. /**
  35022. * Public members
  35023. */
  35024. // Gaussian Blur
  35025. /**
  35026. * Gaussian blur coefficient
  35027. * @type {number}
  35028. */
  35029. this.gaussCoeff = 0.3;
  35030. /**
  35031. * Gaussian blur mean
  35032. * @type {number}
  35033. */
  35034. this.gaussMean = 1.0;
  35035. /**
  35036. * Gaussian blur standard deviation
  35037. * @type {number}
  35038. */
  35039. this.gaussStandDev = 0.8;
  35040. /**
  35041. * Gaussian blur multiplier. Multiplies the blur effect
  35042. * @type {number}
  35043. */
  35044. this.gaussMultiplier = 4.0;
  35045. // HDR
  35046. /**
  35047. * Exposure, controls the overall intensity of the pipeline
  35048. * @type {number}
  35049. */
  35050. this.exposure = 1.0;
  35051. /**
  35052. * Minimum luminance that the post-process can output. Luminance is >= 0
  35053. * @type {number}
  35054. */
  35055. this.minimumLuminance = 1.0;
  35056. /**
  35057. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35058. * @type {number}
  35059. */
  35060. this.maximumLuminance = 1e20;
  35061. /**
  35062. * Increase rate for luminance: eye adaptation speed to dark
  35063. * @type {number}
  35064. */
  35065. this.luminanceIncreaserate = 0.5;
  35066. /**
  35067. * Decrease rate for luminance: eye adaptation speed to bright
  35068. * @type {number}
  35069. */
  35070. this.luminanceDecreaseRate = 0.5;
  35071. // Bright pass
  35072. /**
  35073. * Minimum luminance needed to compute HDR
  35074. * @type {number}
  35075. */
  35076. this.brightThreshold = 0.8;
  35077. this._needUpdate = true;
  35078. this._scene = scene;
  35079. // Bright pass
  35080. this._createBrightPassPostProcess(scene, ratio);
  35081. // Down sample X4
  35082. this._createDownSampleX4PostProcess(scene, ratio);
  35083. // Create gaussian blur post-processes
  35084. this._createGaussianBlurPostProcess(scene, ratio);
  35085. // Texture adder
  35086. this._createTextureAdderPostProcess(scene, ratio);
  35087. // Luminance generator
  35088. this._createLuminanceGeneratorPostProcess(scene);
  35089. // HDR
  35090. this._createHDRPostProcess(scene, ratio);
  35091. // Pass postprocess
  35092. if (originalPostProcess === null) {
  35093. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35094. }
  35095. else {
  35096. this._originalPostProcess = originalPostProcess;
  35097. }
  35098. // Configure pipeline
  35099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35103. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35104. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35105. var addDownSamplerPostProcess = function (id) {
  35106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35107. };
  35108. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35109. addDownSamplerPostProcess(i);
  35110. }
  35111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35112. // Finish
  35113. scene.postProcessRenderPipelineManager.addPipeline(this);
  35114. if (cameras !== null) {
  35115. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35116. }
  35117. this.update();
  35118. }
  35119. /**
  35120. * Tells the pipeline to update its post-processes
  35121. */
  35122. HDRRenderingPipeline.prototype.update = function () {
  35123. this._needUpdate = true;
  35124. };
  35125. /**
  35126. * Returns the current calculated luminance
  35127. */
  35128. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35129. return this._hdrCurrentLuminance;
  35130. };
  35131. /**
  35132. * Returns the currently drawn luminance
  35133. */
  35134. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35135. return this._hdrOutputLuminance;
  35136. };
  35137. /**
  35138. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35139. */
  35140. HDRRenderingPipeline.prototype.dispose = function () {
  35141. this._originalPostProcess = undefined;
  35142. this._brightPassPostProcess = undefined;
  35143. this._downSampleX4PostProcess = undefined;
  35144. this._guassianBlurHPostProcess = undefined;
  35145. this._guassianBlurVPostProcess = undefined;
  35146. this._textureAdderPostProcess = undefined;
  35147. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35148. this._downSamplePostProcesses[i] = undefined;
  35149. }
  35150. this._hdrPostProcess = undefined;
  35151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35152. };
  35153. /**
  35154. * Creates the HDR post-process and computes the luminance adaptation
  35155. */
  35156. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35157. var _this = this;
  35158. var hdrLastLuminance = 0.0;
  35159. this._hdrOutputLuminance = -1.0;
  35160. this._hdrCurrentLuminance = 1.0;
  35161. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35162. this._hdrPostProcess.onApply = function (effect) {
  35163. if (_this._hdrOutputLuminance < 0.0) {
  35164. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35165. }
  35166. else {
  35167. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35168. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35169. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35170. }
  35171. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35172. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35173. }
  35174. else {
  35175. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35176. }
  35177. }
  35178. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35179. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35180. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35181. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35182. effect.setFloat("exposure", _this.exposure);
  35183. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35184. _this._needUpdate = false;
  35185. };
  35186. };
  35187. /**
  35188. * Texture Adder post-process
  35189. */
  35190. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35191. var _this = this;
  35192. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35193. this._textureAdderPostProcess.onApply = function (effect) {
  35194. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35195. };
  35196. };
  35197. /**
  35198. * Down sample X4 post-process
  35199. */
  35200. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35201. var _this = this;
  35202. var downSampleX4Offsets = new Array(32);
  35203. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35204. this._downSampleX4PostProcess.onApply = function (effect) {
  35205. if (_this._needUpdate) {
  35206. var id = 0;
  35207. for (var i = -2; i < 2; i++) {
  35208. for (var j = -2; j < 2; j++) {
  35209. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35210. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35211. id += 2;
  35212. }
  35213. }
  35214. }
  35215. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35216. };
  35217. };
  35218. /**
  35219. * Bright pass post-process
  35220. */
  35221. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35222. var _this = this;
  35223. var brightOffsets = new Array(8);
  35224. var brightPassCallback = function (effect) {
  35225. if (_this._needUpdate) {
  35226. var sU = (1.0 / _this._brightPassPostProcess.width);
  35227. var sV = (1.0 / _this._brightPassPostProcess.height);
  35228. brightOffsets[0] = -0.5 * sU;
  35229. brightOffsets[1] = 0.5 * sV;
  35230. brightOffsets[2] = 0.5 * sU;
  35231. brightOffsets[3] = 0.5 * sV;
  35232. brightOffsets[4] = -0.5 * sU;
  35233. brightOffsets[5] = -0.5 * sV;
  35234. brightOffsets[6] = 0.5 * sU;
  35235. brightOffsets[7] = -0.5 * sV;
  35236. }
  35237. effect.setArray2("dsOffsets", brightOffsets);
  35238. effect.setFloat("brightThreshold", _this.brightThreshold);
  35239. };
  35240. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35241. this._brightPassPostProcess.onApply = brightPassCallback;
  35242. };
  35243. /**
  35244. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35245. */
  35246. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35247. var _this = this;
  35248. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35249. var luminanceOffsets = new Array(8);
  35250. var downSampleOffsets = new Array(18);
  35251. var halfDestPixelSize;
  35252. this._downSamplePostProcesses = new Array(lumSteps);
  35253. // Utils for luminance
  35254. var luminanceUpdateSourceOffsets = function (width, height) {
  35255. var sU = (1.0 / width);
  35256. var sV = (1.0 / height);
  35257. luminanceOffsets[0] = -0.5 * sU;
  35258. luminanceOffsets[1] = 0.5 * sV;
  35259. luminanceOffsets[2] = 0.5 * sU;
  35260. luminanceOffsets[3] = 0.5 * sV;
  35261. luminanceOffsets[4] = -0.5 * sU;
  35262. luminanceOffsets[5] = -0.5 * sV;
  35263. luminanceOffsets[6] = 0.5 * sU;
  35264. luminanceOffsets[7] = -0.5 * sV;
  35265. };
  35266. var luminanceUpdateDestOffsets = function (width, height) {
  35267. var id = 0;
  35268. for (var x = -1; x < 2; x++) {
  35269. for (var y = -1; y < 2; y++) {
  35270. downSampleOffsets[id] = (x) / width;
  35271. downSampleOffsets[id + 1] = (y) / height;
  35272. id += 2;
  35273. }
  35274. }
  35275. };
  35276. // Luminance callback
  35277. var luminanceCallback = function (effect) {
  35278. if (_this._needUpdate) {
  35279. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35280. }
  35281. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35282. effect.setArray2("lumOffsets", luminanceOffsets);
  35283. };
  35284. // Down sample callbacks
  35285. var downSampleCallback = function (indice) {
  35286. var i = indice;
  35287. return function (effect) {
  35288. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35289. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35290. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35291. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35292. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35293. effect.setArray2("dsOffsets", downSampleOffsets);
  35294. };
  35295. };
  35296. var downSampleAfterRenderCallback = function (effect) {
  35297. // Unpack result
  35298. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35299. 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);
  35300. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35301. };
  35302. // Create luminance post-process
  35303. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35304. 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);
  35305. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35306. // Create down sample post-processes
  35307. for (var i = lumSteps - 2; i >= 0; i--) {
  35308. var length = Math.pow(3, i);
  35309. ratio = { width: length, height: length };
  35310. var defines = "#define DOWN_SAMPLE\n";
  35311. if (i === 0) {
  35312. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35313. }
  35314. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35315. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35316. if (i === 0) {
  35317. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35318. }
  35319. }
  35320. };
  35321. /**
  35322. * Gaussian blur post-processes. Horizontal and Vertical
  35323. */
  35324. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35325. var _this = this;
  35326. var blurOffsetsW = new Array(9);
  35327. var blurOffsetsH = new Array(9);
  35328. var blurWeights = new Array(9);
  35329. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35330. // Utils for gaussian blur
  35331. var calculateBlurOffsets = function (height) {
  35332. var lastOutputDimensions = {
  35333. width: scene.getEngine().getRenderWidth(),
  35334. height: scene.getEngine().getRenderHeight()
  35335. };
  35336. for (var i = 0; i < 9; i++) {
  35337. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35338. if (height) {
  35339. blurOffsetsH[i] = value;
  35340. }
  35341. else {
  35342. blurOffsetsW[i] = value;
  35343. }
  35344. }
  35345. };
  35346. var calculateWeights = function () {
  35347. var x = 0.0;
  35348. for (var i = 0; i < 9; i++) {
  35349. x = (i - 4.0) / 4.0;
  35350. 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));
  35351. }
  35352. };
  35353. // Callback
  35354. var gaussianBlurCallback = function (height) {
  35355. return function (effect) {
  35356. if (_this._needUpdate) {
  35357. calculateWeights();
  35358. calculateBlurOffsets(height);
  35359. }
  35360. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35361. effect.setArray("blurWeights", blurWeights);
  35362. effect.setFloat("multiplier", _this.gaussMultiplier);
  35363. };
  35364. };
  35365. // Create horizontal gaussian blur post-processes
  35366. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35367. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35368. // Create vertical gaussian blur post-process
  35369. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35370. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35371. };
  35372. // Luminance generator
  35373. HDRRenderingPipeline.LUM_STEPS = 6;
  35374. return HDRRenderingPipeline;
  35375. })(BABYLON.PostProcessRenderPipeline);
  35376. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35377. })(BABYLON || (BABYLON = {}));
  35378. var BABYLON;
  35379. (function (BABYLON) {
  35380. var FaceAdjacencies = (function () {
  35381. function FaceAdjacencies() {
  35382. this.edges = new Array();
  35383. this.edgesConnectedCount = 0;
  35384. }
  35385. return FaceAdjacencies;
  35386. })();
  35387. var EdgesRenderer = (function () {
  35388. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35389. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35390. if (epsilon === void 0) { epsilon = 0.95; }
  35391. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35392. this._linesPositions = new Array();
  35393. this._linesNormals = new Array();
  35394. this._linesIndices = new Array();
  35395. this._buffers = new Array();
  35396. this._checkVerticesInsteadOfIndices = false;
  35397. this._source = source;
  35398. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35399. this._epsilon = epsilon;
  35400. this._prepareRessources();
  35401. this._generateEdgesLines();
  35402. }
  35403. EdgesRenderer.prototype._prepareRessources = function () {
  35404. if (this._lineShader) {
  35405. return;
  35406. }
  35407. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35408. attributes: ["position", "normal"],
  35409. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35410. });
  35411. this._lineShader.disableDepthWrite = true;
  35412. this._lineShader.backFaceCulling = false;
  35413. };
  35414. EdgesRenderer.prototype.dispose = function () {
  35415. this._vb0.dispose();
  35416. this._vb1.dispose();
  35417. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35418. this._lineShader.dispose();
  35419. };
  35420. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35421. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35422. return 0;
  35423. }
  35424. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35425. return 1;
  35426. }
  35427. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35428. return 2;
  35429. }
  35430. return -1;
  35431. };
  35432. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35433. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35434. return 0;
  35435. }
  35436. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35437. return 1;
  35438. }
  35439. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35440. return 2;
  35441. }
  35442. return -1;
  35443. };
  35444. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35445. var needToCreateLine;
  35446. if (edge === undefined) {
  35447. needToCreateLine = true;
  35448. }
  35449. else {
  35450. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35451. needToCreateLine = dotProduct < this._epsilon;
  35452. }
  35453. if (needToCreateLine) {
  35454. var offset = this._linesPositions.length / 3;
  35455. var normal = p0.subtract(p1);
  35456. normal.normalize();
  35457. // Positions
  35458. this._linesPositions.push(p0.x);
  35459. this._linesPositions.push(p0.y);
  35460. this._linesPositions.push(p0.z);
  35461. this._linesPositions.push(p0.x);
  35462. this._linesPositions.push(p0.y);
  35463. this._linesPositions.push(p0.z);
  35464. this._linesPositions.push(p1.x);
  35465. this._linesPositions.push(p1.y);
  35466. this._linesPositions.push(p1.z);
  35467. this._linesPositions.push(p1.x);
  35468. this._linesPositions.push(p1.y);
  35469. this._linesPositions.push(p1.z);
  35470. // Normals
  35471. this._linesNormals.push(p1.x);
  35472. this._linesNormals.push(p1.y);
  35473. this._linesNormals.push(p1.z);
  35474. this._linesNormals.push(-1);
  35475. this._linesNormals.push(p1.x);
  35476. this._linesNormals.push(p1.y);
  35477. this._linesNormals.push(p1.z);
  35478. this._linesNormals.push(1);
  35479. this._linesNormals.push(p0.x);
  35480. this._linesNormals.push(p0.y);
  35481. this._linesNormals.push(p0.z);
  35482. this._linesNormals.push(-1);
  35483. this._linesNormals.push(p0.x);
  35484. this._linesNormals.push(p0.y);
  35485. this._linesNormals.push(p0.z);
  35486. this._linesNormals.push(1);
  35487. // Indices
  35488. this._linesIndices.push(offset);
  35489. this._linesIndices.push(offset + 1);
  35490. this._linesIndices.push(offset + 2);
  35491. this._linesIndices.push(offset);
  35492. this._linesIndices.push(offset + 2);
  35493. this._linesIndices.push(offset + 3);
  35494. }
  35495. };
  35496. EdgesRenderer.prototype._generateEdgesLines = function () {
  35497. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35498. var indices = this._source.getIndices();
  35499. // First let's find adjacencies
  35500. var adjacencies = new Array();
  35501. var faceNormals = new Array();
  35502. var index;
  35503. var faceAdjacencies;
  35504. // Prepare faces
  35505. for (index = 0; index < indices.length; index += 3) {
  35506. faceAdjacencies = new FaceAdjacencies();
  35507. var p0Index = indices[index];
  35508. var p1Index = indices[index + 1];
  35509. var p2Index = indices[index + 2];
  35510. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35511. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35512. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35513. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35514. faceNormal.normalize();
  35515. faceNormals.push(faceNormal);
  35516. adjacencies.push(faceAdjacencies);
  35517. }
  35518. // Scan
  35519. for (index = 0; index < adjacencies.length; index++) {
  35520. faceAdjacencies = adjacencies[index];
  35521. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35522. var otherFaceAdjacencies = adjacencies[otherIndex];
  35523. if (faceAdjacencies.edgesConnectedCount === 3) {
  35524. break;
  35525. }
  35526. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35527. continue;
  35528. }
  35529. var otherP0 = indices[otherIndex * 3];
  35530. var otherP1 = indices[otherIndex * 3 + 1];
  35531. var otherP2 = indices[otherIndex * 3 + 2];
  35532. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35533. var otherEdgeIndex;
  35534. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35535. continue;
  35536. }
  35537. switch (edgeIndex) {
  35538. case 0:
  35539. if (this._checkVerticesInsteadOfIndices) {
  35540. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35541. }
  35542. else {
  35543. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35544. }
  35545. break;
  35546. case 1:
  35547. if (this._checkVerticesInsteadOfIndices) {
  35548. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35549. }
  35550. else {
  35551. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35552. }
  35553. break;
  35554. case 2:
  35555. if (this._checkVerticesInsteadOfIndices) {
  35556. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35557. }
  35558. else {
  35559. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35560. }
  35561. break;
  35562. }
  35563. if (otherEdgeIndex === -1) {
  35564. continue;
  35565. }
  35566. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35567. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35568. faceAdjacencies.edgesConnectedCount++;
  35569. otherFaceAdjacencies.edgesConnectedCount++;
  35570. if (faceAdjacencies.edgesConnectedCount === 3) {
  35571. break;
  35572. }
  35573. }
  35574. }
  35575. }
  35576. // Create lines
  35577. for (index = 0; index < adjacencies.length; index++) {
  35578. // 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
  35579. var current = adjacencies[index];
  35580. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35581. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35582. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35583. }
  35584. // Merge into a single mesh
  35585. var engine = this._source.getScene().getEngine();
  35586. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35587. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35588. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35589. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35590. this._ib = engine.createIndexBuffer(this._linesIndices);
  35591. this._indicesCount = this._linesIndices.length;
  35592. };
  35593. EdgesRenderer.prototype.render = function () {
  35594. if (!this._lineShader.isReady()) {
  35595. return;
  35596. }
  35597. var scene = this._source.getScene();
  35598. var engine = scene.getEngine();
  35599. this._lineShader._preBind();
  35600. // VBOs
  35601. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35602. scene.resetCachedMaterial();
  35603. this._lineShader.setColor4("color", this._source.edgesColor);
  35604. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35605. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35606. this._lineShader.bind(this._source.getWorldMatrix());
  35607. // Draw order
  35608. engine.draw(true, 0, this._indicesCount);
  35609. this._lineShader.unbind();
  35610. engine.setDepthWrite(true);
  35611. };
  35612. return EdgesRenderer;
  35613. })();
  35614. BABYLON.EdgesRenderer = EdgesRenderer;
  35615. })(BABYLON || (BABYLON = {}));
  35616. var BABYLON;
  35617. (function (BABYLON) {
  35618. (function (TonemappingOperator) {
  35619. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35620. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35621. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35622. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35623. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35624. var TonemappingOperator = BABYLON.TonemappingOperator;
  35625. ;
  35626. var TonemapPostProcess = (function (_super) {
  35627. __extends(TonemapPostProcess, _super);
  35628. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35629. var _this = this;
  35630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35631. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35632. this._operator = operator;
  35633. this._exposureAdjustment = exposureAdjustment;
  35634. var params = ["_ExposureAdjustment"];
  35635. var defines = "#define ";
  35636. if (operator === TonemappingOperator.Hable)
  35637. defines += "HABLE_TONEMAPPING";
  35638. else if (operator === TonemappingOperator.Reinhard)
  35639. defines += "REINHARD_TONEMAPPING";
  35640. else if (operator === TonemappingOperator.HejiDawson)
  35641. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35642. else if (operator === TonemappingOperator.Photographic)
  35643. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35644. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35645. this.onApply = function (effect) {
  35646. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35647. };
  35648. }
  35649. return TonemapPostProcess;
  35650. })(BABYLON.PostProcess);
  35651. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35652. })(BABYLON || (BABYLON = {}));
  35653. var BABYLON;
  35654. (function (BABYLON) {
  35655. var ReflectionProbe = (function () {
  35656. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35657. var _this = this;
  35658. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35659. this.name = name;
  35660. this._viewMatrix = BABYLON.Matrix.Identity();
  35661. this._target = BABYLON.Vector3.Zero();
  35662. this._add = BABYLON.Vector3.Zero();
  35663. this.position = BABYLON.Vector3.Zero();
  35664. this._scene = scene;
  35665. this._scene.reflectionProbes.push(this);
  35666. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35667. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35668. switch (faceIndex) {
  35669. case 0:
  35670. _this._add.copyFromFloats(1, 0, 0);
  35671. break;
  35672. case 1:
  35673. _this._add.copyFromFloats(-1, 0, 0);
  35674. break;
  35675. case 2:
  35676. _this._add.copyFromFloats(0, -1, 0);
  35677. break;
  35678. case 3:
  35679. _this._add.copyFromFloats(0, 1, 0);
  35680. break;
  35681. case 4:
  35682. _this._add.copyFromFloats(0, 0, 1);
  35683. break;
  35684. case 5:
  35685. _this._add.copyFromFloats(0, 0, -1);
  35686. break;
  35687. }
  35688. if (_this._attachedMesh) {
  35689. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35690. }
  35691. _this.position.addToRef(_this._add, _this._target);
  35692. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35693. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35694. };
  35695. this._renderTargetTexture.onAfterUnbind = function () {
  35696. scene.updateTransformMatrix(true);
  35697. };
  35698. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35699. }
  35700. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35701. get: function () {
  35702. return this._renderTargetTexture.refreshRate;
  35703. },
  35704. set: function (value) {
  35705. this._renderTargetTexture.refreshRate = value;
  35706. },
  35707. enumerable: true,
  35708. configurable: true
  35709. });
  35710. ReflectionProbe.prototype.getScene = function () {
  35711. return this._scene;
  35712. };
  35713. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35714. get: function () {
  35715. return this._renderTargetTexture;
  35716. },
  35717. enumerable: true,
  35718. configurable: true
  35719. });
  35720. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35721. get: function () {
  35722. return this._renderTargetTexture.renderList;
  35723. },
  35724. enumerable: true,
  35725. configurable: true
  35726. });
  35727. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35728. this._attachedMesh = mesh;
  35729. };
  35730. ReflectionProbe.prototype.dispose = function () {
  35731. var index = this._scene.reflectionProbes.indexOf(this);
  35732. if (index !== -1) {
  35733. // Remove from the scene if found
  35734. this._scene.reflectionProbes.splice(index, 1);
  35735. }
  35736. };
  35737. return ReflectionProbe;
  35738. })();
  35739. BABYLON.ReflectionProbe = ReflectionProbe;
  35740. })(BABYLON || (BABYLON = {}));
  35741. var BABYLON;
  35742. (function (BABYLON) {
  35743. var SolidParticle = (function () {
  35744. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35745. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35746. this.position = BABYLON.Vector3.Zero(); // position
  35747. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35748. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35749. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35750. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35751. this.alive = true; // alive
  35752. this.idx = particleIndex;
  35753. this._pos = positionIndex;
  35754. this._model = model;
  35755. this.shapeId = shapeId;
  35756. this.idxInShape = idxInShape;
  35757. }
  35758. return SolidParticle;
  35759. })();
  35760. BABYLON.SolidParticle = SolidParticle;
  35761. var ModelShape = (function () {
  35762. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35763. this.shapeID = id;
  35764. this._shape = shape;
  35765. this._shapeUV = shapeUV;
  35766. this._positionFunction = posFunction;
  35767. this._vertexFunction = vtxFunction;
  35768. }
  35769. return ModelShape;
  35770. })();
  35771. BABYLON.ModelShape = ModelShape;
  35772. })(BABYLON || (BABYLON = {}));
  35773. var BABYLON;
  35774. (function (BABYLON) {
  35775. var SolidParticleSystem = (function () {
  35776. function SolidParticleSystem(name, scene, options) {
  35777. // public members
  35778. this.particles = new Array();
  35779. this.nbParticles = 0;
  35780. this.billboard = false;
  35781. this.counter = 0;
  35782. this.vars = {};
  35783. this._positions = new Array();
  35784. this._indices = new Array();
  35785. this._normals = new Array();
  35786. this._colors = new Array();
  35787. this._uvs = new Array();
  35788. this._index = 0; // indices index
  35789. this._updatable = true;
  35790. this._pickable = false;
  35791. this._alwaysVisible = false;
  35792. this._shapeCounter = 0;
  35793. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35794. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35795. this._computeParticleColor = true;
  35796. this._computeParticleTexture = true;
  35797. this._computeParticleRotation = true;
  35798. this._computeParticleVertex = false;
  35799. this._cam_axisZ = BABYLON.Vector3.Zero();
  35800. this._cam_axisY = BABYLON.Vector3.Zero();
  35801. this._cam_axisX = BABYLON.Vector3.Zero();
  35802. this._axisX = BABYLON.Axis.X;
  35803. this._axisY = BABYLON.Axis.Y;
  35804. this._axisZ = BABYLON.Axis.Z;
  35805. this._fakeCamPos = BABYLON.Vector3.Zero();
  35806. this._rotMatrix = new BABYLON.Matrix();
  35807. this._invertMatrix = new BABYLON.Matrix();
  35808. this._rotated = BABYLON.Vector3.Zero();
  35809. this._quaternion = new BABYLON.Quaternion();
  35810. this._vertex = BABYLON.Vector3.Zero();
  35811. this._normal = BABYLON.Vector3.Zero();
  35812. this._yaw = 0.0;
  35813. this._pitch = 0.0;
  35814. this._roll = 0.0;
  35815. this._halfroll = 0.0;
  35816. this._halfpitch = 0.0;
  35817. this._halfyaw = 0.0;
  35818. this._sinRoll = 0.0;
  35819. this._cosRoll = 0.0;
  35820. this._sinPitch = 0.0;
  35821. this._cosPitch = 0.0;
  35822. this._sinYaw = 0.0;
  35823. this._cosYaw = 0.0;
  35824. this._w = 0.0;
  35825. this.name = name;
  35826. this._scene = scene;
  35827. this._camera = scene.activeCamera;
  35828. this._pickable = options ? options.isPickable : false;
  35829. if (options && options.updatable) {
  35830. this._updatable = options.updatable;
  35831. }
  35832. else {
  35833. this._updatable = true;
  35834. }
  35835. if (this._pickable) {
  35836. this.pickedParticles = [];
  35837. }
  35838. }
  35839. // build the SPS mesh : returns the mesh
  35840. SolidParticleSystem.prototype.buildMesh = function () {
  35841. if (this.nbParticles === 0) {
  35842. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35843. this.addShape(triangle, 1);
  35844. triangle.dispose();
  35845. }
  35846. this._positions32 = new Float32Array(this._positions);
  35847. this._uvs32 = new Float32Array(this._uvs);
  35848. this._colors32 = new Float32Array(this._colors);
  35849. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35850. this._normals32 = new Float32Array(this._normals);
  35851. this._fixedNormal32 = new Float32Array(this._normals);
  35852. var vertexData = new BABYLON.VertexData();
  35853. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35854. vertexData.indices = this._indices;
  35855. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35856. if (this._uvs32) {
  35857. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35858. ;
  35859. }
  35860. if (this._colors32) {
  35861. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35862. }
  35863. var mesh = new BABYLON.Mesh(name, this._scene);
  35864. vertexData.applyToMesh(mesh, this._updatable);
  35865. this.mesh = mesh;
  35866. this.mesh.isPickable = this._pickable;
  35867. // free memory
  35868. this._positions = null;
  35869. this._normals = null;
  35870. this._uvs = null;
  35871. this._colors = null;
  35872. if (!this._updatable) {
  35873. this.particles.length = 0;
  35874. }
  35875. return mesh;
  35876. };
  35877. //reset copy
  35878. SolidParticleSystem.prototype._resetCopy = function () {
  35879. this._copy.position.x = 0;
  35880. this._copy.position.y = 0;
  35881. this._copy.position.z = 0;
  35882. this._copy.rotation.x = 0;
  35883. this._copy.rotation.y = 0;
  35884. this._copy.rotation.z = 0;
  35885. this._copy.quaternion = null;
  35886. this._copy.scale.x = 1;
  35887. this._copy.scale.y = 1;
  35888. this._copy.scale.z = 1;
  35889. this._copy.uvs.x = 0;
  35890. this._copy.uvs.y = 0;
  35891. this._copy.uvs.z = 1;
  35892. this._copy.uvs.w = 1;
  35893. this._copy.color = null;
  35894. };
  35895. // _meshBuilder : inserts the shape model in the global SPS mesh
  35896. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35897. var i;
  35898. var u = 0;
  35899. var c = 0;
  35900. this._resetCopy();
  35901. if (options && options.positionFunction) {
  35902. options.positionFunction(this._copy, idx, idxInShape);
  35903. }
  35904. if (this._copy.quaternion) {
  35905. this._quaternion.x = this._copy.quaternion.x;
  35906. this._quaternion.y = this._copy.quaternion.y;
  35907. this._quaternion.z = this._copy.quaternion.z;
  35908. this._quaternion.w = this._copy.quaternion.w;
  35909. }
  35910. else {
  35911. this._yaw = this._copy.rotation.y;
  35912. this._pitch = this._copy.rotation.x;
  35913. this._roll = this._copy.rotation.z;
  35914. this._quaternionRotationYPR();
  35915. }
  35916. this._quaternionToRotationMatrix();
  35917. for (i = 0; i < shape.length; i++) {
  35918. this._vertex.x = shape[i].x;
  35919. this._vertex.y = shape[i].y;
  35920. this._vertex.z = shape[i].z;
  35921. if (options && options.vertexFunction) {
  35922. options.vertexFunction(this._copy, this._vertex, i);
  35923. }
  35924. this._vertex.x *= this._copy.scale.x;
  35925. this._vertex.y *= this._copy.scale.y;
  35926. this._vertex.z *= this._copy.scale.z;
  35927. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35928. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35929. if (meshUV) {
  35930. 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);
  35931. u += 2;
  35932. }
  35933. if (this._copy.color) {
  35934. this._color = this._copy.color;
  35935. }
  35936. else if (meshCol && meshCol[c]) {
  35937. this._color.r = meshCol[c];
  35938. this._color.g = meshCol[c + 1];
  35939. this._color.b = meshCol[c + 2];
  35940. this._color.a = meshCol[c + 3];
  35941. }
  35942. else {
  35943. this._color.r = 1;
  35944. this._color.g = 1;
  35945. this._color.b = 1;
  35946. this._color.a = 1;
  35947. }
  35948. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35949. c += 4;
  35950. }
  35951. for (i = 0; i < meshInd.length; i++) {
  35952. indices.push(p + meshInd[i]);
  35953. }
  35954. if (this._pickable) {
  35955. var nbfaces = meshInd.length / 3;
  35956. for (i = 0; i < nbfaces; i++) {
  35957. this.pickedParticles.push({ idx: idx, faceId: i });
  35958. }
  35959. }
  35960. };
  35961. // returns a shape array from positions array
  35962. SolidParticleSystem.prototype._posToShape = function (positions) {
  35963. var shape = [];
  35964. for (var i = 0; i < positions.length; i += 3) {
  35965. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  35966. }
  35967. return shape;
  35968. };
  35969. // returns a shapeUV array from a Vector4 uvs
  35970. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  35971. var shapeUV = [];
  35972. if (uvs) {
  35973. for (var i = 0; i < uvs.length; i++)
  35974. shapeUV.push(uvs[i]);
  35975. }
  35976. return shapeUV;
  35977. };
  35978. // adds a new particle object in the particles array
  35979. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  35980. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  35981. };
  35982. // add solid particles from a shape model in the particles array
  35983. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  35984. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35985. var meshInd = mesh.getIndices();
  35986. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35987. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35988. var shape = this._posToShape(meshPos);
  35989. var shapeUV = this._uvsToShapeUV(meshUV);
  35990. var posfunc = options ? options.positionFunction : null;
  35991. var vtxfunc = options ? options.vertexFunction : null;
  35992. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  35993. // particles
  35994. var idx = this.nbParticles;
  35995. for (var i = 0; i < nb; i++) {
  35996. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  35997. if (this._updatable) {
  35998. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  35999. }
  36000. this._index += shape.length;
  36001. idx++;
  36002. }
  36003. this.nbParticles += nb;
  36004. this._shapeCounter++;
  36005. return this._shapeCounter;
  36006. };
  36007. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36008. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36009. this._resetCopy();
  36010. if (particle._model._positionFunction) {
  36011. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36012. }
  36013. if (this._copy.quaternion) {
  36014. this._quaternion.x = this._copy.quaternion.x;
  36015. this._quaternion.y = this._copy.quaternion.y;
  36016. this._quaternion.z = this._copy.quaternion.z;
  36017. this._quaternion.w = this._copy.quaternion.w;
  36018. }
  36019. else {
  36020. this._yaw = this._copy.rotation.y;
  36021. this._pitch = this._copy.rotation.x;
  36022. this._roll = this._copy.rotation.z;
  36023. this._quaternionRotationYPR();
  36024. }
  36025. this._quaternionToRotationMatrix();
  36026. this._shape = particle._model._shape;
  36027. for (var pt = 0; pt < this._shape.length; pt++) {
  36028. this._vertex.x = this._shape[pt].x;
  36029. this._vertex.y = this._shape[pt].y;
  36030. this._vertex.z = this._shape[pt].z;
  36031. if (particle._model._vertexFunction) {
  36032. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36033. }
  36034. this._vertex.x *= this._copy.scale.x;
  36035. this._vertex.y *= this._copy.scale.y;
  36036. this._vertex.z *= this._copy.scale.z;
  36037. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36038. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36039. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36040. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36041. }
  36042. particle.position.x = 0;
  36043. particle.position.y = 0;
  36044. particle.position.z = 0;
  36045. particle.rotation.x = 0;
  36046. particle.rotation.y = 0;
  36047. particle.rotation.z = 0;
  36048. particle.quaternion = null;
  36049. particle.scale.x = 1;
  36050. particle.scale.y = 1;
  36051. particle.scale.z = 1;
  36052. };
  36053. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36054. SolidParticleSystem.prototype.rebuildMesh = function () {
  36055. for (var p = 0; p < this.particles.length; p++) {
  36056. this._rebuildParticle(this.particles[p]);
  36057. }
  36058. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36059. };
  36060. // sets all the particles : updates the VBO
  36061. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36062. if (start === void 0) { start = 0; }
  36063. if (end === void 0) { end = this.nbParticles - 1; }
  36064. if (update === void 0) { update = true; }
  36065. if (!this._updatable) {
  36066. return;
  36067. }
  36068. // custom beforeUpdate
  36069. this.beforeUpdateParticles(start, end, update);
  36070. this._cam_axisX.x = 1;
  36071. this._cam_axisX.y = 0;
  36072. this._cam_axisX.z = 0;
  36073. this._cam_axisY.x = 0;
  36074. this._cam_axisY.y = 1;
  36075. this._cam_axisY.z = 0;
  36076. this._cam_axisZ.x = 0;
  36077. this._cam_axisZ.y = 0;
  36078. this._cam_axisZ.z = 1;
  36079. // if the particles will always face the camera
  36080. if (this.billboard) {
  36081. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36082. this._yaw = this.mesh.rotation.y;
  36083. this._pitch = this.mesh.rotation.x;
  36084. this._roll = this.mesh.rotation.z;
  36085. this._quaternionRotationYPR();
  36086. this._quaternionToRotationMatrix();
  36087. this._rotMatrix.invertToRef(this._invertMatrix);
  36088. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36089. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36090. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36091. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36092. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36093. this._cam_axisY.normalize();
  36094. this._cam_axisX.normalize();
  36095. this._cam_axisZ.normalize();
  36096. }
  36097. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36098. var idx = 0;
  36099. var index = 0;
  36100. var colidx = 0;
  36101. var colorIndex = 0;
  36102. var uvidx = 0;
  36103. var uvIndex = 0;
  36104. // particle loop
  36105. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36106. for (var p = start; p <= end; p++) {
  36107. this._particle = this.particles[p];
  36108. this._shape = this._particle._model._shape;
  36109. this._shapeUV = this._particle._model._shapeUV;
  36110. // call to custom user function to update the particle properties
  36111. this.updateParticle(this._particle);
  36112. // particle rotation matrix
  36113. if (this.billboard) {
  36114. this._particle.rotation.x = 0.0;
  36115. this._particle.rotation.y = 0.0;
  36116. }
  36117. if (this._computeParticleRotation) {
  36118. if (this._particle.quaternion) {
  36119. this._quaternion.x = this._particle.quaternion.x;
  36120. this._quaternion.y = this._particle.quaternion.y;
  36121. this._quaternion.z = this._particle.quaternion.z;
  36122. this._quaternion.w = this._particle.quaternion.w;
  36123. }
  36124. else {
  36125. this._yaw = this._particle.rotation.y;
  36126. this._pitch = this._particle.rotation.x;
  36127. this._roll = this._particle.rotation.z;
  36128. this._quaternionRotationYPR();
  36129. }
  36130. this._quaternionToRotationMatrix();
  36131. }
  36132. for (var pt = 0; pt < this._shape.length; pt++) {
  36133. idx = index + pt * 3;
  36134. colidx = colorIndex + pt * 4;
  36135. uvidx = uvIndex + pt * 2;
  36136. this._vertex.x = this._shape[pt].x;
  36137. this._vertex.y = this._shape[pt].y;
  36138. this._vertex.z = this._shape[pt].z;
  36139. if (this._computeParticleVertex) {
  36140. this.updateParticleVertex(this._particle, this._vertex, pt);
  36141. }
  36142. // positions
  36143. this._vertex.x *= this._particle.scale.x;
  36144. this._vertex.y *= this._particle.scale.y;
  36145. this._vertex.z *= this._particle.scale.z;
  36146. 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];
  36147. 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;
  36148. 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;
  36149. 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;
  36150. 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;
  36151. 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;
  36152. 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;
  36153. // normals : if the particles can't be morphed then just rotate the normals
  36154. if (!this._computeParticleVertex && !this.billboard) {
  36155. this._normal.x = this._fixedNormal32[idx];
  36156. this._normal.y = this._fixedNormal32[idx + 1];
  36157. this._normal.z = this._fixedNormal32[idx + 2];
  36158. 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];
  36159. 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;
  36160. 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;
  36161. 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;
  36162. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36163. 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;
  36164. 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;
  36165. }
  36166. if (this._computeParticleColor) {
  36167. this._colors32[colidx] = this._particle.color.r;
  36168. this._colors32[colidx + 1] = this._particle.color.g;
  36169. this._colors32[colidx + 2] = this._particle.color.b;
  36170. this._colors32[colidx + 3] = this._particle.color.a;
  36171. }
  36172. if (this._computeParticleTexture) {
  36173. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36174. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36175. }
  36176. }
  36177. index = idx + 3;
  36178. colorIndex = colidx + 4;
  36179. uvIndex = uvidx + 2;
  36180. }
  36181. if (update) {
  36182. if (this._computeParticleColor) {
  36183. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36184. }
  36185. if (this._computeParticleTexture) {
  36186. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36187. }
  36188. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36189. if (!this.mesh.areNormalsFrozen) {
  36190. if (this._computeParticleVertex || this.billboard) {
  36191. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36192. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36193. for (var i = 0; i < this._normals32.length; i++) {
  36194. this._fixedNormal32[i] = this._normals32[i];
  36195. }
  36196. }
  36197. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36198. }
  36199. }
  36200. this.afterUpdateParticles(start, end, update);
  36201. };
  36202. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36203. this._halfroll = this._roll * 0.5;
  36204. this._halfpitch = this._pitch * 0.5;
  36205. this._halfyaw = this._yaw * 0.5;
  36206. this._sinRoll = Math.sin(this._halfroll);
  36207. this._cosRoll = Math.cos(this._halfroll);
  36208. this._sinPitch = Math.sin(this._halfpitch);
  36209. this._cosPitch = Math.cos(this._halfpitch);
  36210. this._sinYaw = Math.sin(this._halfyaw);
  36211. this._cosYaw = Math.cos(this._halfyaw);
  36212. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36213. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36214. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36215. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36216. };
  36217. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36218. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36219. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36220. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36221. this._rotMatrix.m[3] = 0;
  36222. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36223. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36224. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36225. this._rotMatrix.m[7] = 0;
  36226. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36227. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36228. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36229. this._rotMatrix.m[11] = 0;
  36230. this._rotMatrix.m[12] = 0;
  36231. this._rotMatrix.m[13] = 0;
  36232. this._rotMatrix.m[14] = 0;
  36233. this._rotMatrix.m[15] = 1.0;
  36234. };
  36235. // dispose the SPS
  36236. SolidParticleSystem.prototype.dispose = function () {
  36237. this.mesh.dispose();
  36238. this.vars = null;
  36239. // drop references to internal big arrays for the GC
  36240. this._positions = null;
  36241. this._indices = null;
  36242. this._normals = null;
  36243. this._uvs = null;
  36244. this._colors = null;
  36245. this._positions32 = null;
  36246. this._normals32 = null;
  36247. this._fixedNormal32 = null;
  36248. this._uvs32 = null;
  36249. this._colors32 = null;
  36250. this.pickedParticles = null;
  36251. };
  36252. // Visibilty helpers
  36253. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36254. this.mesh.refreshBoundingInfo();
  36255. };
  36256. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36257. // getter and setter
  36258. get: function () {
  36259. return this._alwaysVisible;
  36260. },
  36261. set: function (val) {
  36262. this._alwaysVisible = val;
  36263. this.mesh.alwaysSelectAsActiveMesh = val;
  36264. },
  36265. enumerable: true,
  36266. configurable: true
  36267. });
  36268. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36269. // getters
  36270. get: function () {
  36271. return this._computeParticleRotation;
  36272. },
  36273. // Optimizer setters
  36274. set: function (val) {
  36275. this._computeParticleRotation = val;
  36276. },
  36277. enumerable: true,
  36278. configurable: true
  36279. });
  36280. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36281. get: function () {
  36282. return this._computeParticleColor;
  36283. },
  36284. set: function (val) {
  36285. this._computeParticleColor = val;
  36286. },
  36287. enumerable: true,
  36288. configurable: true
  36289. });
  36290. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36291. get: function () {
  36292. return this._computeParticleTexture;
  36293. },
  36294. set: function (val) {
  36295. this._computeParticleTexture = val;
  36296. },
  36297. enumerable: true,
  36298. configurable: true
  36299. });
  36300. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36301. get: function () {
  36302. return this._computeParticleVertex;
  36303. },
  36304. set: function (val) {
  36305. this._computeParticleVertex = val;
  36306. },
  36307. enumerable: true,
  36308. configurable: true
  36309. });
  36310. // =======================================================================
  36311. // Particle behavior logic
  36312. // these following methods may be overwritten by the user to fit his needs
  36313. // init : sets all particles first values and calls updateParticle to set them in space
  36314. // can be overwritten by the user
  36315. SolidParticleSystem.prototype.initParticles = function () {
  36316. };
  36317. // recycles a particle : can by overwritten by the user
  36318. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36319. return particle;
  36320. };
  36321. // updates a particle : can be overwritten by the user
  36322. // will be called on each particle by setParticles() :
  36323. // ex : just set a particle position or velocity and recycle conditions
  36324. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36325. return particle;
  36326. };
  36327. // updates a vertex of a particle : can be overwritten by the user
  36328. // will be called on each vertex particle by setParticles() :
  36329. // particle : the current particle
  36330. // vertex : the current index of the current particle
  36331. // pt : the index of the current vertex in the particle shape
  36332. // ex : just set a vertex particle position
  36333. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36334. return vertex;
  36335. };
  36336. // will be called before any other treatment by setParticles()
  36337. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36338. };
  36339. // will be called after all setParticles() treatments
  36340. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36341. };
  36342. return SolidParticleSystem;
  36343. })();
  36344. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36345. })(BABYLON || (BABYLON = {}));
  36346. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  36347. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,S=e*c-a*m,D=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*S+o*D)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*S-n*Z+o*W)*b,t.m[15]=(i*D-n*N+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;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,\nn.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36348. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36349. module.exports = BABYLON;
  36350. };